pdf.js 486 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. (function webpackUniversalModuleDefinition(root, factory) {
  23. if(typeof exports === 'object' && typeof module === 'object')
  24. module.exports = factory();
  25. else if(typeof define === 'function' && define.amd)
  26. define("pdfjs-dist/build/pdf", [], factory);
  27. else if(typeof exports === 'object')
  28. exports["pdfjs-dist/build/pdf"] = factory();
  29. else
  30. root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
  31. })(globalThis, () => {
  32. return /******/ (() => { // webpackBootstrap
  33. /******/ "use strict";
  34. /******/ var __webpack_modules__ = ([
  35. /* 0 */,
  36. /* 1 */
  37. /***/ ((__unused_webpack_module, exports) => {
  38. Object.defineProperty(exports, "__esModule", ({
  39. value: true
  40. }));
  41. exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
  42. exports.arrayByteLength = arrayByteLength;
  43. exports.arraysToBytes = arraysToBytes;
  44. exports.assert = assert;
  45. exports.bytesToString = bytesToString;
  46. exports.createPromiseCapability = createPromiseCapability;
  47. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  48. exports.getModificationDate = getModificationDate;
  49. exports.getVerbosityLevel = getVerbosityLevel;
  50. exports.info = info;
  51. exports.isArrayBuffer = isArrayBuffer;
  52. exports.isArrayEqual = isArrayEqual;
  53. exports.objectFromMap = objectFromMap;
  54. exports.objectSize = objectSize;
  55. exports.setVerbosityLevel = setVerbosityLevel;
  56. exports.shadow = shadow;
  57. exports.string32 = string32;
  58. exports.stringToBytes = stringToBytes;
  59. exports.stringToPDFString = stringToPDFString;
  60. exports.stringToUTF8String = stringToUTF8String;
  61. exports.unreachable = unreachable;
  62. exports.utf8StringToString = utf8StringToString;
  63. exports.warn = warn;
  64. ;
  65. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  66. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  67. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  68. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  69. const LINE_FACTOR = 1.35;
  70. exports.LINE_FACTOR = LINE_FACTOR;
  71. const LINE_DESCENT_FACTOR = 0.35;
  72. exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
  73. const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
  74. exports.BASELINE_FACTOR = BASELINE_FACTOR;
  75. const RenderingIntentFlag = {
  76. ANY: 0x01,
  77. DISPLAY: 0x02,
  78. PRINT: 0x04,
  79. SAVE: 0x08,
  80. ANNOTATIONS_FORMS: 0x10,
  81. ANNOTATIONS_STORAGE: 0x20,
  82. ANNOTATIONS_DISABLE: 0x40,
  83. OPLIST: 0x100
  84. };
  85. exports.RenderingIntentFlag = RenderingIntentFlag;
  86. const AnnotationMode = {
  87. DISABLE: 0,
  88. ENABLE: 1,
  89. ENABLE_FORMS: 2,
  90. ENABLE_STORAGE: 3
  91. };
  92. exports.AnnotationMode = AnnotationMode;
  93. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  94. exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
  95. const AnnotationEditorType = {
  96. DISABLE: -1,
  97. NONE: 0,
  98. FREETEXT: 3,
  99. INK: 15
  100. };
  101. exports.AnnotationEditorType = AnnotationEditorType;
  102. const AnnotationEditorParamsType = {
  103. FREETEXT_SIZE: 1,
  104. FREETEXT_COLOR: 2,
  105. FREETEXT_OPACITY: 3,
  106. INK_COLOR: 11,
  107. INK_THICKNESS: 12,
  108. INK_OPACITY: 13
  109. };
  110. exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
  111. const PermissionFlag = {
  112. PRINT: 0x04,
  113. MODIFY_CONTENTS: 0x08,
  114. COPY: 0x10,
  115. MODIFY_ANNOTATIONS: 0x20,
  116. FILL_INTERACTIVE_FORMS: 0x100,
  117. COPY_FOR_ACCESSIBILITY: 0x200,
  118. ASSEMBLE: 0x400,
  119. PRINT_HIGH_QUALITY: 0x800
  120. };
  121. exports.PermissionFlag = PermissionFlag;
  122. const TextRenderingMode = {
  123. FILL: 0,
  124. STROKE: 1,
  125. FILL_STROKE: 2,
  126. INVISIBLE: 3,
  127. FILL_ADD_TO_PATH: 4,
  128. STROKE_ADD_TO_PATH: 5,
  129. FILL_STROKE_ADD_TO_PATH: 6,
  130. ADD_TO_PATH: 7,
  131. FILL_STROKE_MASK: 3,
  132. ADD_TO_PATH_FLAG: 4
  133. };
  134. exports.TextRenderingMode = TextRenderingMode;
  135. const ImageKind = {
  136. GRAYSCALE_1BPP: 1,
  137. RGB_24BPP: 2,
  138. RGBA_32BPP: 3
  139. };
  140. exports.ImageKind = ImageKind;
  141. const AnnotationType = {
  142. TEXT: 1,
  143. LINK: 2,
  144. FREETEXT: 3,
  145. LINE: 4,
  146. SQUARE: 5,
  147. CIRCLE: 6,
  148. POLYGON: 7,
  149. POLYLINE: 8,
  150. HIGHLIGHT: 9,
  151. UNDERLINE: 10,
  152. SQUIGGLY: 11,
  153. STRIKEOUT: 12,
  154. STAMP: 13,
  155. CARET: 14,
  156. INK: 15,
  157. POPUP: 16,
  158. FILEATTACHMENT: 17,
  159. SOUND: 18,
  160. MOVIE: 19,
  161. WIDGET: 20,
  162. SCREEN: 21,
  163. PRINTERMARK: 22,
  164. TRAPNET: 23,
  165. WATERMARK: 24,
  166. THREED: 25,
  167. REDACT: 26
  168. };
  169. exports.AnnotationType = AnnotationType;
  170. const AnnotationStateModelType = {
  171. MARKED: "Marked",
  172. REVIEW: "Review"
  173. };
  174. exports.AnnotationStateModelType = AnnotationStateModelType;
  175. const AnnotationMarkedState = {
  176. MARKED: "Marked",
  177. UNMARKED: "Unmarked"
  178. };
  179. exports.AnnotationMarkedState = AnnotationMarkedState;
  180. const AnnotationReviewState = {
  181. ACCEPTED: "Accepted",
  182. REJECTED: "Rejected",
  183. CANCELLED: "Cancelled",
  184. COMPLETED: "Completed",
  185. NONE: "None"
  186. };
  187. exports.AnnotationReviewState = AnnotationReviewState;
  188. const AnnotationReplyType = {
  189. GROUP: "Group",
  190. REPLY: "R"
  191. };
  192. exports.AnnotationReplyType = AnnotationReplyType;
  193. const AnnotationFlag = {
  194. INVISIBLE: 0x01,
  195. HIDDEN: 0x02,
  196. PRINT: 0x04,
  197. NOZOOM: 0x08,
  198. NOROTATE: 0x10,
  199. NOVIEW: 0x20,
  200. READONLY: 0x40,
  201. LOCKED: 0x80,
  202. TOGGLENOVIEW: 0x100,
  203. LOCKEDCONTENTS: 0x200
  204. };
  205. exports.AnnotationFlag = AnnotationFlag;
  206. const AnnotationFieldFlag = {
  207. READONLY: 0x0000001,
  208. REQUIRED: 0x0000002,
  209. NOEXPORT: 0x0000004,
  210. MULTILINE: 0x0001000,
  211. PASSWORD: 0x0002000,
  212. NOTOGGLETOOFF: 0x0004000,
  213. RADIO: 0x0008000,
  214. PUSHBUTTON: 0x0010000,
  215. COMBO: 0x0020000,
  216. EDIT: 0x0040000,
  217. SORT: 0x0080000,
  218. FILESELECT: 0x0100000,
  219. MULTISELECT: 0x0200000,
  220. DONOTSPELLCHECK: 0x0400000,
  221. DONOTSCROLL: 0x0800000,
  222. COMB: 0x1000000,
  223. RICHTEXT: 0x2000000,
  224. RADIOSINUNISON: 0x2000000,
  225. COMMITONSELCHANGE: 0x4000000
  226. };
  227. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  228. const AnnotationBorderStyleType = {
  229. SOLID: 1,
  230. DASHED: 2,
  231. BEVELED: 3,
  232. INSET: 4,
  233. UNDERLINE: 5
  234. };
  235. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  236. const AnnotationActionEventType = {
  237. E: "Mouse Enter",
  238. X: "Mouse Exit",
  239. D: "Mouse Down",
  240. U: "Mouse Up",
  241. Fo: "Focus",
  242. Bl: "Blur",
  243. PO: "PageOpen",
  244. PC: "PageClose",
  245. PV: "PageVisible",
  246. PI: "PageInvisible",
  247. K: "Keystroke",
  248. F: "Format",
  249. V: "Validate",
  250. C: "Calculate"
  251. };
  252. exports.AnnotationActionEventType = AnnotationActionEventType;
  253. const DocumentActionEventType = {
  254. WC: "WillClose",
  255. WS: "WillSave",
  256. DS: "DidSave",
  257. WP: "WillPrint",
  258. DP: "DidPrint"
  259. };
  260. exports.DocumentActionEventType = DocumentActionEventType;
  261. const PageActionEventType = {
  262. O: "PageOpen",
  263. C: "PageClose"
  264. };
  265. exports.PageActionEventType = PageActionEventType;
  266. const StreamType = {
  267. UNKNOWN: "UNKNOWN",
  268. FLATE: "FLATE",
  269. LZW: "LZW",
  270. DCT: "DCT",
  271. JPX: "JPX",
  272. JBIG: "JBIG",
  273. A85: "A85",
  274. AHX: "AHX",
  275. CCF: "CCF",
  276. RLX: "RLX"
  277. };
  278. exports.StreamType = StreamType;
  279. const FontType = {
  280. UNKNOWN: "UNKNOWN",
  281. TYPE1: "TYPE1",
  282. TYPE1STANDARD: "TYPE1STANDARD",
  283. TYPE1C: "TYPE1C",
  284. CIDFONTTYPE0: "CIDFONTTYPE0",
  285. CIDFONTTYPE0C: "CIDFONTTYPE0C",
  286. TRUETYPE: "TRUETYPE",
  287. CIDFONTTYPE2: "CIDFONTTYPE2",
  288. TYPE3: "TYPE3",
  289. OPENTYPE: "OPENTYPE",
  290. TYPE0: "TYPE0",
  291. MMTYPE1: "MMTYPE1"
  292. };
  293. exports.FontType = FontType;
  294. const VerbosityLevel = {
  295. ERRORS: 0,
  296. WARNINGS: 1,
  297. INFOS: 5
  298. };
  299. exports.VerbosityLevel = VerbosityLevel;
  300. const CMapCompressionType = {
  301. NONE: 0,
  302. BINARY: 1
  303. };
  304. exports.CMapCompressionType = CMapCompressionType;
  305. const OPS = {
  306. dependency: 1,
  307. setLineWidth: 2,
  308. setLineCap: 3,
  309. setLineJoin: 4,
  310. setMiterLimit: 5,
  311. setDash: 6,
  312. setRenderingIntent: 7,
  313. setFlatness: 8,
  314. setGState: 9,
  315. save: 10,
  316. restore: 11,
  317. transform: 12,
  318. moveTo: 13,
  319. lineTo: 14,
  320. curveTo: 15,
  321. curveTo2: 16,
  322. curveTo3: 17,
  323. closePath: 18,
  324. rectangle: 19,
  325. stroke: 20,
  326. closeStroke: 21,
  327. fill: 22,
  328. eoFill: 23,
  329. fillStroke: 24,
  330. eoFillStroke: 25,
  331. closeFillStroke: 26,
  332. closeEOFillStroke: 27,
  333. endPath: 28,
  334. clip: 29,
  335. eoClip: 30,
  336. beginText: 31,
  337. endText: 32,
  338. setCharSpacing: 33,
  339. setWordSpacing: 34,
  340. setHScale: 35,
  341. setLeading: 36,
  342. setFont: 37,
  343. setTextRenderingMode: 38,
  344. setTextRise: 39,
  345. moveText: 40,
  346. setLeadingMoveText: 41,
  347. setTextMatrix: 42,
  348. nextLine: 43,
  349. showText: 44,
  350. showSpacedText: 45,
  351. nextLineShowText: 46,
  352. nextLineSetSpacingShowText: 47,
  353. setCharWidth: 48,
  354. setCharWidthAndBounds: 49,
  355. setStrokeColorSpace: 50,
  356. setFillColorSpace: 51,
  357. setStrokeColor: 52,
  358. setStrokeColorN: 53,
  359. setFillColor: 54,
  360. setFillColorN: 55,
  361. setStrokeGray: 56,
  362. setFillGray: 57,
  363. setStrokeRGBColor: 58,
  364. setFillRGBColor: 59,
  365. setStrokeCMYKColor: 60,
  366. setFillCMYKColor: 61,
  367. shadingFill: 62,
  368. beginInlineImage: 63,
  369. beginImageData: 64,
  370. endInlineImage: 65,
  371. paintXObject: 66,
  372. markPoint: 67,
  373. markPointProps: 68,
  374. beginMarkedContent: 69,
  375. beginMarkedContentProps: 70,
  376. endMarkedContent: 71,
  377. beginCompat: 72,
  378. endCompat: 73,
  379. paintFormXObjectBegin: 74,
  380. paintFormXObjectEnd: 75,
  381. beginGroup: 76,
  382. endGroup: 77,
  383. beginAnnotation: 80,
  384. endAnnotation: 81,
  385. paintImageMaskXObject: 83,
  386. paintImageMaskXObjectGroup: 84,
  387. paintImageXObject: 85,
  388. paintInlineImageXObject: 86,
  389. paintInlineImageXObjectGroup: 87,
  390. paintImageXObjectRepeat: 88,
  391. paintImageMaskXObjectRepeat: 89,
  392. paintSolidColorImageMask: 90,
  393. constructPath: 91
  394. };
  395. exports.OPS = OPS;
  396. const UNSUPPORTED_FEATURES = {
  397. forms: "forms",
  398. javaScript: "javaScript",
  399. signatures: "signatures",
  400. smask: "smask",
  401. shadingPattern: "shadingPattern",
  402. errorTilingPattern: "errorTilingPattern",
  403. errorExtGState: "errorExtGState",
  404. errorXObject: "errorXObject",
  405. errorFontLoadType3: "errorFontLoadType3",
  406. errorFontState: "errorFontState",
  407. errorFontMissing: "errorFontMissing",
  408. errorFontTranslate: "errorFontTranslate",
  409. errorColorSpace: "errorColorSpace",
  410. errorOperatorList: "errorOperatorList",
  411. errorFontToUnicode: "errorFontToUnicode",
  412. errorFontLoadNative: "errorFontLoadNative",
  413. errorFontBuildPath: "errorFontBuildPath",
  414. errorFontGetPath: "errorFontGetPath",
  415. errorMarkedContent: "errorMarkedContent",
  416. errorContentSubStream: "errorContentSubStream"
  417. };
  418. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  419. const PasswordResponses = {
  420. NEED_PASSWORD: 1,
  421. INCORRECT_PASSWORD: 2
  422. };
  423. exports.PasswordResponses = PasswordResponses;
  424. let verbosity = VerbosityLevel.WARNINGS;
  425. function setVerbosityLevel(level) {
  426. if (Number.isInteger(level)) {
  427. verbosity = level;
  428. }
  429. }
  430. function getVerbosityLevel() {
  431. return verbosity;
  432. }
  433. function info(msg) {
  434. if (verbosity >= VerbosityLevel.INFOS) {
  435. console.log(`Info: ${msg}`);
  436. }
  437. }
  438. function warn(msg) {
  439. if (verbosity >= VerbosityLevel.WARNINGS) {
  440. console.log(`Warning: ${msg}`);
  441. }
  442. }
  443. function unreachable(msg) {
  444. throw new Error(msg);
  445. }
  446. function assert(cond, msg) {
  447. if (!cond) {
  448. unreachable(msg);
  449. }
  450. }
  451. function _isValidProtocol(url) {
  452. if (!url) {
  453. return false;
  454. }
  455. switch (url.protocol) {
  456. case "http:":
  457. case "https:":
  458. case "ftp:":
  459. case "mailto:":
  460. case "tel:":
  461. return true;
  462. default:
  463. return false;
  464. }
  465. }
  466. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  467. if (!url) {
  468. return null;
  469. }
  470. try {
  471. if (options && typeof url === "string") {
  472. if (options.addDefaultProtocol && url.startsWith("www.")) {
  473. const dots = url.match(/\./g);
  474. if (dots && dots.length >= 2) {
  475. url = `http://${url}`;
  476. }
  477. }
  478. if (options.tryConvertEncoding) {
  479. try {
  480. url = stringToUTF8String(url);
  481. } catch (ex) {}
  482. }
  483. }
  484. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  485. if (_isValidProtocol(absoluteUrl)) {
  486. return absoluteUrl;
  487. }
  488. } catch (ex) {}
  489. return null;
  490. }
  491. function shadow(obj, prop, value, nonSerializable = false) {
  492. Object.defineProperty(obj, prop, {
  493. value,
  494. enumerable: !nonSerializable,
  495. configurable: true,
  496. writable: false
  497. });
  498. return value;
  499. }
  500. const BaseException = function BaseExceptionClosure() {
  501. function BaseException(message, name) {
  502. if (this.constructor === BaseException) {
  503. unreachable("Cannot initialize BaseException.");
  504. }
  505. this.message = message;
  506. this.name = name;
  507. }
  508. BaseException.prototype = new Error();
  509. BaseException.constructor = BaseException;
  510. return BaseException;
  511. }();
  512. exports.BaseException = BaseException;
  513. class PasswordException extends BaseException {
  514. constructor(msg, code) {
  515. super(msg, "PasswordException");
  516. this.code = code;
  517. }
  518. }
  519. exports.PasswordException = PasswordException;
  520. class UnknownErrorException extends BaseException {
  521. constructor(msg, details) {
  522. super(msg, "UnknownErrorException");
  523. this.details = details;
  524. }
  525. }
  526. exports.UnknownErrorException = UnknownErrorException;
  527. class InvalidPDFException extends BaseException {
  528. constructor(msg) {
  529. super(msg, "InvalidPDFException");
  530. }
  531. }
  532. exports.InvalidPDFException = InvalidPDFException;
  533. class MissingPDFException extends BaseException {
  534. constructor(msg) {
  535. super(msg, "MissingPDFException");
  536. }
  537. }
  538. exports.MissingPDFException = MissingPDFException;
  539. class UnexpectedResponseException extends BaseException {
  540. constructor(msg, status) {
  541. super(msg, "UnexpectedResponseException");
  542. this.status = status;
  543. }
  544. }
  545. exports.UnexpectedResponseException = UnexpectedResponseException;
  546. class FormatError extends BaseException {
  547. constructor(msg) {
  548. super(msg, "FormatError");
  549. }
  550. }
  551. exports.FormatError = FormatError;
  552. class AbortException extends BaseException {
  553. constructor(msg) {
  554. super(msg, "AbortException");
  555. }
  556. }
  557. exports.AbortException = AbortException;
  558. function bytesToString(bytes) {
  559. if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
  560. unreachable("Invalid argument for bytesToString");
  561. }
  562. const length = bytes.length;
  563. const MAX_ARGUMENT_COUNT = 8192;
  564. if (length < MAX_ARGUMENT_COUNT) {
  565. return String.fromCharCode.apply(null, bytes);
  566. }
  567. const strBuf = [];
  568. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  569. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  570. const chunk = bytes.subarray(i, chunkEnd);
  571. strBuf.push(String.fromCharCode.apply(null, chunk));
  572. }
  573. return strBuf.join("");
  574. }
  575. function stringToBytes(str) {
  576. if (typeof str !== "string") {
  577. unreachable("Invalid argument for stringToBytes");
  578. }
  579. const length = str.length;
  580. const bytes = new Uint8Array(length);
  581. for (let i = 0; i < length; ++i) {
  582. bytes[i] = str.charCodeAt(i) & 0xff;
  583. }
  584. return bytes;
  585. }
  586. function arrayByteLength(arr) {
  587. if (arr.length !== undefined) {
  588. return arr.length;
  589. }
  590. if (arr.byteLength !== undefined) {
  591. return arr.byteLength;
  592. }
  593. unreachable("Invalid argument for arrayByteLength");
  594. }
  595. function arraysToBytes(arr) {
  596. const length = arr.length;
  597. if (length === 1 && arr[0] instanceof Uint8Array) {
  598. return arr[0];
  599. }
  600. let resultLength = 0;
  601. for (let i = 0; i < length; i++) {
  602. resultLength += arrayByteLength(arr[i]);
  603. }
  604. let pos = 0;
  605. const data = new Uint8Array(resultLength);
  606. for (let i = 0; i < length; i++) {
  607. let item = arr[i];
  608. if (!(item instanceof Uint8Array)) {
  609. if (typeof item === "string") {
  610. item = stringToBytes(item);
  611. } else {
  612. item = new Uint8Array(item);
  613. }
  614. }
  615. const itemLength = item.byteLength;
  616. data.set(item, pos);
  617. pos += itemLength;
  618. }
  619. return data;
  620. }
  621. function string32(value) {
  622. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  623. }
  624. function objectSize(obj) {
  625. return Object.keys(obj).length;
  626. }
  627. function objectFromMap(map) {
  628. const obj = Object.create(null);
  629. for (const [key, value] of map) {
  630. obj[key] = value;
  631. }
  632. return obj;
  633. }
  634. function isLittleEndian() {
  635. const buffer8 = new Uint8Array(4);
  636. buffer8[0] = 1;
  637. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  638. return view32[0] === 1;
  639. }
  640. function isEvalSupported() {
  641. try {
  642. new Function("");
  643. return true;
  644. } catch (e) {
  645. return false;
  646. }
  647. }
  648. class FeatureTest {
  649. static get isLittleEndian() {
  650. return shadow(this, "isLittleEndian", isLittleEndian());
  651. }
  652. static get isEvalSupported() {
  653. return shadow(this, "isEvalSupported", isEvalSupported());
  654. }
  655. static get isOffscreenCanvasSupported() {
  656. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  657. }
  658. }
  659. exports.FeatureTest = FeatureTest;
  660. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  661. class Util {
  662. static makeHexColor(r, g, b) {
  663. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  664. }
  665. static scaleMinMax(transform, minMax) {
  666. let temp;
  667. if (transform[0]) {
  668. if (transform[0] < 0) {
  669. temp = minMax[0];
  670. minMax[0] = minMax[1];
  671. minMax[1] = temp;
  672. }
  673. minMax[0] *= transform[0];
  674. minMax[1] *= transform[0];
  675. if (transform[3] < 0) {
  676. temp = minMax[2];
  677. minMax[2] = minMax[3];
  678. minMax[3] = temp;
  679. }
  680. minMax[2] *= transform[3];
  681. minMax[3] *= transform[3];
  682. } else {
  683. temp = minMax[0];
  684. minMax[0] = minMax[2];
  685. minMax[2] = temp;
  686. temp = minMax[1];
  687. minMax[1] = minMax[3];
  688. minMax[3] = temp;
  689. if (transform[1] < 0) {
  690. temp = minMax[2];
  691. minMax[2] = minMax[3];
  692. minMax[3] = temp;
  693. }
  694. minMax[2] *= transform[1];
  695. minMax[3] *= transform[1];
  696. if (transform[2] < 0) {
  697. temp = minMax[0];
  698. minMax[0] = minMax[1];
  699. minMax[1] = temp;
  700. }
  701. minMax[0] *= transform[2];
  702. minMax[1] *= transform[2];
  703. }
  704. minMax[0] += transform[4];
  705. minMax[1] += transform[4];
  706. minMax[2] += transform[5];
  707. minMax[3] += transform[5];
  708. }
  709. static transform(m1, m2) {
  710. return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
  711. }
  712. static applyTransform(p, m) {
  713. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  714. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  715. return [xt, yt];
  716. }
  717. static applyInverseTransform(p, m) {
  718. const d = m[0] * m[3] - m[1] * m[2];
  719. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  720. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  721. return [xt, yt];
  722. }
  723. static getAxialAlignedBoundingBox(r, m) {
  724. const p1 = Util.applyTransform(r, m);
  725. const p2 = Util.applyTransform(r.slice(2, 4), m);
  726. const p3 = Util.applyTransform([r[0], r[3]], m);
  727. const p4 = Util.applyTransform([r[2], r[1]], m);
  728. return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
  729. }
  730. static inverseTransform(m) {
  731. const d = m[0] * m[3] - m[1] * m[2];
  732. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  733. }
  734. static singularValueDecompose2dScale(m) {
  735. const transpose = [m[0], m[2], m[1], m[3]];
  736. const a = m[0] * transpose[0] + m[1] * transpose[2];
  737. const b = m[0] * transpose[1] + m[1] * transpose[3];
  738. const c = m[2] * transpose[0] + m[3] * transpose[2];
  739. const d = m[2] * transpose[1] + m[3] * transpose[3];
  740. const first = (a + d) / 2;
  741. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  742. const sx = first + second || 1;
  743. const sy = first - second || 1;
  744. return [Math.sqrt(sx), Math.sqrt(sy)];
  745. }
  746. static normalizeRect(rect) {
  747. const r = rect.slice(0);
  748. if (rect[0] > rect[2]) {
  749. r[0] = rect[2];
  750. r[2] = rect[0];
  751. }
  752. if (rect[1] > rect[3]) {
  753. r[1] = rect[3];
  754. r[3] = rect[1];
  755. }
  756. return r;
  757. }
  758. static intersect(rect1, rect2) {
  759. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  760. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  761. if (xLow > xHigh) {
  762. return null;
  763. }
  764. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  765. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  766. if (yLow > yHigh) {
  767. return null;
  768. }
  769. return [xLow, yLow, xHigh, yHigh];
  770. }
  771. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
  772. const tvalues = [],
  773. bounds = [[], []];
  774. let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  775. for (let i = 0; i < 2; ++i) {
  776. if (i === 0) {
  777. b = 6 * x0 - 12 * x1 + 6 * x2;
  778. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  779. c = 3 * x1 - 3 * x0;
  780. } else {
  781. b = 6 * y0 - 12 * y1 + 6 * y2;
  782. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  783. c = 3 * y1 - 3 * y0;
  784. }
  785. if (Math.abs(a) < 1e-12) {
  786. if (Math.abs(b) < 1e-12) {
  787. continue;
  788. }
  789. t = -c / b;
  790. if (0 < t && t < 1) {
  791. tvalues.push(t);
  792. }
  793. continue;
  794. }
  795. b2ac = b * b - 4 * c * a;
  796. sqrtb2ac = Math.sqrt(b2ac);
  797. if (b2ac < 0) {
  798. continue;
  799. }
  800. t1 = (-b + sqrtb2ac) / (2 * a);
  801. if (0 < t1 && t1 < 1) {
  802. tvalues.push(t1);
  803. }
  804. t2 = (-b - sqrtb2ac) / (2 * a);
  805. if (0 < t2 && t2 < 1) {
  806. tvalues.push(t2);
  807. }
  808. }
  809. let j = tvalues.length,
  810. mt;
  811. const jlen = j;
  812. while (j--) {
  813. t = tvalues[j];
  814. mt = 1 - t;
  815. bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
  816. bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
  817. }
  818. bounds[0][jlen] = x0;
  819. bounds[1][jlen] = y0;
  820. bounds[0][jlen + 1] = x3;
  821. bounds[1][jlen + 1] = y3;
  822. bounds[0].length = bounds[1].length = jlen + 2;
  823. return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  824. }
  825. }
  826. exports.Util = Util;
  827. const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
  828. function stringToPDFString(str) {
  829. if (str[0] >= "\xEF") {
  830. let encoding;
  831. if (str[0] === "\xFE" && str[1] === "\xFF") {
  832. encoding = "utf-16be";
  833. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  834. encoding = "utf-16le";
  835. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  836. encoding = "utf-8";
  837. }
  838. if (encoding) {
  839. try {
  840. const decoder = new TextDecoder(encoding, {
  841. fatal: true
  842. });
  843. const buffer = stringToBytes(str);
  844. return decoder.decode(buffer);
  845. } catch (ex) {
  846. warn(`stringToPDFString: "${ex}".`);
  847. }
  848. }
  849. }
  850. const strBuf = [];
  851. for (let i = 0, ii = str.length; i < ii; i++) {
  852. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  853. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  854. }
  855. return strBuf.join("");
  856. }
  857. function stringToUTF8String(str) {
  858. return decodeURIComponent(escape(str));
  859. }
  860. function utf8StringToString(str) {
  861. return unescape(encodeURIComponent(str));
  862. }
  863. function isArrayBuffer(v) {
  864. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  865. }
  866. function isArrayEqual(arr1, arr2) {
  867. if (arr1.length !== arr2.length) {
  868. return false;
  869. }
  870. for (let i = 0, ii = arr1.length; i < ii; i++) {
  871. if (arr1[i] !== arr2[i]) {
  872. return false;
  873. }
  874. }
  875. return true;
  876. }
  877. function getModificationDate(date = new Date()) {
  878. 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")];
  879. return buffer.join("");
  880. }
  881. function createPromiseCapability() {
  882. const capability = Object.create(null);
  883. let isSettled = false;
  884. Object.defineProperty(capability, "settled", {
  885. get() {
  886. return isSettled;
  887. }
  888. });
  889. capability.promise = new Promise(function (resolve, reject) {
  890. capability.resolve = function (data) {
  891. isSettled = true;
  892. resolve(data);
  893. };
  894. capability.reject = function (reason) {
  895. isSettled = true;
  896. reject(reason);
  897. };
  898. });
  899. return capability;
  900. }
  901. /***/ }),
  902. /* 2 */
  903. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  904. Object.defineProperty(exports, "__esModule", ({
  905. value: true
  906. }));
  907. exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
  908. exports.getDocument = getDocument;
  909. exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
  910. exports.version = void 0;
  911. var _util = __w_pdfjs_require__(1);
  912. var _annotation_storage = __w_pdfjs_require__(3);
  913. var _display_utils = __w_pdfjs_require__(6);
  914. var _font_loader = __w_pdfjs_require__(9);
  915. var _canvas = __w_pdfjs_require__(10);
  916. var _worker_options = __w_pdfjs_require__(14);
  917. var _is_node = __w_pdfjs_require__(12);
  918. var _message_handler = __w_pdfjs_require__(15);
  919. var _metadata = __w_pdfjs_require__(16);
  920. var _optional_content_config = __w_pdfjs_require__(17);
  921. var _transport_stream = __w_pdfjs_require__(18);
  922. var _xfa_text = __w_pdfjs_require__(19);
  923. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  924. const RENDERING_CANCELLED_TIMEOUT = 100;
  925. let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
  926. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  927. let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
  928. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  929. let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
  930. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  931. if (_is_node.isNodeJS) {
  932. const {
  933. NodeCanvasFactory,
  934. NodeCMapReaderFactory,
  935. NodeStandardFontDataFactory
  936. } = __w_pdfjs_require__(20);
  937. exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
  938. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
  939. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
  940. }
  941. let createPDFNetworkStream;
  942. function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
  943. createPDFNetworkStream = pdfNetworkStreamFactory;
  944. }
  945. function getDocument(src) {
  946. const task = new PDFDocumentLoadingTask();
  947. let source;
  948. if (typeof src === "string" || src instanceof URL) {
  949. source = {
  950. url: src
  951. };
  952. } else if ((0, _util.isArrayBuffer)(src)) {
  953. source = {
  954. data: src
  955. };
  956. } else if (src instanceof PDFDataRangeTransport) {
  957. source = {
  958. range: src
  959. };
  960. } else {
  961. if (typeof src !== "object") {
  962. throw new Error("Invalid parameter in getDocument, " + "need either string, URL, TypedArray, or parameter object.");
  963. }
  964. if (!src.url && !src.data && !src.range) {
  965. throw new Error("Invalid parameter object: need either .data, .range or .url");
  966. }
  967. source = src;
  968. }
  969. const params = Object.create(null);
  970. let rangeTransport = null,
  971. worker = null;
  972. for (const key in source) {
  973. const value = source[key];
  974. switch (key) {
  975. case "url":
  976. if (typeof window !== "undefined") {
  977. try {
  978. params[key] = new URL(value, window.location).href;
  979. continue;
  980. } catch (ex) {
  981. (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
  982. }
  983. } else if (typeof value === "string" || value instanceof URL) {
  984. params[key] = value.toString();
  985. continue;
  986. }
  987. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  988. case "range":
  989. rangeTransport = value;
  990. continue;
  991. case "worker":
  992. worker = value;
  993. continue;
  994. case "data":
  995. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
  996. params[key] = new Uint8Array(value);
  997. } else if (value instanceof Uint8Array) {
  998. break;
  999. } else if (typeof value === "string") {
  1000. params[key] = (0, _util.stringToBytes)(value);
  1001. } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
  1002. params[key] = new Uint8Array(value);
  1003. } else if ((0, _util.isArrayBuffer)(value)) {
  1004. params[key] = new Uint8Array(value);
  1005. } else {
  1006. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  1007. }
  1008. continue;
  1009. }
  1010. params[key] = value;
  1011. }
  1012. params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
  1013. params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
  1014. params.ignoreErrors = params.stopAtErrors !== true;
  1015. params.fontExtraProperties = params.fontExtraProperties === true;
  1016. params.pdfBug = params.pdfBug === true;
  1017. params.enableXfa = params.enableXfa === true;
  1018. if (!Number.isInteger(params.rangeChunkSize) || params.rangeChunkSize < 1) {
  1019. params.rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE;
  1020. }
  1021. if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
  1022. params.docBaseUrl = null;
  1023. }
  1024. if (!Number.isInteger(params.maxImageSize) || params.maxImageSize < -1) {
  1025. params.maxImageSize = -1;
  1026. }
  1027. if (typeof params.cMapUrl !== "string") {
  1028. params.cMapUrl = null;
  1029. }
  1030. if (typeof params.standardFontDataUrl !== "string") {
  1031. params.standardFontDataUrl = null;
  1032. }
  1033. if (typeof params.useWorkerFetch !== "boolean") {
  1034. params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
  1035. }
  1036. if (typeof params.isEvalSupported !== "boolean") {
  1037. params.isEvalSupported = true;
  1038. }
  1039. if (typeof params.isOffscreenCanvasSupported !== "boolean") {
  1040. params.isOffscreenCanvasSupported = !_is_node.isNodeJS;
  1041. }
  1042. if (typeof params.disableFontFace !== "boolean") {
  1043. params.disableFontFace = _is_node.isNodeJS;
  1044. }
  1045. if (typeof params.useSystemFonts !== "boolean") {
  1046. params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
  1047. }
  1048. if (typeof params.ownerDocument !== "object" || params.ownerDocument === null) {
  1049. params.ownerDocument = globalThis.document;
  1050. }
  1051. if (typeof params.disableRange !== "boolean") {
  1052. params.disableRange = false;
  1053. }
  1054. if (typeof params.disableStream !== "boolean") {
  1055. params.disableStream = false;
  1056. }
  1057. if (typeof params.disableAutoFetch !== "boolean") {
  1058. params.disableAutoFetch = false;
  1059. }
  1060. (0, _util.setVerbosityLevel)(params.verbosity);
  1061. if (!worker) {
  1062. const workerParams = {
  1063. verbosity: params.verbosity,
  1064. port: _worker_options.GlobalWorkerOptions.workerPort
  1065. };
  1066. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  1067. task._worker = worker;
  1068. }
  1069. const docId = task.docId;
  1070. worker.promise.then(function () {
  1071. if (task.destroyed) {
  1072. throw new Error("Loading aborted");
  1073. }
  1074. const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
  1075. const networkStreamPromise = new Promise(function (resolve) {
  1076. let networkStream;
  1077. if (rangeTransport) {
  1078. networkStream = new _transport_stream.PDFDataTransportStream({
  1079. length: params.length,
  1080. initialData: params.initialData,
  1081. progressiveDone: params.progressiveDone,
  1082. contentDispositionFilename: params.contentDispositionFilename,
  1083. disableRange: params.disableRange,
  1084. disableStream: params.disableStream
  1085. }, rangeTransport);
  1086. } else if (!params.data) {
  1087. networkStream = createPDFNetworkStream({
  1088. url: params.url,
  1089. length: params.length,
  1090. httpHeaders: params.httpHeaders,
  1091. withCredentials: params.withCredentials,
  1092. rangeChunkSize: params.rangeChunkSize,
  1093. disableRange: params.disableRange,
  1094. disableStream: params.disableStream
  1095. });
  1096. }
  1097. resolve(networkStream);
  1098. });
  1099. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1100. if (task.destroyed) {
  1101. throw new Error("Loading aborted");
  1102. }
  1103. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1104. const transport = new WorkerTransport(messageHandler, task, networkStream, params);
  1105. task._transport = transport;
  1106. messageHandler.send("Ready", null);
  1107. });
  1108. }).catch(task._capability.reject);
  1109. return task;
  1110. }
  1111. async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  1112. if (worker.destroyed) {
  1113. throw new Error("Worker was destroyed");
  1114. }
  1115. if (pdfDataRangeTransport) {
  1116. source.length = pdfDataRangeTransport.length;
  1117. source.initialData = pdfDataRangeTransport.initialData;
  1118. source.progressiveDone = pdfDataRangeTransport.progressiveDone;
  1119. source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
  1120. }
  1121. const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
  1122. docId,
  1123. apiVersion: '3.1.81',
  1124. data: source.data,
  1125. password: source.password,
  1126. disableAutoFetch: source.disableAutoFetch,
  1127. rangeChunkSize: source.rangeChunkSize,
  1128. length: source.length,
  1129. docBaseUrl: source.docBaseUrl,
  1130. enableXfa: source.enableXfa,
  1131. evaluatorOptions: {
  1132. maxImageSize: source.maxImageSize,
  1133. disableFontFace: source.disableFontFace,
  1134. ignoreErrors: source.ignoreErrors,
  1135. isEvalSupported: source.isEvalSupported,
  1136. isOffscreenCanvasSupported: source.isOffscreenCanvasSupported,
  1137. fontExtraProperties: source.fontExtraProperties,
  1138. useSystemFonts: source.useSystemFonts,
  1139. cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
  1140. standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
  1141. }
  1142. });
  1143. if (source.data) {
  1144. source.data = null;
  1145. }
  1146. if (worker.destroyed) {
  1147. throw new Error("Worker was destroyed");
  1148. }
  1149. return workerId;
  1150. }
  1151. class PDFDocumentLoadingTask {
  1152. static #docId = 0;
  1153. constructor() {
  1154. this._capability = (0, _util.createPromiseCapability)();
  1155. this._transport = null;
  1156. this._worker = null;
  1157. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  1158. this.destroyed = false;
  1159. this.onPassword = null;
  1160. this.onProgress = null;
  1161. this.onUnsupportedFeature = null;
  1162. }
  1163. get promise() {
  1164. return this._capability.promise;
  1165. }
  1166. async destroy() {
  1167. this.destroyed = true;
  1168. await this._transport?.destroy();
  1169. this._transport = null;
  1170. if (this._worker) {
  1171. this._worker.destroy();
  1172. this._worker = null;
  1173. }
  1174. }
  1175. }
  1176. exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
  1177. class PDFDataRangeTransport {
  1178. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1179. this.length = length;
  1180. this.initialData = initialData;
  1181. this.progressiveDone = progressiveDone;
  1182. this.contentDispositionFilename = contentDispositionFilename;
  1183. this._rangeListeners = [];
  1184. this._progressListeners = [];
  1185. this._progressiveReadListeners = [];
  1186. this._progressiveDoneListeners = [];
  1187. this._readyCapability = (0, _util.createPromiseCapability)();
  1188. }
  1189. addRangeListener(listener) {
  1190. this._rangeListeners.push(listener);
  1191. }
  1192. addProgressListener(listener) {
  1193. this._progressListeners.push(listener);
  1194. }
  1195. addProgressiveReadListener(listener) {
  1196. this._progressiveReadListeners.push(listener);
  1197. }
  1198. addProgressiveDoneListener(listener) {
  1199. this._progressiveDoneListeners.push(listener);
  1200. }
  1201. onDataRange(begin, chunk) {
  1202. for (const listener of this._rangeListeners) {
  1203. listener(begin, chunk);
  1204. }
  1205. }
  1206. onDataProgress(loaded, total) {
  1207. this._readyCapability.promise.then(() => {
  1208. for (const listener of this._progressListeners) {
  1209. listener(loaded, total);
  1210. }
  1211. });
  1212. }
  1213. onDataProgressiveRead(chunk) {
  1214. this._readyCapability.promise.then(() => {
  1215. for (const listener of this._progressiveReadListeners) {
  1216. listener(chunk);
  1217. }
  1218. });
  1219. }
  1220. onDataProgressiveDone() {
  1221. this._readyCapability.promise.then(() => {
  1222. for (const listener of this._progressiveDoneListeners) {
  1223. listener();
  1224. }
  1225. });
  1226. }
  1227. transportReady() {
  1228. this._readyCapability.resolve();
  1229. }
  1230. requestDataRange(begin, end) {
  1231. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1232. }
  1233. abort() {}
  1234. }
  1235. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1236. class PDFDocumentProxy {
  1237. constructor(pdfInfo, transport) {
  1238. this._pdfInfo = pdfInfo;
  1239. this._transport = transport;
  1240. }
  1241. get annotationStorage() {
  1242. return this._transport.annotationStorage;
  1243. }
  1244. get numPages() {
  1245. return this._pdfInfo.numPages;
  1246. }
  1247. get fingerprints() {
  1248. return this._pdfInfo.fingerprints;
  1249. }
  1250. get stats() {
  1251. return this._transport.stats;
  1252. }
  1253. get isPureXfa() {
  1254. return !!this._transport._htmlForXfa;
  1255. }
  1256. get allXfaHtml() {
  1257. return this._transport._htmlForXfa;
  1258. }
  1259. getPage(pageNumber) {
  1260. return this._transport.getPage(pageNumber);
  1261. }
  1262. getPageIndex(ref) {
  1263. return this._transport.getPageIndex(ref);
  1264. }
  1265. getDestinations() {
  1266. return this._transport.getDestinations();
  1267. }
  1268. getDestination(id) {
  1269. return this._transport.getDestination(id);
  1270. }
  1271. getPageLabels() {
  1272. return this._transport.getPageLabels();
  1273. }
  1274. getPageLayout() {
  1275. return this._transport.getPageLayout();
  1276. }
  1277. getPageMode() {
  1278. return this._transport.getPageMode();
  1279. }
  1280. getViewerPreferences() {
  1281. return this._transport.getViewerPreferences();
  1282. }
  1283. getOpenAction() {
  1284. return this._transport.getOpenAction();
  1285. }
  1286. getAttachments() {
  1287. return this._transport.getAttachments();
  1288. }
  1289. getJavaScript() {
  1290. return this._transport.getJavaScript();
  1291. }
  1292. getJSActions() {
  1293. return this._transport.getDocJSActions();
  1294. }
  1295. getOutline() {
  1296. return this._transport.getOutline();
  1297. }
  1298. getOptionalContentConfig() {
  1299. return this._transport.getOptionalContentConfig();
  1300. }
  1301. getPermissions() {
  1302. return this._transport.getPermissions();
  1303. }
  1304. getMetadata() {
  1305. return this._transport.getMetadata();
  1306. }
  1307. getMarkInfo() {
  1308. return this._transport.getMarkInfo();
  1309. }
  1310. getData() {
  1311. return this._transport.getData();
  1312. }
  1313. saveDocument() {
  1314. return this._transport.saveDocument();
  1315. }
  1316. getDownloadInfo() {
  1317. return this._transport.downloadInfoCapability.promise;
  1318. }
  1319. cleanup(keepLoadedFonts = false) {
  1320. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1321. }
  1322. destroy() {
  1323. return this.loadingTask.destroy();
  1324. }
  1325. get loadingParams() {
  1326. return this._transport.loadingParams;
  1327. }
  1328. get loadingTask() {
  1329. return this._transport.loadingTask;
  1330. }
  1331. getFieldObjects() {
  1332. return this._transport.getFieldObjects();
  1333. }
  1334. hasJSActions() {
  1335. return this._transport.hasJSActions();
  1336. }
  1337. getCalculationOrderIds() {
  1338. return this._transport.getCalculationOrderIds();
  1339. }
  1340. }
  1341. exports.PDFDocumentProxy = PDFDocumentProxy;
  1342. class PDFPageProxy {
  1343. constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
  1344. this._pageIndex = pageIndex;
  1345. this._pageInfo = pageInfo;
  1346. this._ownerDocument = ownerDocument;
  1347. this._transport = transport;
  1348. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1349. this._pdfBug = pdfBug;
  1350. this.commonObjs = transport.commonObjs;
  1351. this.objs = new PDFObjects();
  1352. this._bitmaps = new Set();
  1353. this.cleanupAfterRender = false;
  1354. this.pendingCleanup = false;
  1355. this._intentStates = new Map();
  1356. this._annotationPromises = new Map();
  1357. this.destroyed = false;
  1358. }
  1359. get pageNumber() {
  1360. return this._pageIndex + 1;
  1361. }
  1362. get rotate() {
  1363. return this._pageInfo.rotate;
  1364. }
  1365. get ref() {
  1366. return this._pageInfo.ref;
  1367. }
  1368. get userUnit() {
  1369. return this._pageInfo.userUnit;
  1370. }
  1371. get view() {
  1372. return this._pageInfo.view;
  1373. }
  1374. getViewport({
  1375. scale,
  1376. rotation = this.rotate,
  1377. offsetX = 0,
  1378. offsetY = 0,
  1379. dontFlip = false
  1380. } = {}) {
  1381. return new _display_utils.PageViewport({
  1382. viewBox: this.view,
  1383. scale,
  1384. rotation,
  1385. offsetX,
  1386. offsetY,
  1387. dontFlip
  1388. });
  1389. }
  1390. getAnnotations({
  1391. intent = "display"
  1392. } = {}) {
  1393. const intentArgs = this._transport.getRenderingIntent(intent);
  1394. let promise = this._annotationPromises.get(intentArgs.cacheKey);
  1395. if (!promise) {
  1396. promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  1397. this._annotationPromises.set(intentArgs.cacheKey, promise);
  1398. }
  1399. return promise;
  1400. }
  1401. getJSActions() {
  1402. return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
  1403. }
  1404. async getXfa() {
  1405. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  1406. }
  1407. render({
  1408. canvasContext,
  1409. viewport,
  1410. intent = "display",
  1411. annotationMode = _util.AnnotationMode.ENABLE,
  1412. transform = null,
  1413. canvasFactory = null,
  1414. background = null,
  1415. optionalContentConfigPromise = null,
  1416. annotationCanvasMap = null,
  1417. pageColors = null,
  1418. printAnnotationStorage = null
  1419. }) {
  1420. this._stats?.time("Overall");
  1421. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
  1422. this.pendingCleanup = false;
  1423. if (!optionalContentConfigPromise) {
  1424. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1425. }
  1426. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1427. if (!intentState) {
  1428. intentState = Object.create(null);
  1429. this._intentStates.set(intentArgs.cacheKey, intentState);
  1430. }
  1431. if (intentState.streamReaderCancelTimeout) {
  1432. clearTimeout(intentState.streamReaderCancelTimeout);
  1433. intentState.streamReaderCancelTimeout = null;
  1434. }
  1435. const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
  1436. ownerDocument: this._ownerDocument
  1437. });
  1438. const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
  1439. if (!intentState.displayReadyCapability) {
  1440. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  1441. intentState.operatorList = {
  1442. fnArray: [],
  1443. argsArray: [],
  1444. lastChunk: false,
  1445. separateAnnots: null
  1446. };
  1447. this._stats?.time("Page Request");
  1448. this._pumpOperatorList(intentArgs);
  1449. }
  1450. const complete = error => {
  1451. intentState.renderTasks.delete(internalRenderTask);
  1452. if (this.cleanupAfterRender || intentPrint) {
  1453. this.pendingCleanup = true;
  1454. }
  1455. this._tryCleanup();
  1456. if (error) {
  1457. internalRenderTask.capability.reject(error);
  1458. this._abortOperatorList({
  1459. intentState,
  1460. reason: error instanceof Error ? error : new Error(error)
  1461. });
  1462. } else {
  1463. internalRenderTask.capability.resolve();
  1464. }
  1465. this._stats?.timeEnd("Rendering");
  1466. this._stats?.timeEnd("Overall");
  1467. };
  1468. const internalRenderTask = new InternalRenderTask({
  1469. callback: complete,
  1470. params: {
  1471. canvasContext,
  1472. viewport,
  1473. transform,
  1474. background
  1475. },
  1476. objs: this.objs,
  1477. commonObjs: this.commonObjs,
  1478. annotationCanvasMap,
  1479. operatorList: intentState.operatorList,
  1480. pageIndex: this._pageIndex,
  1481. canvasFactory: canvasFactoryInstance,
  1482. useRequestAnimationFrame: !intentPrint,
  1483. pdfBug: this._pdfBug,
  1484. pageColors
  1485. });
  1486. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  1487. const renderTask = internalRenderTask.task;
  1488. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  1489. if (this.pendingCleanup) {
  1490. complete();
  1491. return;
  1492. }
  1493. this._stats?.time("Rendering");
  1494. internalRenderTask.initializeGraphics({
  1495. transparency,
  1496. optionalContentConfig
  1497. });
  1498. internalRenderTask.operatorListChanged();
  1499. }).catch(complete);
  1500. return renderTask;
  1501. }
  1502. getOperatorList({
  1503. intent = "display",
  1504. annotationMode = _util.AnnotationMode.ENABLE,
  1505. printAnnotationStorage = null
  1506. } = {}) {
  1507. function operatorListChanged() {
  1508. if (intentState.operatorList.lastChunk) {
  1509. intentState.opListReadCapability.resolve(intentState.operatorList);
  1510. intentState.renderTasks.delete(opListTask);
  1511. }
  1512. }
  1513. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
  1514. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1515. if (!intentState) {
  1516. intentState = Object.create(null);
  1517. this._intentStates.set(intentArgs.cacheKey, intentState);
  1518. }
  1519. let opListTask;
  1520. if (!intentState.opListReadCapability) {
  1521. opListTask = Object.create(null);
  1522. opListTask.operatorListChanged = operatorListChanged;
  1523. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  1524. (intentState.renderTasks ||= new Set()).add(opListTask);
  1525. intentState.operatorList = {
  1526. fnArray: [],
  1527. argsArray: [],
  1528. lastChunk: false,
  1529. separateAnnots: null
  1530. };
  1531. this._stats?.time("Page Request");
  1532. this._pumpOperatorList(intentArgs);
  1533. }
  1534. return intentState.opListReadCapability.promise;
  1535. }
  1536. streamTextContent({
  1537. disableCombineTextItems = false,
  1538. includeMarkedContent = false
  1539. } = {}) {
  1540. const TEXT_CONTENT_CHUNK_SIZE = 100;
  1541. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  1542. pageIndex: this._pageIndex,
  1543. combineTextItems: disableCombineTextItems !== true,
  1544. includeMarkedContent: includeMarkedContent === true
  1545. }, {
  1546. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  1547. size(textContent) {
  1548. return textContent.items.length;
  1549. }
  1550. });
  1551. }
  1552. getTextContent(params = {}) {
  1553. if (this._transport._htmlForXfa) {
  1554. return this.getXfa().then(xfa => {
  1555. return _xfa_text.XfaText.textContent(xfa);
  1556. });
  1557. }
  1558. const readableStream = this.streamTextContent(params);
  1559. return new Promise(function (resolve, reject) {
  1560. function pump() {
  1561. reader.read().then(function ({
  1562. value,
  1563. done
  1564. }) {
  1565. if (done) {
  1566. resolve(textContent);
  1567. return;
  1568. }
  1569. Object.assign(textContent.styles, value.styles);
  1570. textContent.items.push(...value.items);
  1571. pump();
  1572. }, reject);
  1573. }
  1574. const reader = readableStream.getReader();
  1575. const textContent = {
  1576. items: [],
  1577. styles: Object.create(null)
  1578. };
  1579. pump();
  1580. });
  1581. }
  1582. getStructTree() {
  1583. return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
  1584. }
  1585. _destroy() {
  1586. this.destroyed = true;
  1587. const waitOn = [];
  1588. for (const intentState of this._intentStates.values()) {
  1589. this._abortOperatorList({
  1590. intentState,
  1591. reason: new Error("Page was destroyed."),
  1592. force: true
  1593. });
  1594. if (intentState.opListReadCapability) {
  1595. continue;
  1596. }
  1597. for (const internalRenderTask of intentState.renderTasks) {
  1598. waitOn.push(internalRenderTask.completed);
  1599. internalRenderTask.cancel();
  1600. }
  1601. }
  1602. this.objs.clear();
  1603. for (const bitmap of this._bitmaps) {
  1604. bitmap.close();
  1605. }
  1606. this._bitmaps.clear();
  1607. this._annotationPromises.clear();
  1608. this._jsActionsPromise = null;
  1609. this._structTreePromise = null;
  1610. this.pendingCleanup = false;
  1611. return Promise.all(waitOn);
  1612. }
  1613. cleanup(resetStats = false) {
  1614. this.pendingCleanup = true;
  1615. return this._tryCleanup(resetStats);
  1616. }
  1617. _tryCleanup(resetStats = false) {
  1618. if (!this.pendingCleanup) {
  1619. return false;
  1620. }
  1621. for (const {
  1622. renderTasks,
  1623. operatorList
  1624. } of this._intentStates.values()) {
  1625. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  1626. return false;
  1627. }
  1628. }
  1629. this._intentStates.clear();
  1630. this.objs.clear();
  1631. this._annotationPromises.clear();
  1632. this._jsActionsPromise = null;
  1633. this._structTreePromise = null;
  1634. if (resetStats && this._stats) {
  1635. this._stats = new _display_utils.StatTimer();
  1636. }
  1637. for (const bitmap of this._bitmaps) {
  1638. bitmap.close();
  1639. }
  1640. this._bitmaps.clear();
  1641. this.pendingCleanup = false;
  1642. return true;
  1643. }
  1644. _startRenderPage(transparency, cacheKey) {
  1645. const intentState = this._intentStates.get(cacheKey);
  1646. if (!intentState) {
  1647. return;
  1648. }
  1649. this._stats?.timeEnd("Page Request");
  1650. intentState.displayReadyCapability?.resolve(transparency);
  1651. }
  1652. _renderPageChunk(operatorListChunk, intentState) {
  1653. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  1654. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  1655. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  1656. }
  1657. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  1658. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  1659. for (const internalRenderTask of intentState.renderTasks) {
  1660. internalRenderTask.operatorListChanged();
  1661. }
  1662. if (operatorListChunk.lastChunk) {
  1663. this._tryCleanup();
  1664. }
  1665. }
  1666. _pumpOperatorList({
  1667. renderingIntent,
  1668. cacheKey,
  1669. annotationStorageMap
  1670. }) {
  1671. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  1672. pageIndex: this._pageIndex,
  1673. intent: renderingIntent,
  1674. cacheKey,
  1675. annotationStorage: annotationStorageMap
  1676. });
  1677. const reader = readableStream.getReader();
  1678. const intentState = this._intentStates.get(cacheKey);
  1679. intentState.streamReader = reader;
  1680. const pump = () => {
  1681. reader.read().then(({
  1682. value,
  1683. done
  1684. }) => {
  1685. if (done) {
  1686. intentState.streamReader = null;
  1687. return;
  1688. }
  1689. if (this._transport.destroyed) {
  1690. return;
  1691. }
  1692. this._renderPageChunk(value, intentState);
  1693. pump();
  1694. }, reason => {
  1695. intentState.streamReader = null;
  1696. if (this._transport.destroyed) {
  1697. return;
  1698. }
  1699. if (intentState.operatorList) {
  1700. intentState.operatorList.lastChunk = true;
  1701. for (const internalRenderTask of intentState.renderTasks) {
  1702. internalRenderTask.operatorListChanged();
  1703. }
  1704. this._tryCleanup();
  1705. }
  1706. if (intentState.displayReadyCapability) {
  1707. intentState.displayReadyCapability.reject(reason);
  1708. } else if (intentState.opListReadCapability) {
  1709. intentState.opListReadCapability.reject(reason);
  1710. } else {
  1711. throw reason;
  1712. }
  1713. });
  1714. };
  1715. pump();
  1716. }
  1717. _abortOperatorList({
  1718. intentState,
  1719. reason,
  1720. force = false
  1721. }) {
  1722. if (!intentState.streamReader) {
  1723. return;
  1724. }
  1725. if (!force) {
  1726. if (intentState.renderTasks.size > 0) {
  1727. return;
  1728. }
  1729. if (reason instanceof _display_utils.RenderingCancelledException) {
  1730. intentState.streamReaderCancelTimeout = setTimeout(() => {
  1731. this._abortOperatorList({
  1732. intentState,
  1733. reason,
  1734. force: true
  1735. });
  1736. intentState.streamReaderCancelTimeout = null;
  1737. }, RENDERING_CANCELLED_TIMEOUT);
  1738. return;
  1739. }
  1740. }
  1741. intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
  1742. intentState.streamReader = null;
  1743. if (this._transport.destroyed) {
  1744. return;
  1745. }
  1746. for (const [curCacheKey, curIntentState] of this._intentStates) {
  1747. if (curIntentState === intentState) {
  1748. this._intentStates.delete(curCacheKey);
  1749. break;
  1750. }
  1751. }
  1752. this.cleanup();
  1753. }
  1754. get stats() {
  1755. return this._stats;
  1756. }
  1757. }
  1758. exports.PDFPageProxy = PDFPageProxy;
  1759. class LoopbackPort {
  1760. #listeners = [];
  1761. #deferred = Promise.resolve();
  1762. postMessage(obj, transfers) {
  1763. const event = {
  1764. data: structuredClone(obj, transfers)
  1765. };
  1766. this.#deferred.then(() => {
  1767. for (const listener of this.#listeners) {
  1768. listener.call(this, event);
  1769. }
  1770. });
  1771. }
  1772. addEventListener(name, listener) {
  1773. this.#listeners.push(listener);
  1774. }
  1775. removeEventListener(name, listener) {
  1776. const i = this.#listeners.indexOf(listener);
  1777. this.#listeners.splice(i, 1);
  1778. }
  1779. terminate() {
  1780. this.#listeners.length = 0;
  1781. }
  1782. }
  1783. exports.LoopbackPort = LoopbackPort;
  1784. const PDFWorkerUtil = {
  1785. isWorkerDisabled: false,
  1786. fallbackWorkerSrc: null,
  1787. fakeWorkerId: 0
  1788. };
  1789. exports.PDFWorkerUtil = PDFWorkerUtil;
  1790. {
  1791. if (_is_node.isNodeJS && typeof require === "function") {
  1792. PDFWorkerUtil.isWorkerDisabled = true;
  1793. PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  1794. } else if (typeof document === "object") {
  1795. const pdfjsFilePath = document?.currentScript?.src;
  1796. if (pdfjsFilePath) {
  1797. PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  1798. }
  1799. }
  1800. PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
  1801. let base;
  1802. try {
  1803. base = new URL(baseUrl);
  1804. if (!base.origin || base.origin === "null") {
  1805. return false;
  1806. }
  1807. } catch (e) {
  1808. return false;
  1809. }
  1810. const other = new URL(otherUrl, base);
  1811. return base.origin === other.origin;
  1812. };
  1813. PDFWorkerUtil.createCDNWrapper = function (url) {
  1814. const wrapper = `importScripts("${url}");`;
  1815. return URL.createObjectURL(new Blob([wrapper]));
  1816. };
  1817. }
  1818. class PDFWorker {
  1819. static #workerPorts = new WeakMap();
  1820. constructor({
  1821. name = null,
  1822. port = null,
  1823. verbosity = (0, _util.getVerbosityLevel)()
  1824. } = {}) {
  1825. if (port && PDFWorker.#workerPorts.has(port)) {
  1826. throw new Error("Cannot use more than one PDFWorker per port.");
  1827. }
  1828. this.name = name;
  1829. this.destroyed = false;
  1830. this.verbosity = verbosity;
  1831. this._readyCapability = (0, _util.createPromiseCapability)();
  1832. this._port = null;
  1833. this._webWorker = null;
  1834. this._messageHandler = null;
  1835. if (port) {
  1836. PDFWorker.#workerPorts.set(port, this);
  1837. this._initializeFromPort(port);
  1838. return;
  1839. }
  1840. this._initialize();
  1841. }
  1842. get promise() {
  1843. return this._readyCapability.promise;
  1844. }
  1845. get port() {
  1846. return this._port;
  1847. }
  1848. get messageHandler() {
  1849. return this._messageHandler;
  1850. }
  1851. _initializeFromPort(port) {
  1852. this._port = port;
  1853. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  1854. this._messageHandler.on("ready", function () {});
  1855. this._readyCapability.resolve();
  1856. this._messageHandler.send("configure", {
  1857. verbosity: this.verbosity
  1858. });
  1859. }
  1860. _initialize() {
  1861. if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
  1862. let {
  1863. workerSrc
  1864. } = PDFWorker;
  1865. try {
  1866. if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
  1867. workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
  1868. }
  1869. const worker = new Worker(workerSrc);
  1870. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  1871. const terminateEarly = () => {
  1872. worker.removeEventListener("error", onWorkerError);
  1873. messageHandler.destroy();
  1874. worker.terminate();
  1875. if (this.destroyed) {
  1876. this._readyCapability.reject(new Error("Worker was destroyed"));
  1877. } else {
  1878. this._setupFakeWorker();
  1879. }
  1880. };
  1881. const onWorkerError = () => {
  1882. if (!this._webWorker) {
  1883. terminateEarly();
  1884. }
  1885. };
  1886. worker.addEventListener("error", onWorkerError);
  1887. messageHandler.on("test", data => {
  1888. worker.removeEventListener("error", onWorkerError);
  1889. if (this.destroyed) {
  1890. terminateEarly();
  1891. return;
  1892. }
  1893. if (data) {
  1894. this._messageHandler = messageHandler;
  1895. this._port = worker;
  1896. this._webWorker = worker;
  1897. this._readyCapability.resolve();
  1898. messageHandler.send("configure", {
  1899. verbosity: this.verbosity
  1900. });
  1901. } else {
  1902. this._setupFakeWorker();
  1903. messageHandler.destroy();
  1904. worker.terminate();
  1905. }
  1906. });
  1907. messageHandler.on("ready", data => {
  1908. worker.removeEventListener("error", onWorkerError);
  1909. if (this.destroyed) {
  1910. terminateEarly();
  1911. return;
  1912. }
  1913. try {
  1914. sendTest();
  1915. } catch (e) {
  1916. this._setupFakeWorker();
  1917. }
  1918. });
  1919. const sendTest = () => {
  1920. const testObj = new Uint8Array();
  1921. messageHandler.send("test", testObj, [testObj.buffer]);
  1922. };
  1923. sendTest();
  1924. return;
  1925. } catch (e) {
  1926. (0, _util.info)("The worker has been disabled.");
  1927. }
  1928. }
  1929. this._setupFakeWorker();
  1930. }
  1931. _setupFakeWorker() {
  1932. if (!PDFWorkerUtil.isWorkerDisabled) {
  1933. (0, _util.warn)("Setting up fake worker.");
  1934. PDFWorkerUtil.isWorkerDisabled = true;
  1935. }
  1936. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  1937. if (this.destroyed) {
  1938. this._readyCapability.reject(new Error("Worker was destroyed"));
  1939. return;
  1940. }
  1941. const port = new LoopbackPort();
  1942. this._port = port;
  1943. const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
  1944. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  1945. WorkerMessageHandler.setup(workerHandler, port);
  1946. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  1947. this._messageHandler = messageHandler;
  1948. this._readyCapability.resolve();
  1949. messageHandler.send("configure", {
  1950. verbosity: this.verbosity
  1951. });
  1952. }).catch(reason => {
  1953. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  1954. });
  1955. }
  1956. destroy() {
  1957. this.destroyed = true;
  1958. if (this._webWorker) {
  1959. this._webWorker.terminate();
  1960. this._webWorker = null;
  1961. }
  1962. PDFWorker.#workerPorts.delete(this._port);
  1963. this._port = null;
  1964. if (this._messageHandler) {
  1965. this._messageHandler.destroy();
  1966. this._messageHandler = null;
  1967. }
  1968. }
  1969. static fromPort(params) {
  1970. if (!params?.port) {
  1971. throw new Error("PDFWorker.fromPort - invalid method signature.");
  1972. }
  1973. if (this.#workerPorts.has(params.port)) {
  1974. return this.#workerPorts.get(params.port);
  1975. }
  1976. return new PDFWorker(params);
  1977. }
  1978. static get workerSrc() {
  1979. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  1980. return _worker_options.GlobalWorkerOptions.workerSrc;
  1981. }
  1982. if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
  1983. if (!_is_node.isNodeJS) {
  1984. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  1985. }
  1986. return PDFWorkerUtil.fallbackWorkerSrc;
  1987. }
  1988. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  1989. }
  1990. static get _mainThreadWorkerMessageHandler() {
  1991. try {
  1992. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  1993. } catch (ex) {
  1994. return null;
  1995. }
  1996. }
  1997. static get _setupFakeWorkerGlobal() {
  1998. const loader = async () => {
  1999. const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
  2000. if (mainWorkerMessageHandler) {
  2001. return mainWorkerMessageHandler;
  2002. }
  2003. if (_is_node.isNodeJS && typeof require === "function") {
  2004. const worker = eval("require")(this.workerSrc);
  2005. return worker.WorkerMessageHandler;
  2006. }
  2007. await (0, _display_utils.loadScript)(this.workerSrc);
  2008. return window.pdfjsWorker.WorkerMessageHandler;
  2009. };
  2010. return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  2011. }
  2012. }
  2013. exports.PDFWorker = PDFWorker;
  2014. class WorkerTransport {
  2015. #docStats = null;
  2016. #pageCache = new Map();
  2017. #pagePromises = new Map();
  2018. #metadataPromise = null;
  2019. constructor(messageHandler, loadingTask, networkStream, params) {
  2020. this.messageHandler = messageHandler;
  2021. this.loadingTask = loadingTask;
  2022. this.commonObjs = new PDFObjects();
  2023. this.fontLoader = new _font_loader.FontLoader({
  2024. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2025. ownerDocument: params.ownerDocument,
  2026. styleElement: params.styleElement
  2027. });
  2028. this._params = params;
  2029. if (!params.useWorkerFetch) {
  2030. this.CMapReaderFactory = new params.CMapReaderFactory({
  2031. baseUrl: params.cMapUrl,
  2032. isCompressed: params.cMapPacked
  2033. });
  2034. this.StandardFontDataFactory = new params.StandardFontDataFactory({
  2035. baseUrl: params.standardFontDataUrl
  2036. });
  2037. }
  2038. this.destroyed = false;
  2039. this.destroyCapability = null;
  2040. this._passwordCapability = null;
  2041. this._networkStream = networkStream;
  2042. this._fullReader = null;
  2043. this._lastProgress = null;
  2044. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  2045. this.setupMessageHandler();
  2046. }
  2047. get annotationStorage() {
  2048. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2049. }
  2050. get stats() {
  2051. return this.#docStats;
  2052. }
  2053. getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
  2054. let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
  2055. let annotationMap = null;
  2056. switch (intent) {
  2057. case "any":
  2058. renderingIntent = _util.RenderingIntentFlag.ANY;
  2059. break;
  2060. case "display":
  2061. break;
  2062. case "print":
  2063. renderingIntent = _util.RenderingIntentFlag.PRINT;
  2064. break;
  2065. default:
  2066. (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
  2067. }
  2068. switch (annotationMode) {
  2069. case _util.AnnotationMode.DISABLE:
  2070. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
  2071. break;
  2072. case _util.AnnotationMode.ENABLE:
  2073. break;
  2074. case _util.AnnotationMode.ENABLE_FORMS:
  2075. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
  2076. break;
  2077. case _util.AnnotationMode.ENABLE_STORAGE:
  2078. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
  2079. const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  2080. annotationMap = annotationStorage.serializable;
  2081. break;
  2082. default:
  2083. (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  2084. }
  2085. if (isOpList) {
  2086. renderingIntent += _util.RenderingIntentFlag.OPLIST;
  2087. }
  2088. return {
  2089. renderingIntent,
  2090. cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
  2091. annotationStorageMap: annotationMap
  2092. };
  2093. }
  2094. destroy() {
  2095. if (this.destroyCapability) {
  2096. return this.destroyCapability.promise;
  2097. }
  2098. this.destroyed = true;
  2099. this.destroyCapability = (0, _util.createPromiseCapability)();
  2100. if (this._passwordCapability) {
  2101. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2102. }
  2103. const waitOn = [];
  2104. for (const page of this.#pageCache.values()) {
  2105. waitOn.push(page._destroy());
  2106. }
  2107. this.#pageCache.clear();
  2108. this.#pagePromises.clear();
  2109. if (this.hasOwnProperty("annotationStorage")) {
  2110. this.annotationStorage.resetModified();
  2111. }
  2112. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2113. waitOn.push(terminated);
  2114. Promise.all(waitOn).then(() => {
  2115. this.commonObjs.clear();
  2116. this.fontLoader.clear();
  2117. this.#metadataPromise = null;
  2118. this._getFieldObjectsPromise = null;
  2119. this._hasJSActionsPromise = null;
  2120. if (this._networkStream) {
  2121. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2122. }
  2123. if (this.messageHandler) {
  2124. this.messageHandler.destroy();
  2125. this.messageHandler = null;
  2126. }
  2127. this.destroyCapability.resolve();
  2128. }, this.destroyCapability.reject);
  2129. return this.destroyCapability.promise;
  2130. }
  2131. setupMessageHandler() {
  2132. const {
  2133. messageHandler,
  2134. loadingTask
  2135. } = this;
  2136. messageHandler.on("GetReader", (data, sink) => {
  2137. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2138. this._fullReader = this._networkStream.getFullReader();
  2139. this._fullReader.onProgress = evt => {
  2140. this._lastProgress = {
  2141. loaded: evt.loaded,
  2142. total: evt.total
  2143. };
  2144. };
  2145. sink.onPull = () => {
  2146. this._fullReader.read().then(function ({
  2147. value,
  2148. done
  2149. }) {
  2150. if (done) {
  2151. sink.close();
  2152. return;
  2153. }
  2154. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
  2155. sink.enqueue(new Uint8Array(value), 1, [value]);
  2156. }).catch(reason => {
  2157. sink.error(reason);
  2158. });
  2159. };
  2160. sink.onCancel = reason => {
  2161. this._fullReader.cancel(reason);
  2162. sink.ready.catch(readyReason => {
  2163. if (this.destroyed) {
  2164. return;
  2165. }
  2166. throw readyReason;
  2167. });
  2168. };
  2169. });
  2170. messageHandler.on("ReaderHeadersReady", data => {
  2171. const headersCapability = (0, _util.createPromiseCapability)();
  2172. const fullReader = this._fullReader;
  2173. fullReader.headersReady.then(() => {
  2174. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2175. if (this._lastProgress) {
  2176. loadingTask.onProgress?.(this._lastProgress);
  2177. }
  2178. fullReader.onProgress = evt => {
  2179. loadingTask.onProgress?.({
  2180. loaded: evt.loaded,
  2181. total: evt.total
  2182. });
  2183. };
  2184. }
  2185. headersCapability.resolve({
  2186. isStreamingSupported: fullReader.isStreamingSupported,
  2187. isRangeSupported: fullReader.isRangeSupported,
  2188. contentLength: fullReader.contentLength
  2189. });
  2190. }, headersCapability.reject);
  2191. return headersCapability.promise;
  2192. });
  2193. messageHandler.on("GetRangeReader", (data, sink) => {
  2194. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2195. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2196. if (!rangeReader) {
  2197. sink.close();
  2198. return;
  2199. }
  2200. sink.onPull = () => {
  2201. rangeReader.read().then(function ({
  2202. value,
  2203. done
  2204. }) {
  2205. if (done) {
  2206. sink.close();
  2207. return;
  2208. }
  2209. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
  2210. sink.enqueue(new Uint8Array(value), 1, [value]);
  2211. }).catch(reason => {
  2212. sink.error(reason);
  2213. });
  2214. };
  2215. sink.onCancel = reason => {
  2216. rangeReader.cancel(reason);
  2217. sink.ready.catch(readyReason => {
  2218. if (this.destroyed) {
  2219. return;
  2220. }
  2221. throw readyReason;
  2222. });
  2223. };
  2224. });
  2225. messageHandler.on("GetDoc", ({
  2226. pdfInfo
  2227. }) => {
  2228. this._numPages = pdfInfo.numPages;
  2229. this._htmlForXfa = pdfInfo.htmlForXfa;
  2230. delete pdfInfo.htmlForXfa;
  2231. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2232. });
  2233. messageHandler.on("DocException", function (ex) {
  2234. let reason;
  2235. switch (ex.name) {
  2236. case "PasswordException":
  2237. reason = new _util.PasswordException(ex.message, ex.code);
  2238. break;
  2239. case "InvalidPDFException":
  2240. reason = new _util.InvalidPDFException(ex.message);
  2241. break;
  2242. case "MissingPDFException":
  2243. reason = new _util.MissingPDFException(ex.message);
  2244. break;
  2245. case "UnexpectedResponseException":
  2246. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2247. break;
  2248. case "UnknownErrorException":
  2249. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2250. break;
  2251. default:
  2252. (0, _util.unreachable)("DocException - expected a valid Error.");
  2253. }
  2254. loadingTask._capability.reject(reason);
  2255. });
  2256. messageHandler.on("PasswordRequest", exception => {
  2257. this._passwordCapability = (0, _util.createPromiseCapability)();
  2258. if (loadingTask.onPassword) {
  2259. const updatePassword = password => {
  2260. if (password instanceof Error) {
  2261. this._passwordCapability.reject(password);
  2262. } else {
  2263. this._passwordCapability.resolve({
  2264. password
  2265. });
  2266. }
  2267. };
  2268. try {
  2269. loadingTask.onPassword(updatePassword, exception.code);
  2270. } catch (ex) {
  2271. this._passwordCapability.reject(ex);
  2272. }
  2273. } else {
  2274. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2275. }
  2276. return this._passwordCapability.promise;
  2277. });
  2278. messageHandler.on("DataLoaded", data => {
  2279. loadingTask.onProgress?.({
  2280. loaded: data.length,
  2281. total: data.length
  2282. });
  2283. this.downloadInfoCapability.resolve(data);
  2284. });
  2285. messageHandler.on("StartRenderPage", data => {
  2286. if (this.destroyed) {
  2287. return;
  2288. }
  2289. const page = this.#pageCache.get(data.pageIndex);
  2290. page._startRenderPage(data.transparency, data.cacheKey);
  2291. });
  2292. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  2293. if (this.destroyed) {
  2294. return;
  2295. }
  2296. if (this.commonObjs.has(id)) {
  2297. return;
  2298. }
  2299. switch (type) {
  2300. case "Font":
  2301. const params = this._params;
  2302. if ("error" in exportedData) {
  2303. const exportedError = exportedData.error;
  2304. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2305. this.commonObjs.resolve(id, exportedError);
  2306. break;
  2307. }
  2308. let fontRegistry = null;
  2309. if (params.pdfBug && globalThis.FontInspector?.enabled) {
  2310. fontRegistry = {
  2311. registerFont(font, url) {
  2312. globalThis.FontInspector.fontAdded(font, url);
  2313. }
  2314. };
  2315. }
  2316. const font = new _font_loader.FontFaceObject(exportedData, {
  2317. isEvalSupported: params.isEvalSupported,
  2318. disableFontFace: params.disableFontFace,
  2319. ignoreErrors: params.ignoreErrors,
  2320. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2321. fontRegistry
  2322. });
  2323. this.fontLoader.bind(font).catch(reason => {
  2324. return messageHandler.sendWithPromise("FontFallback", {
  2325. id
  2326. });
  2327. }).finally(() => {
  2328. if (!params.fontExtraProperties && font.data) {
  2329. font.data = null;
  2330. }
  2331. this.commonObjs.resolve(id, font);
  2332. });
  2333. break;
  2334. case "FontPath":
  2335. case "Image":
  2336. this.commonObjs.resolve(id, exportedData);
  2337. break;
  2338. default:
  2339. throw new Error(`Got unknown common object type ${type}`);
  2340. }
  2341. });
  2342. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  2343. if (this.destroyed) {
  2344. return;
  2345. }
  2346. const pageProxy = this.#pageCache.get(pageIndex);
  2347. if (pageProxy.objs.has(id)) {
  2348. return;
  2349. }
  2350. switch (type) {
  2351. case "Image":
  2352. pageProxy.objs.resolve(id, imageData);
  2353. const MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2354. if (imageData) {
  2355. let length;
  2356. if (imageData.bitmap) {
  2357. const {
  2358. bitmap,
  2359. width,
  2360. height
  2361. } = imageData;
  2362. length = width * height * 4;
  2363. pageProxy._bitmaps.add(bitmap);
  2364. } else {
  2365. length = imageData.data?.length || 0;
  2366. }
  2367. if (length > MAX_IMAGE_SIZE_TO_STORE) {
  2368. pageProxy.cleanupAfterRender = true;
  2369. }
  2370. }
  2371. break;
  2372. case "Pattern":
  2373. pageProxy.objs.resolve(id, imageData);
  2374. break;
  2375. default:
  2376. throw new Error(`Got unknown object type ${type}`);
  2377. }
  2378. });
  2379. messageHandler.on("DocProgress", data => {
  2380. if (this.destroyed) {
  2381. return;
  2382. }
  2383. loadingTask.onProgress?.({
  2384. loaded: data.loaded,
  2385. total: data.total
  2386. });
  2387. });
  2388. messageHandler.on("DocStats", data => {
  2389. if (this.destroyed) {
  2390. return;
  2391. }
  2392. this.#docStats = Object.freeze({
  2393. streamTypes: Object.freeze(data.streamTypes),
  2394. fontTypes: Object.freeze(data.fontTypes)
  2395. });
  2396. });
  2397. messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
  2398. messageHandler.on("FetchBuiltInCMap", data => {
  2399. if (this.destroyed) {
  2400. return Promise.reject(new Error("Worker was destroyed."));
  2401. }
  2402. if (!this.CMapReaderFactory) {
  2403. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  2404. }
  2405. return this.CMapReaderFactory.fetch(data);
  2406. });
  2407. messageHandler.on("FetchStandardFontData", data => {
  2408. if (this.destroyed) {
  2409. return Promise.reject(new Error("Worker was destroyed."));
  2410. }
  2411. if (!this.StandardFontDataFactory) {
  2412. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  2413. }
  2414. return this.StandardFontDataFactory.fetch(data);
  2415. });
  2416. }
  2417. _onUnsupportedFeature({
  2418. featureId
  2419. }) {
  2420. if (this.destroyed) {
  2421. return;
  2422. }
  2423. this.loadingTask.onUnsupportedFeature?.(featureId);
  2424. }
  2425. getData() {
  2426. return this.messageHandler.sendWithPromise("GetData", null);
  2427. }
  2428. saveDocument() {
  2429. if (this.annotationStorage.size <= 0) {
  2430. (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  2431. }
  2432. return this.messageHandler.sendWithPromise("SaveDocument", {
  2433. isPureXfa: !!this._htmlForXfa,
  2434. numPages: this._numPages,
  2435. annotationStorage: this.annotationStorage.serializable,
  2436. filename: this._fullReader?.filename ?? null
  2437. }).finally(() => {
  2438. this.annotationStorage.resetModified();
  2439. });
  2440. }
  2441. getPage(pageNumber) {
  2442. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  2443. return Promise.reject(new Error("Invalid page request."));
  2444. }
  2445. const pageIndex = pageNumber - 1,
  2446. cachedPromise = this.#pagePromises.get(pageIndex);
  2447. if (cachedPromise) {
  2448. return cachedPromise;
  2449. }
  2450. const promise = this.messageHandler.sendWithPromise("GetPage", {
  2451. pageIndex
  2452. }).then(pageInfo => {
  2453. if (this.destroyed) {
  2454. throw new Error("Transport destroyed");
  2455. }
  2456. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
  2457. this.#pageCache.set(pageIndex, page);
  2458. return page;
  2459. });
  2460. this.#pagePromises.set(pageIndex, promise);
  2461. return promise;
  2462. }
  2463. getPageIndex(ref) {
  2464. if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
  2465. return Promise.reject(new Error("Invalid pageIndex request."));
  2466. }
  2467. return this.messageHandler.sendWithPromise("GetPageIndex", {
  2468. num: ref.num,
  2469. gen: ref.gen
  2470. });
  2471. }
  2472. getAnnotations(pageIndex, intent) {
  2473. return this.messageHandler.sendWithPromise("GetAnnotations", {
  2474. pageIndex,
  2475. intent
  2476. });
  2477. }
  2478. getFieldObjects() {
  2479. return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
  2480. }
  2481. hasJSActions() {
  2482. return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
  2483. }
  2484. getCalculationOrderIds() {
  2485. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  2486. }
  2487. getDestinations() {
  2488. return this.messageHandler.sendWithPromise("GetDestinations", null);
  2489. }
  2490. getDestination(id) {
  2491. if (typeof id !== "string") {
  2492. return Promise.reject(new Error("Invalid destination request."));
  2493. }
  2494. return this.messageHandler.sendWithPromise("GetDestination", {
  2495. id
  2496. });
  2497. }
  2498. getPageLabels() {
  2499. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  2500. }
  2501. getPageLayout() {
  2502. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  2503. }
  2504. getPageMode() {
  2505. return this.messageHandler.sendWithPromise("GetPageMode", null);
  2506. }
  2507. getViewerPreferences() {
  2508. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  2509. }
  2510. getOpenAction() {
  2511. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  2512. }
  2513. getAttachments() {
  2514. return this.messageHandler.sendWithPromise("GetAttachments", null);
  2515. }
  2516. getJavaScript() {
  2517. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  2518. }
  2519. getDocJSActions() {
  2520. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  2521. }
  2522. getPageJSActions(pageIndex) {
  2523. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  2524. pageIndex
  2525. });
  2526. }
  2527. getStructTree(pageIndex) {
  2528. return this.messageHandler.sendWithPromise("GetStructTree", {
  2529. pageIndex
  2530. });
  2531. }
  2532. getOutline() {
  2533. return this.messageHandler.sendWithPromise("GetOutline", null);
  2534. }
  2535. getOptionalContentConfig() {
  2536. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  2537. return new _optional_content_config.OptionalContentConfig(results);
  2538. });
  2539. }
  2540. getPermissions() {
  2541. return this.messageHandler.sendWithPromise("GetPermissions", null);
  2542. }
  2543. getMetadata() {
  2544. return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
  2545. return {
  2546. info: results[0],
  2547. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  2548. contentDispositionFilename: this._fullReader?.filename ?? null,
  2549. contentLength: this._fullReader?.contentLength ?? null
  2550. };
  2551. });
  2552. }
  2553. getMarkInfo() {
  2554. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  2555. }
  2556. async startCleanup(keepLoadedFonts = false) {
  2557. if (this.destroyed) {
  2558. return;
  2559. }
  2560. await this.messageHandler.sendWithPromise("Cleanup", null);
  2561. for (const page of this.#pageCache.values()) {
  2562. const cleanupSuccessful = page.cleanup();
  2563. if (!cleanupSuccessful) {
  2564. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  2565. }
  2566. }
  2567. this.commonObjs.clear();
  2568. if (!keepLoadedFonts) {
  2569. this.fontLoader.clear();
  2570. }
  2571. this.#metadataPromise = null;
  2572. this._getFieldObjectsPromise = null;
  2573. this._hasJSActionsPromise = null;
  2574. }
  2575. get loadingParams() {
  2576. const params = this._params;
  2577. return (0, _util.shadow)(this, "loadingParams", {
  2578. disableAutoFetch: params.disableAutoFetch,
  2579. enableXfa: params.enableXfa
  2580. });
  2581. }
  2582. }
  2583. class PDFObjects {
  2584. #objs = Object.create(null);
  2585. #ensureObj(objId) {
  2586. const obj = this.#objs[objId];
  2587. if (obj) {
  2588. return obj;
  2589. }
  2590. return this.#objs[objId] = {
  2591. capability: (0, _util.createPromiseCapability)(),
  2592. data: null
  2593. };
  2594. }
  2595. get(objId, callback = null) {
  2596. if (callback) {
  2597. const obj = this.#ensureObj(objId);
  2598. obj.capability.promise.then(() => callback(obj.data));
  2599. return null;
  2600. }
  2601. const obj = this.#objs[objId];
  2602. if (!obj?.capability.settled) {
  2603. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  2604. }
  2605. return obj.data;
  2606. }
  2607. has(objId) {
  2608. const obj = this.#objs[objId];
  2609. return obj?.capability.settled || false;
  2610. }
  2611. resolve(objId, data = null) {
  2612. const obj = this.#ensureObj(objId);
  2613. obj.data = data;
  2614. obj.capability.resolve();
  2615. }
  2616. clear() {
  2617. this.#objs = Object.create(null);
  2618. }
  2619. }
  2620. class RenderTask {
  2621. #internalRenderTask = null;
  2622. constructor(internalRenderTask) {
  2623. this.#internalRenderTask = internalRenderTask;
  2624. this.onContinue = null;
  2625. }
  2626. get promise() {
  2627. return this.#internalRenderTask.capability.promise;
  2628. }
  2629. cancel() {
  2630. this.#internalRenderTask.cancel();
  2631. }
  2632. get separateAnnots() {
  2633. const {
  2634. separateAnnots
  2635. } = this.#internalRenderTask.operatorList;
  2636. if (!separateAnnots) {
  2637. return false;
  2638. }
  2639. const {
  2640. annotationCanvasMap
  2641. } = this.#internalRenderTask;
  2642. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  2643. }
  2644. }
  2645. exports.RenderTask = RenderTask;
  2646. class InternalRenderTask {
  2647. static #canvasInUse = new WeakSet();
  2648. constructor({
  2649. callback,
  2650. params,
  2651. objs,
  2652. commonObjs,
  2653. annotationCanvasMap,
  2654. operatorList,
  2655. pageIndex,
  2656. canvasFactory,
  2657. useRequestAnimationFrame = false,
  2658. pdfBug = false,
  2659. pageColors = null
  2660. }) {
  2661. this.callback = callback;
  2662. this.params = params;
  2663. this.objs = objs;
  2664. this.commonObjs = commonObjs;
  2665. this.annotationCanvasMap = annotationCanvasMap;
  2666. this.operatorListIdx = null;
  2667. this.operatorList = operatorList;
  2668. this._pageIndex = pageIndex;
  2669. this.canvasFactory = canvasFactory;
  2670. this._pdfBug = pdfBug;
  2671. this.pageColors = pageColors;
  2672. this.running = false;
  2673. this.graphicsReadyCallback = null;
  2674. this.graphicsReady = false;
  2675. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  2676. this.cancelled = false;
  2677. this.capability = (0, _util.createPromiseCapability)();
  2678. this.task = new RenderTask(this);
  2679. this._cancelBound = this.cancel.bind(this);
  2680. this._continueBound = this._continue.bind(this);
  2681. this._scheduleNextBound = this._scheduleNext.bind(this);
  2682. this._nextBound = this._next.bind(this);
  2683. this._canvas = params.canvasContext.canvas;
  2684. }
  2685. get completed() {
  2686. return this.capability.promise.catch(function () {});
  2687. }
  2688. initializeGraphics({
  2689. transparency = false,
  2690. optionalContentConfig
  2691. }) {
  2692. if (this.cancelled) {
  2693. return;
  2694. }
  2695. if (this._canvas) {
  2696. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  2697. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  2698. }
  2699. InternalRenderTask.#canvasInUse.add(this._canvas);
  2700. }
  2701. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  2702. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  2703. this.stepper.init(this.operatorList);
  2704. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2705. }
  2706. const {
  2707. canvasContext,
  2708. viewport,
  2709. transform,
  2710. background
  2711. } = this.params;
  2712. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, {
  2713. optionalContentConfig
  2714. }, this.annotationCanvasMap, this.pageColors);
  2715. this.gfx.beginDrawing({
  2716. transform,
  2717. viewport,
  2718. transparency,
  2719. background
  2720. });
  2721. this.operatorListIdx = 0;
  2722. this.graphicsReady = true;
  2723. this.graphicsReadyCallback?.();
  2724. }
  2725. cancel(error = null) {
  2726. this.running = false;
  2727. this.cancelled = true;
  2728. this.gfx?.endDrawing();
  2729. if (this._canvas) {
  2730. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2731. }
  2732. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
  2733. }
  2734. operatorListChanged() {
  2735. if (!this.graphicsReady) {
  2736. if (!this.graphicsReadyCallback) {
  2737. this.graphicsReadyCallback = this._continueBound;
  2738. }
  2739. return;
  2740. }
  2741. this.stepper?.updateOperatorList(this.operatorList);
  2742. if (this.running) {
  2743. return;
  2744. }
  2745. this._continue();
  2746. }
  2747. _continue() {
  2748. this.running = true;
  2749. if (this.cancelled) {
  2750. return;
  2751. }
  2752. if (this.task.onContinue) {
  2753. this.task.onContinue(this._scheduleNextBound);
  2754. } else {
  2755. this._scheduleNext();
  2756. }
  2757. }
  2758. _scheduleNext() {
  2759. if (this._useRequestAnimationFrame) {
  2760. window.requestAnimationFrame(() => {
  2761. this._nextBound().catch(this._cancelBound);
  2762. });
  2763. } else {
  2764. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  2765. }
  2766. }
  2767. async _next() {
  2768. if (this.cancelled) {
  2769. return;
  2770. }
  2771. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  2772. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2773. this.running = false;
  2774. if (this.operatorList.lastChunk) {
  2775. this.gfx.endDrawing();
  2776. if (this._canvas) {
  2777. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2778. }
  2779. this.callback();
  2780. }
  2781. }
  2782. }
  2783. }
  2784. const version = '3.1.81';
  2785. exports.version = version;
  2786. const build = '0766898d5';
  2787. exports.build = build;
  2788. /***/ }),
  2789. /* 3 */
  2790. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2791. Object.defineProperty(exports, "__esModule", ({
  2792. value: true
  2793. }));
  2794. exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
  2795. var _util = __w_pdfjs_require__(1);
  2796. var _editor = __w_pdfjs_require__(4);
  2797. var _murmurhash = __w_pdfjs_require__(8);
  2798. class AnnotationStorage {
  2799. #modified = false;
  2800. #storage = new Map();
  2801. constructor() {
  2802. this.onSetModified = null;
  2803. this.onResetModified = null;
  2804. this.onAnnotationEditor = null;
  2805. }
  2806. getValue(key, defaultValue) {
  2807. const value = this.#storage.get(key);
  2808. if (value === undefined) {
  2809. return defaultValue;
  2810. }
  2811. return Object.assign(defaultValue, value);
  2812. }
  2813. getRawValue(key) {
  2814. return this.#storage.get(key);
  2815. }
  2816. remove(key) {
  2817. this.#storage.delete(key);
  2818. if (this.#storage.size === 0) {
  2819. this.resetModified();
  2820. }
  2821. if (typeof this.onAnnotationEditor === "function") {
  2822. for (const value of this.#storage.values()) {
  2823. if (value instanceof _editor.AnnotationEditor) {
  2824. return;
  2825. }
  2826. }
  2827. this.onAnnotationEditor(null);
  2828. }
  2829. }
  2830. setValue(key, value) {
  2831. const obj = this.#storage.get(key);
  2832. let modified = false;
  2833. if (obj !== undefined) {
  2834. for (const [entry, val] of Object.entries(value)) {
  2835. if (obj[entry] !== val) {
  2836. modified = true;
  2837. obj[entry] = val;
  2838. }
  2839. }
  2840. } else {
  2841. modified = true;
  2842. this.#storage.set(key, value);
  2843. }
  2844. if (modified) {
  2845. this.#setModified();
  2846. }
  2847. if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  2848. this.onAnnotationEditor(value.constructor._type);
  2849. }
  2850. }
  2851. has(key) {
  2852. return this.#storage.has(key);
  2853. }
  2854. getAll() {
  2855. return this.#storage.size > 0 ? (0, _util.objectFromMap)(this.#storage) : null;
  2856. }
  2857. get size() {
  2858. return this.#storage.size;
  2859. }
  2860. #setModified() {
  2861. if (!this.#modified) {
  2862. this.#modified = true;
  2863. if (typeof this.onSetModified === "function") {
  2864. this.onSetModified();
  2865. }
  2866. }
  2867. }
  2868. resetModified() {
  2869. if (this.#modified) {
  2870. this.#modified = false;
  2871. if (typeof this.onResetModified === "function") {
  2872. this.onResetModified();
  2873. }
  2874. }
  2875. }
  2876. get print() {
  2877. return new PrintAnnotationStorage(this);
  2878. }
  2879. get serializable() {
  2880. if (this.#storage.size === 0) {
  2881. return null;
  2882. }
  2883. const clone = new Map();
  2884. for (const [key, val] of this.#storage) {
  2885. const serialized = val instanceof _editor.AnnotationEditor ? val.serialize() : val;
  2886. if (serialized) {
  2887. clone.set(key, serialized);
  2888. }
  2889. }
  2890. return clone;
  2891. }
  2892. static getHash(map) {
  2893. if (!map) {
  2894. return "";
  2895. }
  2896. const hash = new _murmurhash.MurmurHash3_64();
  2897. for (const [key, val] of map) {
  2898. hash.update(`${key}:${JSON.stringify(val)}`);
  2899. }
  2900. return hash.hexdigest();
  2901. }
  2902. }
  2903. exports.AnnotationStorage = AnnotationStorage;
  2904. class PrintAnnotationStorage extends AnnotationStorage {
  2905. #serializable = null;
  2906. constructor(parent) {
  2907. super();
  2908. this.#serializable = structuredClone(parent.serializable);
  2909. }
  2910. get print() {
  2911. (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
  2912. }
  2913. get serializable() {
  2914. return this.#serializable;
  2915. }
  2916. }
  2917. exports.PrintAnnotationStorage = PrintAnnotationStorage;
  2918. /***/ }),
  2919. /* 4 */
  2920. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2921. Object.defineProperty(exports, "__esModule", ({
  2922. value: true
  2923. }));
  2924. exports.AnnotationEditor = void 0;
  2925. var _tools = __w_pdfjs_require__(5);
  2926. var _util = __w_pdfjs_require__(1);
  2927. class AnnotationEditor {
  2928. #boundFocusin = this.focusin.bind(this);
  2929. #boundFocusout = this.focusout.bind(this);
  2930. #hasBeenSelected = false;
  2931. #isEditing = false;
  2932. #isInEditMode = false;
  2933. #zIndex = AnnotationEditor._zIndex++;
  2934. static _colorManager = new _tools.ColorManager();
  2935. static _zIndex = 1;
  2936. constructor(parameters) {
  2937. if (this.constructor === AnnotationEditor) {
  2938. (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
  2939. }
  2940. this.parent = parameters.parent;
  2941. this.id = parameters.id;
  2942. this.width = this.height = null;
  2943. this.pageIndex = parameters.parent.pageIndex;
  2944. this.name = parameters.name;
  2945. this.div = null;
  2946. const [width, height] = this.parent.viewportBaseDimensions;
  2947. this.x = parameters.x / width;
  2948. this.y = parameters.y / height;
  2949. this.rotation = this.parent.viewport.rotation;
  2950. this.isAttachedToDOM = false;
  2951. }
  2952. static get _defaultLineColor() {
  2953. return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  2954. }
  2955. setInBackground() {
  2956. this.div.style.zIndex = 0;
  2957. }
  2958. setInForeground() {
  2959. this.div.style.zIndex = this.#zIndex;
  2960. }
  2961. focusin(event) {
  2962. if (!this.#hasBeenSelected) {
  2963. this.parent.setSelected(this);
  2964. } else {
  2965. this.#hasBeenSelected = false;
  2966. }
  2967. }
  2968. focusout(event) {
  2969. if (!this.isAttachedToDOM) {
  2970. return;
  2971. }
  2972. const target = event.relatedTarget;
  2973. if (target?.closest(`#${this.id}`)) {
  2974. return;
  2975. }
  2976. event.preventDefault();
  2977. if (!this.parent.isMultipleSelection) {
  2978. this.commitOrRemove();
  2979. }
  2980. }
  2981. commitOrRemove() {
  2982. if (this.isEmpty()) {
  2983. this.remove();
  2984. } else {
  2985. this.commit();
  2986. }
  2987. }
  2988. commit() {
  2989. this.parent.addToAnnotationStorage(this);
  2990. }
  2991. dragstart(event) {
  2992. const rect = this.parent.div.getBoundingClientRect();
  2993. this.startX = event.clientX - rect.x;
  2994. this.startY = event.clientY - rect.y;
  2995. event.dataTransfer.setData("text/plain", this.id);
  2996. event.dataTransfer.effectAllowed = "move";
  2997. }
  2998. setAt(x, y, tx, ty) {
  2999. const [width, height] = this.parent.viewportBaseDimensions;
  3000. [tx, ty] = this.screenToPageTranslation(tx, ty);
  3001. this.x = (x + tx) / width;
  3002. this.y = (y + ty) / height;
  3003. this.div.style.left = `${100 * this.x}%`;
  3004. this.div.style.top = `${100 * this.y}%`;
  3005. }
  3006. translate(x, y) {
  3007. const [width, height] = this.parent.viewportBaseDimensions;
  3008. [x, y] = this.screenToPageTranslation(x, y);
  3009. this.x += x / width;
  3010. this.y += y / height;
  3011. this.div.style.left = `${100 * this.x}%`;
  3012. this.div.style.top = `${100 * this.y}%`;
  3013. }
  3014. screenToPageTranslation(x, y) {
  3015. const {
  3016. rotation
  3017. } = this.parent.viewport;
  3018. switch (rotation) {
  3019. case 90:
  3020. return [y, -x];
  3021. case 180:
  3022. return [-x, -y];
  3023. case 270:
  3024. return [-y, x];
  3025. default:
  3026. return [x, y];
  3027. }
  3028. }
  3029. setDims(width, height) {
  3030. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3031. this.div.style.width = `${100 * width / parentWidth}%`;
  3032. this.div.style.height = `${100 * height / parentHeight}%`;
  3033. }
  3034. fixDims() {
  3035. const {
  3036. style
  3037. } = this.div;
  3038. const {
  3039. height,
  3040. width
  3041. } = style;
  3042. const widthPercent = width.endsWith("%");
  3043. const heightPercent = height.endsWith("%");
  3044. if (widthPercent && heightPercent) {
  3045. return;
  3046. }
  3047. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3048. if (!widthPercent) {
  3049. style.width = `${100 * parseFloat(width) / parentWidth}%`;
  3050. }
  3051. if (!heightPercent) {
  3052. style.height = `${100 * parseFloat(height) / parentHeight}%`;
  3053. }
  3054. }
  3055. getInitialTranslation() {
  3056. return [0, 0];
  3057. }
  3058. render() {
  3059. this.div = document.createElement("div");
  3060. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  3061. this.div.className = this.name;
  3062. this.div.setAttribute("id", this.id);
  3063. this.div.setAttribute("tabIndex", 0);
  3064. this.setInForeground();
  3065. this.div.addEventListener("focusin", this.#boundFocusin);
  3066. this.div.addEventListener("focusout", this.#boundFocusout);
  3067. const [tx, ty] = this.getInitialTranslation();
  3068. this.translate(tx, ty);
  3069. (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
  3070. return this.div;
  3071. }
  3072. pointerdown(event) {
  3073. const isMac = _tools.KeyboardManager.platform.isMac;
  3074. if (event.button !== 0 || event.ctrlKey && isMac) {
  3075. event.preventDefault();
  3076. return;
  3077. }
  3078. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  3079. this.parent.toggleSelected(this);
  3080. } else {
  3081. this.parent.setSelected(this);
  3082. }
  3083. this.#hasBeenSelected = true;
  3084. }
  3085. getRect(tx, ty) {
  3086. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3087. const [pageWidth, pageHeight] = this.parent.pageDimensions;
  3088. const shiftX = pageWidth * tx / parentWidth;
  3089. const shiftY = pageHeight * ty / parentHeight;
  3090. const x = this.x * pageWidth;
  3091. const y = this.y * pageHeight;
  3092. const width = this.width * pageWidth;
  3093. const height = this.height * pageHeight;
  3094. switch (this.rotation) {
  3095. case 0:
  3096. return [x + shiftX, pageHeight - y - shiftY - height, x + shiftX + width, pageHeight - y - shiftY];
  3097. case 90:
  3098. return [x + shiftY, pageHeight - y + shiftX, x + shiftY + height, pageHeight - y + shiftX + width];
  3099. case 180:
  3100. return [x - shiftX - width, pageHeight - y + shiftY, x - shiftX, pageHeight - y + shiftY + height];
  3101. case 270:
  3102. return [x - shiftY - height, pageHeight - y - shiftX - width, x - shiftY, pageHeight - y - shiftX];
  3103. default:
  3104. throw new Error("Invalid rotation");
  3105. }
  3106. }
  3107. getRectInCurrentCoords(rect, pageHeight) {
  3108. const [x1, y1, x2, y2] = rect;
  3109. const width = x2 - x1;
  3110. const height = y2 - y1;
  3111. switch (this.rotation) {
  3112. case 0:
  3113. return [x1, pageHeight - y2, width, height];
  3114. case 90:
  3115. return [x1, pageHeight - y1, height, width];
  3116. case 180:
  3117. return [x2, pageHeight - y1, width, height];
  3118. case 270:
  3119. return [x2, pageHeight - y2, height, width];
  3120. default:
  3121. throw new Error("Invalid rotation");
  3122. }
  3123. }
  3124. onceAdded() {}
  3125. isEmpty() {
  3126. return false;
  3127. }
  3128. enableEditMode() {
  3129. this.#isInEditMode = true;
  3130. }
  3131. disableEditMode() {
  3132. this.#isInEditMode = false;
  3133. }
  3134. isInEditMode() {
  3135. return this.#isInEditMode;
  3136. }
  3137. shouldGetKeyboardEvents() {
  3138. return false;
  3139. }
  3140. needsToBeRebuilt() {
  3141. return this.div && !this.isAttachedToDOM;
  3142. }
  3143. rebuild() {
  3144. this.div?.addEventListener("focusin", this.#boundFocusin);
  3145. }
  3146. serialize() {
  3147. (0, _util.unreachable)("An editor must be serializable");
  3148. }
  3149. static deserialize(data, parent) {
  3150. const editor = new this.prototype.constructor({
  3151. parent,
  3152. id: parent.getNextId()
  3153. });
  3154. editor.rotation = data.rotation;
  3155. const [pageWidth, pageHeight] = parent.pageDimensions;
  3156. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  3157. editor.x = x / pageWidth;
  3158. editor.y = y / pageHeight;
  3159. editor.width = width / pageWidth;
  3160. editor.height = height / pageHeight;
  3161. return editor;
  3162. }
  3163. remove() {
  3164. this.div.removeEventListener("focusin", this.#boundFocusin);
  3165. this.div.removeEventListener("focusout", this.#boundFocusout);
  3166. if (!this.isEmpty()) {
  3167. this.commit();
  3168. }
  3169. this.parent.remove(this);
  3170. }
  3171. select() {
  3172. this.div?.classList.add("selectedEditor");
  3173. }
  3174. unselect() {
  3175. this.div?.classList.remove("selectedEditor");
  3176. }
  3177. updateParams(type, value) {}
  3178. disableEditing() {}
  3179. enableEditing() {}
  3180. get propertiesToUpdate() {
  3181. return {};
  3182. }
  3183. get contentDiv() {
  3184. return this.div;
  3185. }
  3186. get isEditing() {
  3187. return this.#isEditing;
  3188. }
  3189. set isEditing(value) {
  3190. this.#isEditing = value;
  3191. if (value) {
  3192. this.parent.setSelected(this);
  3193. this.parent.setActiveEditor(this);
  3194. } else {
  3195. this.parent.setActiveEditor(null);
  3196. }
  3197. }
  3198. }
  3199. exports.AnnotationEditor = AnnotationEditor;
  3200. /***/ }),
  3201. /* 5 */
  3202. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3203. Object.defineProperty(exports, "__esModule", ({
  3204. value: true
  3205. }));
  3206. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  3207. exports.bindEvents = bindEvents;
  3208. exports.opacityToHex = opacityToHex;
  3209. var _util = __w_pdfjs_require__(1);
  3210. var _display_utils = __w_pdfjs_require__(6);
  3211. function bindEvents(obj, element, names) {
  3212. for (const name of names) {
  3213. element.addEventListener(name, obj[name].bind(obj));
  3214. }
  3215. }
  3216. function opacityToHex(opacity) {
  3217. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  3218. }
  3219. class IdManager {
  3220. #id = 0;
  3221. getId() {
  3222. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  3223. }
  3224. }
  3225. class CommandManager {
  3226. #commands = [];
  3227. #locked = false;
  3228. #maxSize;
  3229. #position = -1;
  3230. constructor(maxSize = 128) {
  3231. this.#maxSize = maxSize;
  3232. }
  3233. add({
  3234. cmd,
  3235. undo,
  3236. mustExec,
  3237. type = NaN,
  3238. overwriteIfSameType = false,
  3239. keepUndo = false
  3240. }) {
  3241. if (mustExec) {
  3242. cmd();
  3243. }
  3244. if (this.#locked) {
  3245. return;
  3246. }
  3247. const save = {
  3248. cmd,
  3249. undo,
  3250. type
  3251. };
  3252. if (this.#position === -1) {
  3253. if (this.#commands.length > 0) {
  3254. this.#commands.length = 0;
  3255. }
  3256. this.#position = 0;
  3257. this.#commands.push(save);
  3258. return;
  3259. }
  3260. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  3261. if (keepUndo) {
  3262. save.undo = this.#commands[this.#position].undo;
  3263. }
  3264. this.#commands[this.#position] = save;
  3265. return;
  3266. }
  3267. const next = this.#position + 1;
  3268. if (next === this.#maxSize) {
  3269. this.#commands.splice(0, 1);
  3270. } else {
  3271. this.#position = next;
  3272. if (next < this.#commands.length) {
  3273. this.#commands.splice(next);
  3274. }
  3275. }
  3276. this.#commands.push(save);
  3277. }
  3278. undo() {
  3279. if (this.#position === -1) {
  3280. return;
  3281. }
  3282. this.#locked = true;
  3283. this.#commands[this.#position].undo();
  3284. this.#locked = false;
  3285. this.#position -= 1;
  3286. }
  3287. redo() {
  3288. if (this.#position < this.#commands.length - 1) {
  3289. this.#position += 1;
  3290. this.#locked = true;
  3291. this.#commands[this.#position].cmd();
  3292. this.#locked = false;
  3293. }
  3294. }
  3295. hasSomethingToUndo() {
  3296. return this.#position !== -1;
  3297. }
  3298. hasSomethingToRedo() {
  3299. return this.#position < this.#commands.length - 1;
  3300. }
  3301. destroy() {
  3302. this.#commands = null;
  3303. }
  3304. }
  3305. exports.CommandManager = CommandManager;
  3306. class KeyboardManager {
  3307. constructor(callbacks) {
  3308. this.buffer = [];
  3309. this.callbacks = new Map();
  3310. this.allKeys = new Set();
  3311. const isMac = KeyboardManager.platform.isMac;
  3312. for (const [keys, callback] of callbacks) {
  3313. for (const key of keys) {
  3314. const isMacKey = key.startsWith("mac+");
  3315. if (isMac && isMacKey) {
  3316. this.callbacks.set(key.slice(4), callback);
  3317. this.allKeys.add(key.split("+").at(-1));
  3318. } else if (!isMac && !isMacKey) {
  3319. this.callbacks.set(key, callback);
  3320. this.allKeys.add(key.split("+").at(-1));
  3321. }
  3322. }
  3323. }
  3324. }
  3325. static get platform() {
  3326. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  3327. return (0, _util.shadow)(this, "platform", {
  3328. isWin: platform.includes("Win"),
  3329. isMac: platform.includes("Mac")
  3330. });
  3331. }
  3332. #serialize(event) {
  3333. if (event.altKey) {
  3334. this.buffer.push("alt");
  3335. }
  3336. if (event.ctrlKey) {
  3337. this.buffer.push("ctrl");
  3338. }
  3339. if (event.metaKey) {
  3340. this.buffer.push("meta");
  3341. }
  3342. if (event.shiftKey) {
  3343. this.buffer.push("shift");
  3344. }
  3345. this.buffer.push(event.key);
  3346. const str = this.buffer.join("+");
  3347. this.buffer.length = 0;
  3348. return str;
  3349. }
  3350. exec(self, event) {
  3351. if (!this.allKeys.has(event.key)) {
  3352. return;
  3353. }
  3354. const callback = this.callbacks.get(this.#serialize(event));
  3355. if (!callback) {
  3356. return;
  3357. }
  3358. callback.bind(self)();
  3359. event.stopPropagation();
  3360. event.preventDefault();
  3361. }
  3362. }
  3363. exports.KeyboardManager = KeyboardManager;
  3364. class ColorManager {
  3365. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  3366. get _colors() {
  3367. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  3368. (0, _display_utils.getColorValues)(colors);
  3369. return (0, _util.shadow)(this, "_colors", colors);
  3370. }
  3371. convert(color) {
  3372. const rgb = (0, _display_utils.getRGB)(color);
  3373. if (!window.matchMedia("(forced-colors: active)").matches) {
  3374. return rgb;
  3375. }
  3376. for (const [name, RGB] of this._colors) {
  3377. if (RGB.every((x, i) => x === rgb[i])) {
  3378. return ColorManager._colorsMapping.get(name);
  3379. }
  3380. }
  3381. return rgb;
  3382. }
  3383. getHexCode(name) {
  3384. const rgb = this._colors.get(name);
  3385. if (!rgb) {
  3386. return name;
  3387. }
  3388. return _util.Util.makeHexColor(...rgb);
  3389. }
  3390. }
  3391. exports.ColorManager = ColorManager;
  3392. class AnnotationEditorUIManager {
  3393. #activeEditor = null;
  3394. #allEditors = new Map();
  3395. #allLayers = new Map();
  3396. #commandManager = new CommandManager();
  3397. #currentPageIndex = 0;
  3398. #editorTypes = null;
  3399. #eventBus = null;
  3400. #idManager = new IdManager();
  3401. #isEnabled = false;
  3402. #mode = _util.AnnotationEditorType.NONE;
  3403. #selectedEditors = new Set();
  3404. #boundCopy = this.copy.bind(this);
  3405. #boundCut = this.cut.bind(this);
  3406. #boundPaste = this.paste.bind(this);
  3407. #boundKeydown = this.keydown.bind(this);
  3408. #boundOnEditingAction = this.onEditingAction.bind(this);
  3409. #boundOnPageChanging = this.onPageChanging.bind(this);
  3410. #previousStates = {
  3411. isEditing: false,
  3412. isEmpty: true,
  3413. hasSomethingToUndo: false,
  3414. hasSomethingToRedo: false,
  3415. hasSelectedEditor: false
  3416. };
  3417. #container = null;
  3418. 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]]);
  3419. constructor(container, eventBus) {
  3420. this.#container = container;
  3421. this.#eventBus = eventBus;
  3422. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  3423. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  3424. }
  3425. destroy() {
  3426. this.#removeKeyboardManager();
  3427. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  3428. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  3429. for (const layer of this.#allLayers.values()) {
  3430. layer.destroy();
  3431. }
  3432. this.#allLayers.clear();
  3433. this.#allEditors.clear();
  3434. this.#activeEditor = null;
  3435. this.#selectedEditors.clear();
  3436. this.#commandManager.destroy();
  3437. }
  3438. onPageChanging({
  3439. pageNumber
  3440. }) {
  3441. this.#currentPageIndex = pageNumber - 1;
  3442. }
  3443. focusMainContainer() {
  3444. this.#container.focus();
  3445. }
  3446. #addKeyboardManager() {
  3447. this.#container.addEventListener("keydown", this.#boundKeydown);
  3448. }
  3449. #removeKeyboardManager() {
  3450. this.#container.removeEventListener("keydown", this.#boundKeydown);
  3451. }
  3452. #addCopyPasteListeners() {
  3453. document.addEventListener("copy", this.#boundCopy);
  3454. document.addEventListener("cut", this.#boundCut);
  3455. document.addEventListener("paste", this.#boundPaste);
  3456. }
  3457. #removeCopyPasteListeners() {
  3458. document.removeEventListener("copy", this.#boundCopy);
  3459. document.removeEventListener("cut", this.#boundCut);
  3460. document.removeEventListener("paste", this.#boundPaste);
  3461. }
  3462. copy(event) {
  3463. event.preventDefault();
  3464. if (this.#activeEditor) {
  3465. this.#activeEditor.commitOrRemove();
  3466. }
  3467. if (!this.hasSelection) {
  3468. return;
  3469. }
  3470. const editors = [];
  3471. for (const editor of this.#selectedEditors) {
  3472. if (!editor.isEmpty()) {
  3473. editors.push(editor.serialize());
  3474. }
  3475. }
  3476. if (editors.length === 0) {
  3477. return;
  3478. }
  3479. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  3480. }
  3481. cut(event) {
  3482. this.copy(event);
  3483. this.delete();
  3484. }
  3485. paste(event) {
  3486. event.preventDefault();
  3487. let data = event.clipboardData.getData("application/pdfjs");
  3488. if (!data) {
  3489. return;
  3490. }
  3491. try {
  3492. data = JSON.parse(data);
  3493. } catch (ex) {
  3494. (0, _util.warn)(`paste: "${ex.message}".`);
  3495. return;
  3496. }
  3497. if (!Array.isArray(data)) {
  3498. return;
  3499. }
  3500. this.unselectAll();
  3501. const layer = this.#allLayers.get(this.#currentPageIndex);
  3502. try {
  3503. const newEditors = [];
  3504. for (const editor of data) {
  3505. const deserializedEditor = layer.deserialize(editor);
  3506. if (!deserializedEditor) {
  3507. return;
  3508. }
  3509. newEditors.push(deserializedEditor);
  3510. }
  3511. const cmd = () => {
  3512. for (const editor of newEditors) {
  3513. this.#addEditorToLayer(editor);
  3514. }
  3515. this.#selectEditors(newEditors);
  3516. };
  3517. const undo = () => {
  3518. for (const editor of newEditors) {
  3519. editor.remove();
  3520. }
  3521. };
  3522. this.addCommands({
  3523. cmd,
  3524. undo,
  3525. mustExec: true
  3526. });
  3527. } catch (ex) {
  3528. (0, _util.warn)(`paste: "${ex.message}".`);
  3529. }
  3530. }
  3531. keydown(event) {
  3532. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  3533. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  3534. }
  3535. }
  3536. onEditingAction(details) {
  3537. if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
  3538. this[details.name]();
  3539. }
  3540. }
  3541. #dispatchUpdateStates(details) {
  3542. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  3543. if (hasChanged) {
  3544. this.#eventBus.dispatch("annotationeditorstateschanged", {
  3545. source: this,
  3546. details: Object.assign(this.#previousStates, details)
  3547. });
  3548. }
  3549. }
  3550. #dispatchUpdateUI(details) {
  3551. this.#eventBus.dispatch("annotationeditorparamschanged", {
  3552. source: this,
  3553. details
  3554. });
  3555. }
  3556. setEditingState(isEditing) {
  3557. if (isEditing) {
  3558. this.#addKeyboardManager();
  3559. this.#addCopyPasteListeners();
  3560. this.#dispatchUpdateStates({
  3561. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  3562. isEmpty: this.#isEmpty(),
  3563. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3564. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3565. hasSelectedEditor: false
  3566. });
  3567. } else {
  3568. this.#removeKeyboardManager();
  3569. this.#removeCopyPasteListeners();
  3570. this.#dispatchUpdateStates({
  3571. isEditing: false
  3572. });
  3573. }
  3574. }
  3575. registerEditorTypes(types) {
  3576. if (this.#editorTypes) {
  3577. return;
  3578. }
  3579. this.#editorTypes = types;
  3580. for (const editorType of this.#editorTypes) {
  3581. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  3582. }
  3583. }
  3584. getId() {
  3585. return this.#idManager.getId();
  3586. }
  3587. addLayer(layer) {
  3588. this.#allLayers.set(layer.pageIndex, layer);
  3589. if (this.#isEnabled) {
  3590. layer.enable();
  3591. } else {
  3592. layer.disable();
  3593. }
  3594. }
  3595. removeLayer(layer) {
  3596. this.#allLayers.delete(layer.pageIndex);
  3597. }
  3598. updateMode(mode) {
  3599. this.#mode = mode;
  3600. if (mode === _util.AnnotationEditorType.NONE) {
  3601. this.setEditingState(false);
  3602. this.#disableAll();
  3603. } else {
  3604. this.setEditingState(true);
  3605. this.#enableAll();
  3606. for (const layer of this.#allLayers.values()) {
  3607. layer.updateMode(mode);
  3608. }
  3609. }
  3610. }
  3611. updateToolbar(mode) {
  3612. if (mode === this.#mode) {
  3613. return;
  3614. }
  3615. this.#eventBus.dispatch("switchannotationeditormode", {
  3616. source: this,
  3617. mode
  3618. });
  3619. }
  3620. updateParams(type, value) {
  3621. if (!this.#editorTypes) {
  3622. return;
  3623. }
  3624. for (const editor of this.#selectedEditors) {
  3625. editor.updateParams(type, value);
  3626. }
  3627. for (const editorType of this.#editorTypes) {
  3628. editorType.updateDefaultParams(type, value);
  3629. }
  3630. }
  3631. #enableAll() {
  3632. if (!this.#isEnabled) {
  3633. this.#isEnabled = true;
  3634. for (const layer of this.#allLayers.values()) {
  3635. layer.enable();
  3636. }
  3637. }
  3638. }
  3639. #disableAll() {
  3640. this.unselectAll();
  3641. if (this.#isEnabled) {
  3642. this.#isEnabled = false;
  3643. for (const layer of this.#allLayers.values()) {
  3644. layer.disable();
  3645. }
  3646. }
  3647. }
  3648. getEditors(pageIndex) {
  3649. const editors = [];
  3650. for (const editor of this.#allEditors.values()) {
  3651. if (editor.pageIndex === pageIndex) {
  3652. editors.push(editor);
  3653. }
  3654. }
  3655. return editors;
  3656. }
  3657. getEditor(id) {
  3658. return this.#allEditors.get(id);
  3659. }
  3660. addEditor(editor) {
  3661. this.#allEditors.set(editor.id, editor);
  3662. }
  3663. removeEditor(editor) {
  3664. this.#allEditors.delete(editor.id);
  3665. this.unselect(editor);
  3666. }
  3667. #addEditorToLayer(editor) {
  3668. const layer = this.#allLayers.get(editor.pageIndex);
  3669. if (layer) {
  3670. layer.addOrRebuild(editor);
  3671. } else {
  3672. this.addEditor(editor);
  3673. }
  3674. }
  3675. setActiveEditor(editor) {
  3676. if (this.#activeEditor === editor) {
  3677. return;
  3678. }
  3679. this.#activeEditor = editor;
  3680. if (editor) {
  3681. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3682. }
  3683. }
  3684. toggleSelected(editor) {
  3685. if (this.#selectedEditors.has(editor)) {
  3686. this.#selectedEditors.delete(editor);
  3687. editor.unselect();
  3688. this.#dispatchUpdateStates({
  3689. hasSelectedEditor: this.hasSelection
  3690. });
  3691. return;
  3692. }
  3693. this.#selectedEditors.add(editor);
  3694. editor.select();
  3695. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3696. this.#dispatchUpdateStates({
  3697. hasSelectedEditor: true
  3698. });
  3699. }
  3700. setSelected(editor) {
  3701. for (const ed of this.#selectedEditors) {
  3702. if (ed !== editor) {
  3703. ed.unselect();
  3704. }
  3705. }
  3706. this.#selectedEditors.clear();
  3707. this.#selectedEditors.add(editor);
  3708. editor.select();
  3709. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3710. this.#dispatchUpdateStates({
  3711. hasSelectedEditor: true
  3712. });
  3713. }
  3714. isSelected(editor) {
  3715. return this.#selectedEditors.has(editor);
  3716. }
  3717. unselect(editor) {
  3718. editor.unselect();
  3719. this.#selectedEditors.delete(editor);
  3720. this.#dispatchUpdateStates({
  3721. hasSelectedEditor: this.hasSelection
  3722. });
  3723. }
  3724. get hasSelection() {
  3725. return this.#selectedEditors.size !== 0;
  3726. }
  3727. undo() {
  3728. this.#commandManager.undo();
  3729. this.#dispatchUpdateStates({
  3730. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3731. hasSomethingToRedo: true,
  3732. isEmpty: this.#isEmpty()
  3733. });
  3734. }
  3735. redo() {
  3736. this.#commandManager.redo();
  3737. this.#dispatchUpdateStates({
  3738. hasSomethingToUndo: true,
  3739. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3740. isEmpty: this.#isEmpty()
  3741. });
  3742. }
  3743. addCommands(params) {
  3744. this.#commandManager.add(params);
  3745. this.#dispatchUpdateStates({
  3746. hasSomethingToUndo: true,
  3747. hasSomethingToRedo: false,
  3748. isEmpty: this.#isEmpty()
  3749. });
  3750. }
  3751. #isEmpty() {
  3752. if (this.#allEditors.size === 0) {
  3753. return true;
  3754. }
  3755. if (this.#allEditors.size === 1) {
  3756. for (const editor of this.#allEditors.values()) {
  3757. return editor.isEmpty();
  3758. }
  3759. }
  3760. return false;
  3761. }
  3762. delete() {
  3763. this.commitOrRemove();
  3764. if (!this.hasSelection) {
  3765. return;
  3766. }
  3767. const editors = [...this.#selectedEditors];
  3768. const cmd = () => {
  3769. for (const editor of editors) {
  3770. editor.remove();
  3771. }
  3772. };
  3773. const undo = () => {
  3774. for (const editor of editors) {
  3775. this.#addEditorToLayer(editor);
  3776. }
  3777. };
  3778. this.addCommands({
  3779. cmd,
  3780. undo,
  3781. mustExec: true
  3782. });
  3783. }
  3784. commitOrRemove() {
  3785. this.#activeEditor?.commitOrRemove();
  3786. }
  3787. #selectEditors(editors) {
  3788. this.#selectedEditors.clear();
  3789. for (const editor of editors) {
  3790. if (editor.isEmpty()) {
  3791. continue;
  3792. }
  3793. this.#selectedEditors.add(editor);
  3794. editor.select();
  3795. }
  3796. this.#dispatchUpdateStates({
  3797. hasSelectedEditor: true
  3798. });
  3799. }
  3800. selectAll() {
  3801. for (const editor of this.#selectedEditors) {
  3802. editor.commit();
  3803. }
  3804. this.#selectEditors(this.#allEditors.values());
  3805. }
  3806. unselectAll() {
  3807. if (this.#activeEditor) {
  3808. this.#activeEditor.commitOrRemove();
  3809. return;
  3810. }
  3811. if (this.#selectedEditors.size === 0) {
  3812. return;
  3813. }
  3814. for (const editor of this.#selectedEditors) {
  3815. editor.unselect();
  3816. }
  3817. this.#selectedEditors.clear();
  3818. this.#dispatchUpdateStates({
  3819. hasSelectedEditor: false
  3820. });
  3821. }
  3822. isActive(editor) {
  3823. return this.#activeEditor === editor;
  3824. }
  3825. getActive() {
  3826. return this.#activeEditor;
  3827. }
  3828. getMode() {
  3829. return this.#mode;
  3830. }
  3831. }
  3832. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
  3833. /***/ }),
  3834. /* 6 */
  3835. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3836. Object.defineProperty(exports, "__esModule", ({
  3837. value: true
  3838. }));
  3839. exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
  3840. exports.deprecated = deprecated;
  3841. exports.getColorValues = getColorValues;
  3842. exports.getCurrentTransform = getCurrentTransform;
  3843. exports.getCurrentTransformInverse = getCurrentTransformInverse;
  3844. exports.getFilenameFromUrl = getFilenameFromUrl;
  3845. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  3846. exports.getRGB = getRGB;
  3847. exports.getXfaPageViewport = getXfaPageViewport;
  3848. exports.isDataScheme = isDataScheme;
  3849. exports.isPdfFile = isPdfFile;
  3850. exports.isValidFetchUrl = isValidFetchUrl;
  3851. exports.loadScript = loadScript;
  3852. var _base_factory = __w_pdfjs_require__(7);
  3853. var _util = __w_pdfjs_require__(1);
  3854. const SVG_NS = "http://www.w3.org/2000/svg";
  3855. const AnnotationPrefix = "pdfjs_internal_id_";
  3856. exports.AnnotationPrefix = AnnotationPrefix;
  3857. class PixelsPerInch {
  3858. static CSS = 96.0;
  3859. static PDF = 72.0;
  3860. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  3861. }
  3862. exports.PixelsPerInch = PixelsPerInch;
  3863. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  3864. constructor({
  3865. ownerDocument = globalThis.document
  3866. } = {}) {
  3867. super();
  3868. this._document = ownerDocument;
  3869. }
  3870. _createCanvas(width, height) {
  3871. const canvas = this._document.createElement("canvas");
  3872. canvas.width = width;
  3873. canvas.height = height;
  3874. return canvas;
  3875. }
  3876. }
  3877. exports.DOMCanvasFactory = DOMCanvasFactory;
  3878. async function fetchData(url, asTypedArray = false) {
  3879. if (isValidFetchUrl(url, document.baseURI)) {
  3880. const response = await fetch(url);
  3881. if (!response.ok) {
  3882. throw new Error(response.statusText);
  3883. }
  3884. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  3885. }
  3886. return new Promise((resolve, reject) => {
  3887. const request = new XMLHttpRequest();
  3888. request.open("GET", url, true);
  3889. if (asTypedArray) {
  3890. request.responseType = "arraybuffer";
  3891. }
  3892. request.onreadystatechange = () => {
  3893. if (request.readyState !== XMLHttpRequest.DONE) {
  3894. return;
  3895. }
  3896. if (request.status === 200 || request.status === 0) {
  3897. let data;
  3898. if (asTypedArray && request.response) {
  3899. data = new Uint8Array(request.response);
  3900. } else if (!asTypedArray && request.responseText) {
  3901. data = (0, _util.stringToBytes)(request.responseText);
  3902. }
  3903. if (data) {
  3904. resolve(data);
  3905. return;
  3906. }
  3907. }
  3908. reject(new Error(request.statusText));
  3909. };
  3910. request.send(null);
  3911. });
  3912. }
  3913. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  3914. _fetchData(url, compressionType) {
  3915. return fetchData(url, this.isCompressed).then(data => {
  3916. return {
  3917. cMapData: data,
  3918. compressionType
  3919. };
  3920. });
  3921. }
  3922. }
  3923. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  3924. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  3925. _fetchData(url) {
  3926. return fetchData(url, true);
  3927. }
  3928. }
  3929. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  3930. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  3931. _createSVG(type) {
  3932. return document.createElementNS(SVG_NS, type);
  3933. }
  3934. }
  3935. exports.DOMSVGFactory = DOMSVGFactory;
  3936. class PageViewport {
  3937. constructor({
  3938. viewBox,
  3939. scale,
  3940. rotation,
  3941. offsetX = 0,
  3942. offsetY = 0,
  3943. dontFlip = false
  3944. }) {
  3945. this.viewBox = viewBox;
  3946. this.scale = scale;
  3947. this.rotation = rotation;
  3948. this.offsetX = offsetX;
  3949. this.offsetY = offsetY;
  3950. const centerX = (viewBox[2] + viewBox[0]) / 2;
  3951. const centerY = (viewBox[3] + viewBox[1]) / 2;
  3952. let rotateA, rotateB, rotateC, rotateD;
  3953. rotation %= 360;
  3954. if (rotation < 0) {
  3955. rotation += 360;
  3956. }
  3957. switch (rotation) {
  3958. case 180:
  3959. rotateA = -1;
  3960. rotateB = 0;
  3961. rotateC = 0;
  3962. rotateD = 1;
  3963. break;
  3964. case 90:
  3965. rotateA = 0;
  3966. rotateB = 1;
  3967. rotateC = 1;
  3968. rotateD = 0;
  3969. break;
  3970. case 270:
  3971. rotateA = 0;
  3972. rotateB = -1;
  3973. rotateC = -1;
  3974. rotateD = 0;
  3975. break;
  3976. case 0:
  3977. rotateA = 1;
  3978. rotateB = 0;
  3979. rotateC = 0;
  3980. rotateD = -1;
  3981. break;
  3982. default:
  3983. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  3984. }
  3985. if (dontFlip) {
  3986. rotateC = -rotateC;
  3987. rotateD = -rotateD;
  3988. }
  3989. let offsetCanvasX, offsetCanvasY;
  3990. let width, height;
  3991. if (rotateA === 0) {
  3992. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  3993. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  3994. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  3995. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  3996. } else {
  3997. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  3998. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  3999. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  4000. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  4001. }
  4002. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  4003. this.width = width;
  4004. this.height = height;
  4005. }
  4006. clone({
  4007. scale = this.scale,
  4008. rotation = this.rotation,
  4009. offsetX = this.offsetX,
  4010. offsetY = this.offsetY,
  4011. dontFlip = false
  4012. } = {}) {
  4013. return new PageViewport({
  4014. viewBox: this.viewBox.slice(),
  4015. scale,
  4016. rotation,
  4017. offsetX,
  4018. offsetY,
  4019. dontFlip
  4020. });
  4021. }
  4022. convertToViewportPoint(x, y) {
  4023. return _util.Util.applyTransform([x, y], this.transform);
  4024. }
  4025. convertToViewportRectangle(rect) {
  4026. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  4027. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  4028. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  4029. }
  4030. convertToPdfPoint(x, y) {
  4031. return _util.Util.applyInverseTransform([x, y], this.transform);
  4032. }
  4033. }
  4034. exports.PageViewport = PageViewport;
  4035. class RenderingCancelledException extends _util.BaseException {
  4036. constructor(msg, type) {
  4037. super(msg, "RenderingCancelledException");
  4038. this.type = type;
  4039. }
  4040. }
  4041. exports.RenderingCancelledException = RenderingCancelledException;
  4042. function isDataScheme(url) {
  4043. const ii = url.length;
  4044. let i = 0;
  4045. while (i < ii && url[i].trim() === "") {
  4046. i++;
  4047. }
  4048. return url.substring(i, i + 5).toLowerCase() === "data:";
  4049. }
  4050. function isPdfFile(filename) {
  4051. return typeof filename === "string" && /\.pdf$/i.test(filename);
  4052. }
  4053. function getFilenameFromUrl(url, onlyStripPath = false) {
  4054. if (!onlyStripPath) {
  4055. [url] = url.split(/[#?]/, 1);
  4056. }
  4057. return url.substring(url.lastIndexOf("/") + 1);
  4058. }
  4059. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  4060. if (typeof url !== "string") {
  4061. return defaultFilename;
  4062. }
  4063. if (isDataScheme(url)) {
  4064. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  4065. return defaultFilename;
  4066. }
  4067. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  4068. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  4069. const splitURI = reURI.exec(url);
  4070. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  4071. if (suggestedFilename) {
  4072. suggestedFilename = suggestedFilename[0];
  4073. if (suggestedFilename.includes("%")) {
  4074. try {
  4075. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  4076. } catch (ex) {}
  4077. }
  4078. }
  4079. return suggestedFilename || defaultFilename;
  4080. }
  4081. class StatTimer {
  4082. started = Object.create(null);
  4083. times = [];
  4084. time(name) {
  4085. if (name in this.started) {
  4086. (0, _util.warn)(`Timer is already running for ${name}`);
  4087. }
  4088. this.started[name] = Date.now();
  4089. }
  4090. timeEnd(name) {
  4091. if (!(name in this.started)) {
  4092. (0, _util.warn)(`Timer has not been started for ${name}`);
  4093. }
  4094. this.times.push({
  4095. name,
  4096. start: this.started[name],
  4097. end: Date.now()
  4098. });
  4099. delete this.started[name];
  4100. }
  4101. toString() {
  4102. const outBuf = [];
  4103. let longest = 0;
  4104. for (const {
  4105. name
  4106. } of this.times) {
  4107. longest = Math.max(name.length, longest);
  4108. }
  4109. for (const {
  4110. name,
  4111. start,
  4112. end
  4113. } of this.times) {
  4114. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  4115. }
  4116. return outBuf.join("");
  4117. }
  4118. }
  4119. exports.StatTimer = StatTimer;
  4120. function isValidFetchUrl(url, baseUrl) {
  4121. try {
  4122. const {
  4123. protocol
  4124. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  4125. return protocol === "http:" || protocol === "https:";
  4126. } catch (ex) {
  4127. return false;
  4128. }
  4129. }
  4130. function loadScript(src, removeScriptElement = false) {
  4131. return new Promise((resolve, reject) => {
  4132. const script = document.createElement("script");
  4133. script.src = src;
  4134. script.onload = function (evt) {
  4135. if (removeScriptElement) {
  4136. script.remove();
  4137. }
  4138. resolve(evt);
  4139. };
  4140. script.onerror = function () {
  4141. reject(new Error(`Cannot load script at: ${script.src}`));
  4142. };
  4143. (document.head || document.documentElement).append(script);
  4144. });
  4145. }
  4146. function deprecated(details) {
  4147. console.log("Deprecated API usage: " + details);
  4148. }
  4149. let pdfDateStringRegex;
  4150. class PDFDateString {
  4151. static toDateObject(input) {
  4152. if (!input || typeof input !== "string") {
  4153. return null;
  4154. }
  4155. if (!pdfDateStringRegex) {
  4156. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  4157. }
  4158. const matches = pdfDateStringRegex.exec(input);
  4159. if (!matches) {
  4160. return null;
  4161. }
  4162. const year = parseInt(matches[1], 10);
  4163. let month = parseInt(matches[2], 10);
  4164. month = month >= 1 && month <= 12 ? month - 1 : 0;
  4165. let day = parseInt(matches[3], 10);
  4166. day = day >= 1 && day <= 31 ? day : 1;
  4167. let hour = parseInt(matches[4], 10);
  4168. hour = hour >= 0 && hour <= 23 ? hour : 0;
  4169. let minute = parseInt(matches[5], 10);
  4170. minute = minute >= 0 && minute <= 59 ? minute : 0;
  4171. let second = parseInt(matches[6], 10);
  4172. second = second >= 0 && second <= 59 ? second : 0;
  4173. const universalTimeRelation = matches[7] || "Z";
  4174. let offsetHour = parseInt(matches[8], 10);
  4175. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  4176. let offsetMinute = parseInt(matches[9], 10) || 0;
  4177. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  4178. if (universalTimeRelation === "-") {
  4179. hour += offsetHour;
  4180. minute += offsetMinute;
  4181. } else if (universalTimeRelation === "+") {
  4182. hour -= offsetHour;
  4183. minute -= offsetMinute;
  4184. }
  4185. return new Date(Date.UTC(year, month, day, hour, minute, second));
  4186. }
  4187. }
  4188. exports.PDFDateString = PDFDateString;
  4189. function getXfaPageViewport(xfaPage, {
  4190. scale = 1,
  4191. rotation = 0
  4192. }) {
  4193. const {
  4194. width,
  4195. height
  4196. } = xfaPage.attributes.style;
  4197. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  4198. return new PageViewport({
  4199. viewBox,
  4200. scale,
  4201. rotation
  4202. });
  4203. }
  4204. function getRGB(color) {
  4205. if (color.startsWith("#")) {
  4206. const colorRGB = parseInt(color.slice(1), 16);
  4207. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  4208. }
  4209. if (color.startsWith("rgb(")) {
  4210. return color.slice(4, -1).split(",").map(x => parseInt(x));
  4211. }
  4212. if (color.startsWith("rgba(")) {
  4213. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  4214. }
  4215. (0, _util.warn)(`Not a valid color format: "${color}"`);
  4216. return [0, 0, 0];
  4217. }
  4218. function getColorValues(colors) {
  4219. const span = document.createElement("span");
  4220. span.style.visibility = "hidden";
  4221. document.body.append(span);
  4222. for (const name of colors.keys()) {
  4223. span.style.color = name;
  4224. const computedColor = window.getComputedStyle(span).color;
  4225. colors.set(name, getRGB(computedColor));
  4226. }
  4227. span.remove();
  4228. }
  4229. function getCurrentTransform(ctx) {
  4230. const {
  4231. a,
  4232. b,
  4233. c,
  4234. d,
  4235. e,
  4236. f
  4237. } = ctx.getTransform();
  4238. return [a, b, c, d, e, f];
  4239. }
  4240. function getCurrentTransformInverse(ctx) {
  4241. const {
  4242. a,
  4243. b,
  4244. c,
  4245. d,
  4246. e,
  4247. f
  4248. } = ctx.getTransform().invertSelf();
  4249. return [a, b, c, d, e, f];
  4250. }
  4251. /***/ }),
  4252. /* 7 */
  4253. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4254. Object.defineProperty(exports, "__esModule", ({
  4255. value: true
  4256. }));
  4257. exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
  4258. var _util = __w_pdfjs_require__(1);
  4259. class BaseCanvasFactory {
  4260. constructor() {
  4261. if (this.constructor === BaseCanvasFactory) {
  4262. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  4263. }
  4264. }
  4265. create(width, height) {
  4266. if (width <= 0 || height <= 0) {
  4267. throw new Error("Invalid canvas size");
  4268. }
  4269. const canvas = this._createCanvas(width, height);
  4270. return {
  4271. canvas,
  4272. context: canvas.getContext("2d")
  4273. };
  4274. }
  4275. reset(canvasAndContext, width, height) {
  4276. if (!canvasAndContext.canvas) {
  4277. throw new Error("Canvas is not specified");
  4278. }
  4279. if (width <= 0 || height <= 0) {
  4280. throw new Error("Invalid canvas size");
  4281. }
  4282. canvasAndContext.canvas.width = width;
  4283. canvasAndContext.canvas.height = height;
  4284. }
  4285. destroy(canvasAndContext) {
  4286. if (!canvasAndContext.canvas) {
  4287. throw new Error("Canvas is not specified");
  4288. }
  4289. canvasAndContext.canvas.width = 0;
  4290. canvasAndContext.canvas.height = 0;
  4291. canvasAndContext.canvas = null;
  4292. canvasAndContext.context = null;
  4293. }
  4294. _createCanvas(width, height) {
  4295. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  4296. }
  4297. }
  4298. exports.BaseCanvasFactory = BaseCanvasFactory;
  4299. class BaseCMapReaderFactory {
  4300. constructor({
  4301. baseUrl = null,
  4302. isCompressed = false
  4303. }) {
  4304. if (this.constructor === BaseCMapReaderFactory) {
  4305. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  4306. }
  4307. this.baseUrl = baseUrl;
  4308. this.isCompressed = isCompressed;
  4309. }
  4310. async fetch({
  4311. name
  4312. }) {
  4313. if (!this.baseUrl) {
  4314. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  4315. }
  4316. if (!name) {
  4317. throw new Error("CMap name must be specified.");
  4318. }
  4319. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  4320. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  4321. return this._fetchData(url, compressionType).catch(reason => {
  4322. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  4323. });
  4324. }
  4325. _fetchData(url, compressionType) {
  4326. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4327. }
  4328. }
  4329. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  4330. class BaseStandardFontDataFactory {
  4331. constructor({
  4332. baseUrl = null
  4333. }) {
  4334. if (this.constructor === BaseStandardFontDataFactory) {
  4335. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  4336. }
  4337. this.baseUrl = baseUrl;
  4338. }
  4339. async fetch({
  4340. filename
  4341. }) {
  4342. if (!this.baseUrl) {
  4343. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  4344. }
  4345. if (!filename) {
  4346. throw new Error("Font filename must be specified.");
  4347. }
  4348. const url = `${this.baseUrl}${filename}`;
  4349. return this._fetchData(url).catch(reason => {
  4350. throw new Error(`Unable to load font data at: ${url}`);
  4351. });
  4352. }
  4353. _fetchData(url) {
  4354. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4355. }
  4356. }
  4357. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  4358. class BaseSVGFactory {
  4359. constructor() {
  4360. if (this.constructor === BaseSVGFactory) {
  4361. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  4362. }
  4363. }
  4364. create(width, height, skipDimensions = false) {
  4365. if (width <= 0 || height <= 0) {
  4366. throw new Error("Invalid SVG dimensions");
  4367. }
  4368. const svg = this._createSVG("svg:svg");
  4369. svg.setAttribute("version", "1.1");
  4370. if (!skipDimensions) {
  4371. svg.setAttribute("width", `${width}px`);
  4372. svg.setAttribute("height", `${height}px`);
  4373. }
  4374. svg.setAttribute("preserveAspectRatio", "none");
  4375. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  4376. return svg;
  4377. }
  4378. createElement(type) {
  4379. if (typeof type !== "string") {
  4380. throw new Error("Invalid SVG element type");
  4381. }
  4382. return this._createSVG(type);
  4383. }
  4384. _createSVG(type) {
  4385. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  4386. }
  4387. }
  4388. exports.BaseSVGFactory = BaseSVGFactory;
  4389. /***/ }),
  4390. /* 8 */
  4391. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4392. Object.defineProperty(exports, "__esModule", ({
  4393. value: true
  4394. }));
  4395. exports.MurmurHash3_64 = void 0;
  4396. var _util = __w_pdfjs_require__(1);
  4397. const SEED = 0xc3d2e1f0;
  4398. const MASK_HIGH = 0xffff0000;
  4399. const MASK_LOW = 0xffff;
  4400. class MurmurHash3_64 {
  4401. constructor(seed) {
  4402. this.h1 = seed ? seed & 0xffffffff : SEED;
  4403. this.h2 = seed ? seed & 0xffffffff : SEED;
  4404. }
  4405. update(input) {
  4406. let data, length;
  4407. if (typeof input === "string") {
  4408. data = new Uint8Array(input.length * 2);
  4409. length = 0;
  4410. for (let i = 0, ii = input.length; i < ii; i++) {
  4411. const code = input.charCodeAt(i);
  4412. if (code <= 0xff) {
  4413. data[length++] = code;
  4414. } else {
  4415. data[length++] = code >>> 8;
  4416. data[length++] = code & 0xff;
  4417. }
  4418. }
  4419. } else if ((0, _util.isArrayBuffer)(input)) {
  4420. data = input.slice();
  4421. length = data.byteLength;
  4422. } else {
  4423. throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
  4424. }
  4425. const blockCounts = length >> 2;
  4426. const tailLength = length - blockCounts * 4;
  4427. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  4428. let k1 = 0,
  4429. k2 = 0;
  4430. let h1 = this.h1,
  4431. h2 = this.h2;
  4432. const C1 = 0xcc9e2d51,
  4433. C2 = 0x1b873593;
  4434. const C1_LOW = C1 & MASK_LOW,
  4435. C2_LOW = C2 & MASK_LOW;
  4436. for (let i = 0; i < blockCounts; i++) {
  4437. if (i & 1) {
  4438. k1 = dataUint32[i];
  4439. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4440. k1 = k1 << 15 | k1 >>> 17;
  4441. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4442. h1 ^= k1;
  4443. h1 = h1 << 13 | h1 >>> 19;
  4444. h1 = h1 * 5 + 0xe6546b64;
  4445. } else {
  4446. k2 = dataUint32[i];
  4447. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  4448. k2 = k2 << 15 | k2 >>> 17;
  4449. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  4450. h2 ^= k2;
  4451. h2 = h2 << 13 | h2 >>> 19;
  4452. h2 = h2 * 5 + 0xe6546b64;
  4453. }
  4454. }
  4455. k1 = 0;
  4456. switch (tailLength) {
  4457. case 3:
  4458. k1 ^= data[blockCounts * 4 + 2] << 16;
  4459. case 2:
  4460. k1 ^= data[blockCounts * 4 + 1] << 8;
  4461. case 1:
  4462. k1 ^= data[blockCounts * 4];
  4463. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4464. k1 = k1 << 15 | k1 >>> 17;
  4465. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4466. if (blockCounts & 1) {
  4467. h1 ^= k1;
  4468. } else {
  4469. h2 ^= k1;
  4470. }
  4471. }
  4472. this.h1 = h1;
  4473. this.h2 = h2;
  4474. }
  4475. hexdigest() {
  4476. let h1 = this.h1,
  4477. h2 = this.h2;
  4478. h1 ^= h2 >>> 1;
  4479. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  4480. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  4481. h1 ^= h2 >>> 1;
  4482. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  4483. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  4484. h1 ^= h2 >>> 1;
  4485. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  4486. }
  4487. }
  4488. exports.MurmurHash3_64 = MurmurHash3_64;
  4489. /***/ }),
  4490. /* 9 */
  4491. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4492. Object.defineProperty(exports, "__esModule", ({
  4493. value: true
  4494. }));
  4495. exports.FontLoader = exports.FontFaceObject = void 0;
  4496. var _util = __w_pdfjs_require__(1);
  4497. class FontLoader {
  4498. constructor({
  4499. onUnsupportedFeature,
  4500. ownerDocument = globalThis.document,
  4501. styleElement = null
  4502. }) {
  4503. this._onUnsupportedFeature = onUnsupportedFeature;
  4504. this._document = ownerDocument;
  4505. this.nativeFontFaces = [];
  4506. this.styleElement = null;
  4507. this.loadingRequests = [];
  4508. this.loadTestFontId = 0;
  4509. }
  4510. addNativeFontFace(nativeFontFace) {
  4511. this.nativeFontFaces.push(nativeFontFace);
  4512. this._document.fonts.add(nativeFontFace);
  4513. }
  4514. insertRule(rule) {
  4515. if (!this.styleElement) {
  4516. this.styleElement = this._document.createElement("style");
  4517. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  4518. }
  4519. const styleSheet = this.styleElement.sheet;
  4520. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  4521. }
  4522. clear() {
  4523. for (const nativeFontFace of this.nativeFontFaces) {
  4524. this._document.fonts.delete(nativeFontFace);
  4525. }
  4526. this.nativeFontFaces.length = 0;
  4527. if (this.styleElement) {
  4528. this.styleElement.remove();
  4529. this.styleElement = null;
  4530. }
  4531. }
  4532. async bind(font) {
  4533. if (font.attached || font.missingFile) {
  4534. return;
  4535. }
  4536. font.attached = true;
  4537. if (this.isFontLoadingAPISupported) {
  4538. const nativeFontFace = font.createNativeFontFace();
  4539. if (nativeFontFace) {
  4540. this.addNativeFontFace(nativeFontFace);
  4541. try {
  4542. await nativeFontFace.loaded;
  4543. } catch (ex) {
  4544. this._onUnsupportedFeature({
  4545. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  4546. });
  4547. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  4548. font.disableFontFace = true;
  4549. throw ex;
  4550. }
  4551. }
  4552. return;
  4553. }
  4554. const rule = font.createFontFaceRule();
  4555. if (rule) {
  4556. this.insertRule(rule);
  4557. if (this.isSyncFontLoadingSupported) {
  4558. return;
  4559. }
  4560. await new Promise(resolve => {
  4561. const request = this._queueLoadingCallback(resolve);
  4562. this._prepareFontLoadEvent(font, request);
  4563. });
  4564. }
  4565. }
  4566. get isFontLoadingAPISupported() {
  4567. const hasFonts = !!this._document?.fonts;
  4568. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  4569. }
  4570. get isSyncFontLoadingSupported() {
  4571. let supported = false;
  4572. if (typeof navigator === "undefined") {
  4573. supported = true;
  4574. } else {
  4575. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  4576. if (m?.[1] >= 14) {
  4577. supported = true;
  4578. }
  4579. }
  4580. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  4581. }
  4582. _queueLoadingCallback(callback) {
  4583. function completeRequest() {
  4584. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  4585. request.done = true;
  4586. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  4587. const otherRequest = loadingRequests.shift();
  4588. setTimeout(otherRequest.callback, 0);
  4589. }
  4590. }
  4591. const {
  4592. loadingRequests
  4593. } = this;
  4594. const request = {
  4595. done: false,
  4596. complete: completeRequest,
  4597. callback
  4598. };
  4599. loadingRequests.push(request);
  4600. return request;
  4601. }
  4602. get _loadTestFont() {
  4603. 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==");
  4604. return (0, _util.shadow)(this, "_loadTestFont", testFont);
  4605. }
  4606. _prepareFontLoadEvent(font, request) {
  4607. function int32(data, offset) {
  4608. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  4609. }
  4610. function spliceString(s, offset, remove, insert) {
  4611. const chunk1 = s.substring(0, offset);
  4612. const chunk2 = s.substring(offset + remove);
  4613. return chunk1 + insert + chunk2;
  4614. }
  4615. let i, ii;
  4616. const canvas = this._document.createElement("canvas");
  4617. canvas.width = 1;
  4618. canvas.height = 1;
  4619. const ctx = canvas.getContext("2d");
  4620. let called = 0;
  4621. function isFontReady(name, callback) {
  4622. if (++called > 30) {
  4623. (0, _util.warn)("Load test font never loaded.");
  4624. callback();
  4625. return;
  4626. }
  4627. ctx.font = "30px " + name;
  4628. ctx.fillText(".", 0, 20);
  4629. const imageData = ctx.getImageData(0, 0, 1, 1);
  4630. if (imageData.data[3] > 0) {
  4631. callback();
  4632. return;
  4633. }
  4634. setTimeout(isFontReady.bind(null, name, callback));
  4635. }
  4636. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  4637. let data = this._loadTestFont;
  4638. const COMMENT_OFFSET = 976;
  4639. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  4640. const CFF_CHECKSUM_OFFSET = 16;
  4641. const XXXX_VALUE = 0x58585858;
  4642. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  4643. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  4644. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  4645. }
  4646. if (i < loadTestFontId.length) {
  4647. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  4648. }
  4649. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  4650. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  4651. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  4652. this.insertRule(rule);
  4653. const div = this._document.createElement("div");
  4654. div.style.visibility = "hidden";
  4655. div.style.width = div.style.height = "10px";
  4656. div.style.position = "absolute";
  4657. div.style.top = div.style.left = "0px";
  4658. for (const name of [font.loadedName, loadTestFontId]) {
  4659. const span = this._document.createElement("span");
  4660. span.textContent = "Hi";
  4661. span.style.fontFamily = name;
  4662. div.append(span);
  4663. }
  4664. this._document.body.append(div);
  4665. isFontReady(loadTestFontId, () => {
  4666. div.remove();
  4667. request.complete();
  4668. });
  4669. }
  4670. }
  4671. exports.FontLoader = FontLoader;
  4672. class FontFaceObject {
  4673. constructor(translatedData, {
  4674. isEvalSupported = true,
  4675. disableFontFace = false,
  4676. ignoreErrors = false,
  4677. onUnsupportedFeature,
  4678. fontRegistry = null
  4679. }) {
  4680. this.compiledGlyphs = Object.create(null);
  4681. for (const i in translatedData) {
  4682. this[i] = translatedData[i];
  4683. }
  4684. this.isEvalSupported = isEvalSupported !== false;
  4685. this.disableFontFace = disableFontFace === true;
  4686. this.ignoreErrors = ignoreErrors === true;
  4687. this._onUnsupportedFeature = onUnsupportedFeature;
  4688. this.fontRegistry = fontRegistry;
  4689. }
  4690. createNativeFontFace() {
  4691. if (!this.data || this.disableFontFace) {
  4692. return null;
  4693. }
  4694. let nativeFontFace;
  4695. if (!this.cssFontInfo) {
  4696. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  4697. } else {
  4698. const css = {
  4699. weight: this.cssFontInfo.fontWeight
  4700. };
  4701. if (this.cssFontInfo.italicAngle) {
  4702. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  4703. }
  4704. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  4705. }
  4706. this.fontRegistry?.registerFont(this);
  4707. return nativeFontFace;
  4708. }
  4709. createFontFaceRule() {
  4710. if (!this.data || this.disableFontFace) {
  4711. return null;
  4712. }
  4713. const data = (0, _util.bytesToString)(this.data);
  4714. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  4715. let rule;
  4716. if (!this.cssFontInfo) {
  4717. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  4718. } else {
  4719. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  4720. if (this.cssFontInfo.italicAngle) {
  4721. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  4722. }
  4723. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  4724. }
  4725. this.fontRegistry?.registerFont(this, url);
  4726. return rule;
  4727. }
  4728. getPathGenerator(objs, character) {
  4729. if (this.compiledGlyphs[character] !== undefined) {
  4730. return this.compiledGlyphs[character];
  4731. }
  4732. let cmds;
  4733. try {
  4734. cmds = objs.get(this.loadedName + "_path_" + character);
  4735. } catch (ex) {
  4736. if (!this.ignoreErrors) {
  4737. throw ex;
  4738. }
  4739. this._onUnsupportedFeature({
  4740. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  4741. });
  4742. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  4743. return this.compiledGlyphs[character] = function (c, size) {};
  4744. }
  4745. if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
  4746. const jsBuf = [];
  4747. for (const current of cmds) {
  4748. const args = current.args !== undefined ? current.args.join(",") : "";
  4749. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  4750. }
  4751. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  4752. }
  4753. return this.compiledGlyphs[character] = function (c, size) {
  4754. for (const current of cmds) {
  4755. if (current.cmd === "scale") {
  4756. current.args = [size, -size];
  4757. }
  4758. c[current.cmd].apply(c, current.args);
  4759. }
  4760. };
  4761. }
  4762. }
  4763. exports.FontFaceObject = FontFaceObject;
  4764. /***/ }),
  4765. /* 10 */
  4766. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4767. Object.defineProperty(exports, "__esModule", ({
  4768. value: true
  4769. }));
  4770. exports.CanvasGraphics = void 0;
  4771. var _util = __w_pdfjs_require__(1);
  4772. var _display_utils = __w_pdfjs_require__(6);
  4773. var _pattern_helper = __w_pdfjs_require__(11);
  4774. var _image_utils = __w_pdfjs_require__(13);
  4775. var _is_node = __w_pdfjs_require__(12);
  4776. const MIN_FONT_SIZE = 16;
  4777. const MAX_FONT_SIZE = 100;
  4778. const MAX_GROUP_SIZE = 4096;
  4779. const EXECUTION_TIME = 15;
  4780. const EXECUTION_STEPS = 10;
  4781. const MAX_SIZE_TO_COMPILE = _is_node.isNodeJS && typeof Path2D === "undefined" ? -1 : 1000;
  4782. const FULL_CHUNK_HEIGHT = 16;
  4783. function mirrorContextOperations(ctx, destCtx) {
  4784. if (ctx._removeMirroring) {
  4785. throw new Error("Context is already forwarding operations.");
  4786. }
  4787. ctx.__originalSave = ctx.save;
  4788. ctx.__originalRestore = ctx.restore;
  4789. ctx.__originalRotate = ctx.rotate;
  4790. ctx.__originalScale = ctx.scale;
  4791. ctx.__originalTranslate = ctx.translate;
  4792. ctx.__originalTransform = ctx.transform;
  4793. ctx.__originalSetTransform = ctx.setTransform;
  4794. ctx.__originalResetTransform = ctx.resetTransform;
  4795. ctx.__originalClip = ctx.clip;
  4796. ctx.__originalMoveTo = ctx.moveTo;
  4797. ctx.__originalLineTo = ctx.lineTo;
  4798. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  4799. ctx.__originalRect = ctx.rect;
  4800. ctx.__originalClosePath = ctx.closePath;
  4801. ctx.__originalBeginPath = ctx.beginPath;
  4802. ctx._removeMirroring = () => {
  4803. ctx.save = ctx.__originalSave;
  4804. ctx.restore = ctx.__originalRestore;
  4805. ctx.rotate = ctx.__originalRotate;
  4806. ctx.scale = ctx.__originalScale;
  4807. ctx.translate = ctx.__originalTranslate;
  4808. ctx.transform = ctx.__originalTransform;
  4809. ctx.setTransform = ctx.__originalSetTransform;
  4810. ctx.resetTransform = ctx.__originalResetTransform;
  4811. ctx.clip = ctx.__originalClip;
  4812. ctx.moveTo = ctx.__originalMoveTo;
  4813. ctx.lineTo = ctx.__originalLineTo;
  4814. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  4815. ctx.rect = ctx.__originalRect;
  4816. ctx.closePath = ctx.__originalClosePath;
  4817. ctx.beginPath = ctx.__originalBeginPath;
  4818. delete ctx._removeMirroring;
  4819. };
  4820. ctx.save = function ctxSave() {
  4821. destCtx.save();
  4822. this.__originalSave();
  4823. };
  4824. ctx.restore = function ctxRestore() {
  4825. destCtx.restore();
  4826. this.__originalRestore();
  4827. };
  4828. ctx.translate = function ctxTranslate(x, y) {
  4829. destCtx.translate(x, y);
  4830. this.__originalTranslate(x, y);
  4831. };
  4832. ctx.scale = function ctxScale(x, y) {
  4833. destCtx.scale(x, y);
  4834. this.__originalScale(x, y);
  4835. };
  4836. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  4837. destCtx.transform(a, b, c, d, e, f);
  4838. this.__originalTransform(a, b, c, d, e, f);
  4839. };
  4840. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  4841. destCtx.setTransform(a, b, c, d, e, f);
  4842. this.__originalSetTransform(a, b, c, d, e, f);
  4843. };
  4844. ctx.resetTransform = function ctxResetTransform() {
  4845. destCtx.resetTransform();
  4846. this.__originalResetTransform();
  4847. };
  4848. ctx.rotate = function ctxRotate(angle) {
  4849. destCtx.rotate(angle);
  4850. this.__originalRotate(angle);
  4851. };
  4852. ctx.clip = function ctxRotate(rule) {
  4853. destCtx.clip(rule);
  4854. this.__originalClip(rule);
  4855. };
  4856. ctx.moveTo = function (x, y) {
  4857. destCtx.moveTo(x, y);
  4858. this.__originalMoveTo(x, y);
  4859. };
  4860. ctx.lineTo = function (x, y) {
  4861. destCtx.lineTo(x, y);
  4862. this.__originalLineTo(x, y);
  4863. };
  4864. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  4865. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  4866. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  4867. };
  4868. ctx.rect = function (x, y, width, height) {
  4869. destCtx.rect(x, y, width, height);
  4870. this.__originalRect(x, y, width, height);
  4871. };
  4872. ctx.closePath = function () {
  4873. destCtx.closePath();
  4874. this.__originalClosePath();
  4875. };
  4876. ctx.beginPath = function () {
  4877. destCtx.beginPath();
  4878. this.__originalBeginPath();
  4879. };
  4880. }
  4881. class CachedCanvases {
  4882. constructor(canvasFactory) {
  4883. this.canvasFactory = canvasFactory;
  4884. this.cache = Object.create(null);
  4885. }
  4886. getCanvas(id, width, height) {
  4887. let canvasEntry;
  4888. if (this.cache[id] !== undefined) {
  4889. canvasEntry = this.cache[id];
  4890. this.canvasFactory.reset(canvasEntry, width, height);
  4891. } else {
  4892. canvasEntry = this.canvasFactory.create(width, height);
  4893. this.cache[id] = canvasEntry;
  4894. }
  4895. return canvasEntry;
  4896. }
  4897. delete(id) {
  4898. delete this.cache[id];
  4899. }
  4900. clear() {
  4901. for (const id in this.cache) {
  4902. const canvasEntry = this.cache[id];
  4903. this.canvasFactory.destroy(canvasEntry);
  4904. delete this.cache[id];
  4905. }
  4906. }
  4907. }
  4908. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  4909. const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
  4910. if (b === 0 && c === 0) {
  4911. const tlX = destX * a + tx;
  4912. const rTlX = Math.round(tlX);
  4913. const tlY = destY * d + ty;
  4914. const rTlY = Math.round(tlY);
  4915. const brX = (destX + destW) * a + tx;
  4916. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  4917. const brY = (destY + destH) * d + ty;
  4918. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  4919. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  4920. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  4921. ctx.setTransform(a, b, c, d, tx, ty);
  4922. return [rWidth, rHeight];
  4923. }
  4924. if (a === 0 && d === 0) {
  4925. const tlX = destY * c + tx;
  4926. const rTlX = Math.round(tlX);
  4927. const tlY = destX * b + ty;
  4928. const rTlY = Math.round(tlY);
  4929. const brX = (destY + destH) * c + tx;
  4930. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  4931. const brY = (destX + destW) * b + ty;
  4932. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  4933. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  4934. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  4935. ctx.setTransform(a, b, c, d, tx, ty);
  4936. return [rHeight, rWidth];
  4937. }
  4938. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  4939. const scaleX = Math.hypot(a, b);
  4940. const scaleY = Math.hypot(c, d);
  4941. return [scaleX * destW, scaleY * destH];
  4942. }
  4943. function compileType3Glyph(imgData) {
  4944. const {
  4945. width,
  4946. height
  4947. } = imgData;
  4948. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  4949. return null;
  4950. }
  4951. const POINT_TO_PROCESS_LIMIT = 1000;
  4952. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  4953. const width1 = width + 1;
  4954. let points = new Uint8Array(width1 * (height + 1));
  4955. let i, j, j0;
  4956. const lineSize = width + 7 & ~7;
  4957. let data = new Uint8Array(lineSize * height),
  4958. pos = 0;
  4959. for (const elem of imgData.data) {
  4960. let mask = 128;
  4961. while (mask > 0) {
  4962. data[pos++] = elem & mask ? 0 : 255;
  4963. mask >>= 1;
  4964. }
  4965. }
  4966. let count = 0;
  4967. pos = 0;
  4968. if (data[pos] !== 0) {
  4969. points[0] = 1;
  4970. ++count;
  4971. }
  4972. for (j = 1; j < width; j++) {
  4973. if (data[pos] !== data[pos + 1]) {
  4974. points[j] = data[pos] ? 2 : 1;
  4975. ++count;
  4976. }
  4977. pos++;
  4978. }
  4979. if (data[pos] !== 0) {
  4980. points[j] = 2;
  4981. ++count;
  4982. }
  4983. for (i = 1; i < height; i++) {
  4984. pos = i * lineSize;
  4985. j0 = i * width1;
  4986. if (data[pos - lineSize] !== data[pos]) {
  4987. points[j0] = data[pos] ? 1 : 8;
  4988. ++count;
  4989. }
  4990. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  4991. for (j = 1; j < width; j++) {
  4992. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  4993. if (POINT_TYPES[sum]) {
  4994. points[j0 + j] = POINT_TYPES[sum];
  4995. ++count;
  4996. }
  4997. pos++;
  4998. }
  4999. if (data[pos - lineSize] !== data[pos]) {
  5000. points[j0 + j] = data[pos] ? 2 : 4;
  5001. ++count;
  5002. }
  5003. if (count > POINT_TO_PROCESS_LIMIT) {
  5004. return null;
  5005. }
  5006. }
  5007. pos = lineSize * (height - 1);
  5008. j0 = i * width1;
  5009. if (data[pos] !== 0) {
  5010. points[j0] = 8;
  5011. ++count;
  5012. }
  5013. for (j = 1; j < width; j++) {
  5014. if (data[pos] !== data[pos + 1]) {
  5015. points[j0 + j] = data[pos] ? 4 : 8;
  5016. ++count;
  5017. }
  5018. pos++;
  5019. }
  5020. if (data[pos] !== 0) {
  5021. points[j0 + j] = 4;
  5022. ++count;
  5023. }
  5024. if (count > POINT_TO_PROCESS_LIMIT) {
  5025. return null;
  5026. }
  5027. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5028. const path = new Path2D();
  5029. for (i = 0; count && i <= height; i++) {
  5030. let p = i * width1;
  5031. const end = p + width;
  5032. while (p < end && !points[p]) {
  5033. p++;
  5034. }
  5035. if (p === end) {
  5036. continue;
  5037. }
  5038. path.moveTo(p % width1, i);
  5039. const p0 = p;
  5040. let type = points[p];
  5041. do {
  5042. const step = steps[type];
  5043. do {
  5044. p += step;
  5045. } while (!points[p]);
  5046. const pp = points[p];
  5047. if (pp !== 5 && pp !== 10) {
  5048. type = pp;
  5049. points[p] = 0;
  5050. } else {
  5051. type = pp & 0x33 * type >> 4;
  5052. points[p] &= type >> 2 | type << 2;
  5053. }
  5054. path.lineTo(p % width1, p / width1 | 0);
  5055. if (!points[p]) {
  5056. --count;
  5057. }
  5058. } while (p0 !== p);
  5059. --i;
  5060. }
  5061. data = null;
  5062. points = null;
  5063. const drawOutline = function (c) {
  5064. c.save();
  5065. c.scale(1 / width, -1 / height);
  5066. c.translate(0, -height);
  5067. c.fill(path);
  5068. c.beginPath();
  5069. c.restore();
  5070. };
  5071. return drawOutline;
  5072. }
  5073. class CanvasExtraState {
  5074. constructor(width, height) {
  5075. this.alphaIsShape = false;
  5076. this.fontSize = 0;
  5077. this.fontSizeScale = 1;
  5078. this.textMatrix = _util.IDENTITY_MATRIX;
  5079. this.textMatrixScale = 1;
  5080. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  5081. this.leading = 0;
  5082. this.x = 0;
  5083. this.y = 0;
  5084. this.lineX = 0;
  5085. this.lineY = 0;
  5086. this.charSpacing = 0;
  5087. this.wordSpacing = 0;
  5088. this.textHScale = 1;
  5089. this.textRenderingMode = _util.TextRenderingMode.FILL;
  5090. this.textRise = 0;
  5091. this.fillColor = "#000000";
  5092. this.strokeColor = "#000000";
  5093. this.patternFill = false;
  5094. this.fillAlpha = 1;
  5095. this.strokeAlpha = 1;
  5096. this.lineWidth = 1;
  5097. this.activeSMask = null;
  5098. this.transferMaps = null;
  5099. this.startNewPathAndClipBox([0, 0, width, height]);
  5100. }
  5101. clone() {
  5102. const clone = Object.create(this);
  5103. clone.clipBox = this.clipBox.slice();
  5104. return clone;
  5105. }
  5106. setCurrentPoint(x, y) {
  5107. this.x = x;
  5108. this.y = y;
  5109. }
  5110. updatePathMinMax(transform, x, y) {
  5111. [x, y] = _util.Util.applyTransform([x, y], transform);
  5112. this.minX = Math.min(this.minX, x);
  5113. this.minY = Math.min(this.minY, y);
  5114. this.maxX = Math.max(this.maxX, x);
  5115. this.maxY = Math.max(this.maxY, y);
  5116. }
  5117. updateRectMinMax(transform, rect) {
  5118. const p1 = _util.Util.applyTransform(rect, transform);
  5119. const p2 = _util.Util.applyTransform(rect.slice(2), transform);
  5120. this.minX = Math.min(this.minX, p1[0], p2[0]);
  5121. this.minY = Math.min(this.minY, p1[1], p2[1]);
  5122. this.maxX = Math.max(this.maxX, p1[0], p2[0]);
  5123. this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  5124. }
  5125. updateScalingPathMinMax(transform, minMax) {
  5126. _util.Util.scaleMinMax(transform, minMax);
  5127. this.minX = Math.min(this.minX, minMax[0]);
  5128. this.maxX = Math.max(this.maxX, minMax[1]);
  5129. this.minY = Math.min(this.minY, minMax[2]);
  5130. this.maxY = Math.max(this.maxY, minMax[3]);
  5131. }
  5132. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  5133. const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
  5134. if (minMax) {
  5135. minMax[0] = Math.min(minMax[0], box[0], box[2]);
  5136. minMax[1] = Math.max(minMax[1], box[0], box[2]);
  5137. minMax[2] = Math.min(minMax[2], box[1], box[3]);
  5138. minMax[3] = Math.max(minMax[3], box[1], box[3]);
  5139. return;
  5140. }
  5141. this.updateRectMinMax(transform, box);
  5142. }
  5143. getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5144. const box = [this.minX, this.minY, this.maxX, this.maxY];
  5145. if (pathType === _pattern_helper.PathType.STROKE) {
  5146. if (!transform) {
  5147. (0, _util.unreachable)("Stroke bounding box must include transform.");
  5148. }
  5149. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5150. const xStrokePad = scale[0] * this.lineWidth / 2;
  5151. const yStrokePad = scale[1] * this.lineWidth / 2;
  5152. box[0] -= xStrokePad;
  5153. box[1] -= yStrokePad;
  5154. box[2] += xStrokePad;
  5155. box[3] += yStrokePad;
  5156. }
  5157. return box;
  5158. }
  5159. updateClipFromPath() {
  5160. const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
  5161. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  5162. }
  5163. isEmptyClip() {
  5164. return this.minX === Infinity;
  5165. }
  5166. startNewPathAndClipBox(box) {
  5167. this.clipBox = box;
  5168. this.minX = Infinity;
  5169. this.minY = Infinity;
  5170. this.maxX = 0;
  5171. this.maxY = 0;
  5172. }
  5173. getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5174. return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  5175. }
  5176. }
  5177. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  5178. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  5179. ctx.putImageData(imgData, 0, 0);
  5180. return;
  5181. }
  5182. const height = imgData.height,
  5183. width = imgData.width;
  5184. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5185. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5186. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5187. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5188. let srcPos = 0,
  5189. destPos;
  5190. const src = imgData.data;
  5191. const dest = chunkImgData.data;
  5192. let i, j, thisChunkHeight, elemsInThisChunk;
  5193. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  5194. if (transferMaps) {
  5195. switch (transferMaps.length) {
  5196. case 1:
  5197. transferMapRed = transferMaps[0];
  5198. transferMapGreen = transferMaps[0];
  5199. transferMapBlue = transferMaps[0];
  5200. transferMapGray = transferMaps[0];
  5201. break;
  5202. case 4:
  5203. transferMapRed = transferMaps[0];
  5204. transferMapGreen = transferMaps[1];
  5205. transferMapBlue = transferMaps[2];
  5206. transferMapGray = transferMaps[3];
  5207. break;
  5208. }
  5209. }
  5210. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  5211. const srcLength = src.byteLength;
  5212. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  5213. const dest32DataLength = dest32.length;
  5214. const fullSrcDiff = width + 7 >> 3;
  5215. let white = 0xffffffff;
  5216. let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  5217. if (transferMapGray) {
  5218. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  5219. [white, black] = [black, white];
  5220. }
  5221. }
  5222. for (i = 0; i < totalChunks; i++) {
  5223. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5224. destPos = 0;
  5225. for (j = 0; j < thisChunkHeight; j++) {
  5226. const srcDiff = srcLength - srcPos;
  5227. let k = 0;
  5228. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  5229. const kEndUnrolled = kEnd & ~7;
  5230. let mask = 0;
  5231. let srcByte = 0;
  5232. for (; k < kEndUnrolled; k += 8) {
  5233. srcByte = src[srcPos++];
  5234. dest32[destPos++] = srcByte & 128 ? white : black;
  5235. dest32[destPos++] = srcByte & 64 ? white : black;
  5236. dest32[destPos++] = srcByte & 32 ? white : black;
  5237. dest32[destPos++] = srcByte & 16 ? white : black;
  5238. dest32[destPos++] = srcByte & 8 ? white : black;
  5239. dest32[destPos++] = srcByte & 4 ? white : black;
  5240. dest32[destPos++] = srcByte & 2 ? white : black;
  5241. dest32[destPos++] = srcByte & 1 ? white : black;
  5242. }
  5243. for (; k < kEnd; k++) {
  5244. if (mask === 0) {
  5245. srcByte = src[srcPos++];
  5246. mask = 128;
  5247. }
  5248. dest32[destPos++] = srcByte & mask ? white : black;
  5249. mask >>= 1;
  5250. }
  5251. }
  5252. while (destPos < dest32DataLength) {
  5253. dest32[destPos++] = 0;
  5254. }
  5255. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5256. }
  5257. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  5258. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5259. j = 0;
  5260. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  5261. for (i = 0; i < fullChunks; i++) {
  5262. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5263. srcPos += elemsInThisChunk;
  5264. if (hasTransferMaps) {
  5265. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5266. if (transferMapRed) {
  5267. dest[k + 0] = transferMapRed[dest[k + 0]];
  5268. }
  5269. if (transferMapGreen) {
  5270. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5271. }
  5272. if (transferMapBlue) {
  5273. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5274. }
  5275. }
  5276. }
  5277. ctx.putImageData(chunkImgData, 0, j);
  5278. j += FULL_CHUNK_HEIGHT;
  5279. }
  5280. if (i < totalChunks) {
  5281. elemsInThisChunk = width * partialChunkHeight * 4;
  5282. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5283. if (hasTransferMaps) {
  5284. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5285. if (transferMapRed) {
  5286. dest[k + 0] = transferMapRed[dest[k + 0]];
  5287. }
  5288. if (transferMapGreen) {
  5289. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5290. }
  5291. if (transferMapBlue) {
  5292. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5293. }
  5294. }
  5295. }
  5296. ctx.putImageData(chunkImgData, 0, j);
  5297. }
  5298. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  5299. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5300. thisChunkHeight = FULL_CHUNK_HEIGHT;
  5301. elemsInThisChunk = width * thisChunkHeight;
  5302. for (i = 0; i < totalChunks; i++) {
  5303. if (i >= fullChunks) {
  5304. thisChunkHeight = partialChunkHeight;
  5305. elemsInThisChunk = width * thisChunkHeight;
  5306. }
  5307. destPos = 0;
  5308. for (j = elemsInThisChunk; j--;) {
  5309. dest[destPos++] = src[srcPos++];
  5310. dest[destPos++] = src[srcPos++];
  5311. dest[destPos++] = src[srcPos++];
  5312. dest[destPos++] = 255;
  5313. }
  5314. if (hasTransferMaps) {
  5315. for (let k = 0; k < destPos; k += 4) {
  5316. if (transferMapRed) {
  5317. dest[k + 0] = transferMapRed[dest[k + 0]];
  5318. }
  5319. if (transferMapGreen) {
  5320. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5321. }
  5322. if (transferMapBlue) {
  5323. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5324. }
  5325. }
  5326. }
  5327. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5328. }
  5329. } else {
  5330. throw new Error(`bad image kind: ${imgData.kind}`);
  5331. }
  5332. }
  5333. function putBinaryImageMask(ctx, imgData) {
  5334. if (imgData.bitmap) {
  5335. ctx.drawImage(imgData.bitmap, 0, 0);
  5336. return;
  5337. }
  5338. const height = imgData.height,
  5339. width = imgData.width;
  5340. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5341. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5342. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5343. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5344. let srcPos = 0;
  5345. const src = imgData.data;
  5346. const dest = chunkImgData.data;
  5347. for (let i = 0; i < totalChunks; i++) {
  5348. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5349. ({
  5350. srcPos
  5351. } = (0, _image_utils.applyMaskImageData)({
  5352. src,
  5353. srcPos,
  5354. dest,
  5355. width,
  5356. height: thisChunkHeight
  5357. }));
  5358. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5359. }
  5360. }
  5361. function copyCtxState(sourceCtx, destCtx) {
  5362. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  5363. for (const property of properties) {
  5364. if (sourceCtx[property] !== undefined) {
  5365. destCtx[property] = sourceCtx[property];
  5366. }
  5367. }
  5368. if (sourceCtx.setLineDash !== undefined) {
  5369. destCtx.setLineDash(sourceCtx.getLineDash());
  5370. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5371. }
  5372. }
  5373. function resetCtxToDefault(ctx, foregroundColor) {
  5374. ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
  5375. ctx.fillRule = "nonzero";
  5376. ctx.globalAlpha = 1;
  5377. ctx.lineWidth = 1;
  5378. ctx.lineCap = "butt";
  5379. ctx.lineJoin = "miter";
  5380. ctx.miterLimit = 10;
  5381. ctx.globalCompositeOperation = "source-over";
  5382. ctx.font = "10px sans-serif";
  5383. if (ctx.setLineDash !== undefined) {
  5384. ctx.setLineDash([]);
  5385. ctx.lineDashOffset = 0;
  5386. }
  5387. }
  5388. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  5389. const length = bytes.length;
  5390. for (let i = 3; i < length; i += 4) {
  5391. const alpha = bytes[i];
  5392. if (alpha === 0) {
  5393. bytes[i - 3] = r0;
  5394. bytes[i - 2] = g0;
  5395. bytes[i - 1] = b0;
  5396. } else if (alpha < 255) {
  5397. const alpha_ = 255 - alpha;
  5398. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  5399. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  5400. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  5401. }
  5402. }
  5403. }
  5404. function composeSMaskAlpha(maskData, layerData, transferMap) {
  5405. const length = maskData.length;
  5406. const scale = 1 / 255;
  5407. for (let i = 3; i < length; i += 4) {
  5408. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  5409. layerData[i] = layerData[i] * alpha * scale | 0;
  5410. }
  5411. }
  5412. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  5413. const length = maskData.length;
  5414. for (let i = 3; i < length; i += 4) {
  5415. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  5416. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  5417. }
  5418. }
  5419. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  5420. const hasBackdrop = !!backdrop;
  5421. const r0 = hasBackdrop ? backdrop[0] : 0;
  5422. const g0 = hasBackdrop ? backdrop[1] : 0;
  5423. const b0 = hasBackdrop ? backdrop[2] : 0;
  5424. let composeFn;
  5425. if (subtype === "Luminosity") {
  5426. composeFn = composeSMaskLuminosity;
  5427. } else {
  5428. composeFn = composeSMaskAlpha;
  5429. }
  5430. const PIXELS_TO_PROCESS = 1048576;
  5431. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5432. for (let row = 0; row < height; row += chunkSize) {
  5433. const chunkHeight = Math.min(chunkSize, height - row);
  5434. const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
  5435. const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
  5436. if (hasBackdrop) {
  5437. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  5438. }
  5439. composeFn(maskData.data, layerData.data, transferMap);
  5440. layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  5441. }
  5442. }
  5443. function composeSMask(ctx, smask, layerCtx, layerBox) {
  5444. const layerOffsetX = layerBox[0];
  5445. const layerOffsetY = layerBox[1];
  5446. const layerWidth = layerBox[2] - layerOffsetX;
  5447. const layerHeight = layerBox[3] - layerOffsetY;
  5448. if (layerWidth === 0 || layerHeight === 0) {
  5449. return;
  5450. }
  5451. genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  5452. ctx.save();
  5453. ctx.globalAlpha = 1;
  5454. ctx.globalCompositeOperation = "source-over";
  5455. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5456. ctx.drawImage(layerCtx.canvas, 0, 0);
  5457. ctx.restore();
  5458. }
  5459. function getImageSmoothingEnabled(transform, interpolate) {
  5460. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5461. scale[0] = Math.fround(scale[0]);
  5462. scale[1] = Math.fround(scale[1]);
  5463. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  5464. if (interpolate !== undefined) {
  5465. return interpolate;
  5466. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  5467. return true;
  5468. }
  5469. return false;
  5470. }
  5471. const LINE_CAP_STYLES = ["butt", "round", "square"];
  5472. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  5473. const NORMAL_CLIP = {};
  5474. const EO_CLIP = {};
  5475. class CanvasGraphics {
  5476. constructor(canvasCtx, commonObjs, objs, canvasFactory, {
  5477. optionalContentConfig,
  5478. markedContentStack = null
  5479. }, annotationCanvasMap, pageColors) {
  5480. this.ctx = canvasCtx;
  5481. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  5482. this.stateStack = [];
  5483. this.pendingClip = null;
  5484. this.pendingEOFill = false;
  5485. this.res = null;
  5486. this.xobjs = null;
  5487. this.commonObjs = commonObjs;
  5488. this.objs = objs;
  5489. this.canvasFactory = canvasFactory;
  5490. this.groupStack = [];
  5491. this.processingType3 = null;
  5492. this.baseTransform = null;
  5493. this.baseTransformStack = [];
  5494. this.groupLevel = 0;
  5495. this.smaskStack = [];
  5496. this.smaskCounter = 0;
  5497. this.tempSMask = null;
  5498. this.suspendedCtx = null;
  5499. this.contentVisible = true;
  5500. this.markedContentStack = markedContentStack || [];
  5501. this.optionalContentConfig = optionalContentConfig;
  5502. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  5503. this.cachedPatterns = new Map();
  5504. this.annotationCanvasMap = annotationCanvasMap;
  5505. this.viewportScale = 1;
  5506. this.outputScaleX = 1;
  5507. this.outputScaleY = 1;
  5508. this.backgroundColor = pageColors?.background || null;
  5509. this.foregroundColor = pageColors?.foreground || null;
  5510. this._cachedScaleForStroking = null;
  5511. this._cachedGetSinglePixelWidth = null;
  5512. this._cachedBitmapsMap = new Map();
  5513. }
  5514. getObject(data, fallback = null) {
  5515. if (typeof data === "string") {
  5516. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  5517. }
  5518. return fallback;
  5519. }
  5520. beginDrawing({
  5521. transform,
  5522. viewport,
  5523. transparency = false,
  5524. background = null
  5525. }) {
  5526. const width = this.ctx.canvas.width;
  5527. const height = this.ctx.canvas.height;
  5528. const defaultBackgroundColor = background || "#ffffff";
  5529. this.ctx.save();
  5530. if (this.foregroundColor && this.backgroundColor) {
  5531. this.ctx.fillStyle = this.foregroundColor;
  5532. const fg = this.foregroundColor = this.ctx.fillStyle;
  5533. this.ctx.fillStyle = this.backgroundColor;
  5534. const bg = this.backgroundColor = this.ctx.fillStyle;
  5535. let isValidDefaultBg = true;
  5536. let defaultBg = defaultBackgroundColor;
  5537. this.ctx.fillStyle = defaultBackgroundColor;
  5538. defaultBg = this.ctx.fillStyle;
  5539. isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
  5540. if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
  5541. this.foregroundColor = this.backgroundColor = null;
  5542. } else {
  5543. const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
  5544. const newComp = x => {
  5545. x /= 255;
  5546. return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  5547. };
  5548. const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
  5549. this.selectColor = (r, g, b) => {
  5550. const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
  5551. return Math.round(lumC) === lumB ? bg : fg;
  5552. };
  5553. }
  5554. }
  5555. this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
  5556. this.ctx.fillRect(0, 0, width, height);
  5557. this.ctx.restore();
  5558. if (transparency) {
  5559. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  5560. this.compositeCtx = this.ctx;
  5561. this.transparentCanvas = transparentCanvas.canvas;
  5562. this.ctx = transparentCanvas.context;
  5563. this.ctx.save();
  5564. this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
  5565. }
  5566. this.ctx.save();
  5567. resetCtxToDefault(this.ctx, this.foregroundColor);
  5568. if (transform) {
  5569. this.ctx.transform(...transform);
  5570. this.outputScaleX = transform[0];
  5571. this.outputScaleY = transform[0];
  5572. }
  5573. this.ctx.transform(...viewport.transform);
  5574. this.viewportScale = viewport.scale;
  5575. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  5576. }
  5577. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  5578. const argsArray = operatorList.argsArray;
  5579. const fnArray = operatorList.fnArray;
  5580. let i = executionStartIdx || 0;
  5581. const argsArrayLen = argsArray.length;
  5582. if (argsArrayLen === i) {
  5583. return i;
  5584. }
  5585. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  5586. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  5587. let steps = 0;
  5588. const commonObjs = this.commonObjs;
  5589. const objs = this.objs;
  5590. let fnId;
  5591. while (true) {
  5592. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  5593. stepper.breakIt(i, continueCallback);
  5594. return i;
  5595. }
  5596. fnId = fnArray[i];
  5597. if (fnId !== _util.OPS.dependency) {
  5598. this[fnId].apply(this, argsArray[i]);
  5599. } else {
  5600. for (const depObjId of argsArray[i]) {
  5601. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  5602. if (!objsPool.has(depObjId)) {
  5603. objsPool.get(depObjId, continueCallback);
  5604. return i;
  5605. }
  5606. }
  5607. }
  5608. i++;
  5609. if (i === argsArrayLen) {
  5610. return i;
  5611. }
  5612. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  5613. if (Date.now() > endTime) {
  5614. continueCallback();
  5615. return i;
  5616. }
  5617. steps = 0;
  5618. }
  5619. }
  5620. }
  5621. #restoreInitialState() {
  5622. while (this.stateStack.length || this.inSMaskMode) {
  5623. this.restore();
  5624. }
  5625. this.ctx.restore();
  5626. if (this.transparentCanvas) {
  5627. this.ctx = this.compositeCtx;
  5628. this.ctx.save();
  5629. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  5630. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  5631. this.ctx.restore();
  5632. this.transparentCanvas = null;
  5633. }
  5634. }
  5635. endDrawing() {
  5636. this.#restoreInitialState();
  5637. this.cachedCanvases.clear();
  5638. this.cachedPatterns.clear();
  5639. for (const cache of this._cachedBitmapsMap.values()) {
  5640. for (const canvas of cache.values()) {
  5641. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  5642. canvas.width = canvas.height = 0;
  5643. }
  5644. }
  5645. cache.clear();
  5646. }
  5647. this._cachedBitmapsMap.clear();
  5648. }
  5649. _scaleImage(img, inverseTransform) {
  5650. const width = img.width;
  5651. const height = img.height;
  5652. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  5653. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  5654. let paintWidth = width,
  5655. paintHeight = height;
  5656. let tmpCanvasId = "prescale1";
  5657. let tmpCanvas, tmpCtx;
  5658. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  5659. let newWidth = paintWidth,
  5660. newHeight = paintHeight;
  5661. if (widthScale > 2 && paintWidth > 1) {
  5662. newWidth = Math.ceil(paintWidth / 2);
  5663. widthScale /= paintWidth / newWidth;
  5664. }
  5665. if (heightScale > 2 && paintHeight > 1) {
  5666. newHeight = Math.ceil(paintHeight / 2);
  5667. heightScale /= paintHeight / newHeight;
  5668. }
  5669. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  5670. tmpCtx = tmpCanvas.context;
  5671. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5672. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  5673. img = tmpCanvas.canvas;
  5674. paintWidth = newWidth;
  5675. paintHeight = newHeight;
  5676. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  5677. }
  5678. return {
  5679. img,
  5680. paintWidth,
  5681. paintHeight
  5682. };
  5683. }
  5684. _createMaskCanvas(img) {
  5685. const ctx = this.ctx;
  5686. const {
  5687. width,
  5688. height
  5689. } = img;
  5690. const fillColor = this.current.fillColor;
  5691. const isPatternFill = this.current.patternFill;
  5692. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  5693. let cache, cacheKey, scaled, maskCanvas;
  5694. if ((img.bitmap || img.data) && img.count > 1) {
  5695. const mainKey = img.bitmap || img.data.buffer;
  5696. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  5697. cache = this._cachedBitmapsMap.get(mainKey);
  5698. if (!cache) {
  5699. cache = new Map();
  5700. this._cachedBitmapsMap.set(mainKey, cache);
  5701. }
  5702. const cachedImage = cache.get(cacheKey);
  5703. if (cachedImage && !isPatternFill) {
  5704. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  5705. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  5706. return {
  5707. canvas: cachedImage,
  5708. offsetX,
  5709. offsetY
  5710. };
  5711. }
  5712. scaled = cachedImage;
  5713. }
  5714. if (!scaled) {
  5715. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5716. putBinaryImageMask(maskCanvas.context, img);
  5717. }
  5718. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  5719. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  5720. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  5721. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  5722. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  5723. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  5724. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  5725. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  5726. const fillCtx = fillCanvas.context;
  5727. const offsetX = Math.min(cord1[0], cord2[0]);
  5728. const offsetY = Math.min(cord1[1], cord2[1]);
  5729. fillCtx.translate(-offsetX, -offsetY);
  5730. fillCtx.transform(...maskToCanvas);
  5731. if (!scaled) {
  5732. scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
  5733. scaled = scaled.img;
  5734. if (cache && isPatternFill) {
  5735. cache.set(cacheKey, scaled);
  5736. }
  5737. }
  5738. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
  5739. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  5740. fillCtx.globalCompositeOperation = "source-in";
  5741. const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  5742. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  5743. fillCtx.fillRect(0, 0, width, height);
  5744. if (cache && !isPatternFill) {
  5745. this.cachedCanvases.delete("fillCanvas");
  5746. cache.set(cacheKey, fillCanvas.canvas);
  5747. }
  5748. return {
  5749. canvas: fillCanvas.canvas,
  5750. offsetX: Math.round(offsetX),
  5751. offsetY: Math.round(offsetY)
  5752. };
  5753. }
  5754. setLineWidth(width) {
  5755. if (width !== this.current.lineWidth) {
  5756. this._cachedScaleForStroking = null;
  5757. }
  5758. this.current.lineWidth = width;
  5759. this.ctx.lineWidth = width;
  5760. }
  5761. setLineCap(style) {
  5762. this.ctx.lineCap = LINE_CAP_STYLES[style];
  5763. }
  5764. setLineJoin(style) {
  5765. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  5766. }
  5767. setMiterLimit(limit) {
  5768. this.ctx.miterLimit = limit;
  5769. }
  5770. setDash(dashArray, dashPhase) {
  5771. const ctx = this.ctx;
  5772. if (ctx.setLineDash !== undefined) {
  5773. ctx.setLineDash(dashArray);
  5774. ctx.lineDashOffset = dashPhase;
  5775. }
  5776. }
  5777. setRenderingIntent(intent) {}
  5778. setFlatness(flatness) {}
  5779. setGState(states) {
  5780. for (const [key, value] of states) {
  5781. switch (key) {
  5782. case "LW":
  5783. this.setLineWidth(value);
  5784. break;
  5785. case "LC":
  5786. this.setLineCap(value);
  5787. break;
  5788. case "LJ":
  5789. this.setLineJoin(value);
  5790. break;
  5791. case "ML":
  5792. this.setMiterLimit(value);
  5793. break;
  5794. case "D":
  5795. this.setDash(value[0], value[1]);
  5796. break;
  5797. case "RI":
  5798. this.setRenderingIntent(value);
  5799. break;
  5800. case "FL":
  5801. this.setFlatness(value);
  5802. break;
  5803. case "Font":
  5804. this.setFont(value[0], value[1]);
  5805. break;
  5806. case "CA":
  5807. this.current.strokeAlpha = value;
  5808. break;
  5809. case "ca":
  5810. this.current.fillAlpha = value;
  5811. this.ctx.globalAlpha = value;
  5812. break;
  5813. case "BM":
  5814. this.ctx.globalCompositeOperation = value;
  5815. break;
  5816. case "SMask":
  5817. this.current.activeSMask = value ? this.tempSMask : null;
  5818. this.tempSMask = null;
  5819. this.checkSMaskState();
  5820. break;
  5821. case "TR":
  5822. this.current.transferMaps = value;
  5823. }
  5824. }
  5825. }
  5826. get inSMaskMode() {
  5827. return !!this.suspendedCtx;
  5828. }
  5829. checkSMaskState() {
  5830. const inSMaskMode = this.inSMaskMode;
  5831. if (this.current.activeSMask && !inSMaskMode) {
  5832. this.beginSMaskMode();
  5833. } else if (!this.current.activeSMask && inSMaskMode) {
  5834. this.endSMaskMode();
  5835. }
  5836. }
  5837. beginSMaskMode() {
  5838. if (this.inSMaskMode) {
  5839. throw new Error("beginSMaskMode called while already in smask mode");
  5840. }
  5841. const drawnWidth = this.ctx.canvas.width;
  5842. const drawnHeight = this.ctx.canvas.height;
  5843. const cacheId = "smaskGroupAt" + this.groupLevel;
  5844. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  5845. this.suspendedCtx = this.ctx;
  5846. this.ctx = scratchCanvas.context;
  5847. const ctx = this.ctx;
  5848. ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
  5849. copyCtxState(this.suspendedCtx, ctx);
  5850. mirrorContextOperations(ctx, this.suspendedCtx);
  5851. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  5852. }
  5853. endSMaskMode() {
  5854. if (!this.inSMaskMode) {
  5855. throw new Error("endSMaskMode called while not in smask mode");
  5856. }
  5857. this.ctx._removeMirroring();
  5858. copyCtxState(this.ctx, this.suspendedCtx);
  5859. this.ctx = this.suspendedCtx;
  5860. this.suspendedCtx = null;
  5861. }
  5862. compose(dirtyBox) {
  5863. if (!this.current.activeSMask) {
  5864. return;
  5865. }
  5866. if (!dirtyBox) {
  5867. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  5868. } else {
  5869. dirtyBox[0] = Math.floor(dirtyBox[0]);
  5870. dirtyBox[1] = Math.floor(dirtyBox[1]);
  5871. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  5872. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  5873. }
  5874. const smask = this.current.activeSMask;
  5875. const suspendedCtx = this.suspendedCtx;
  5876. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  5877. this.ctx.save();
  5878. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  5879. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  5880. this.ctx.restore();
  5881. }
  5882. save() {
  5883. if (this.inSMaskMode) {
  5884. copyCtxState(this.ctx, this.suspendedCtx);
  5885. this.suspendedCtx.save();
  5886. } else {
  5887. this.ctx.save();
  5888. }
  5889. const old = this.current;
  5890. this.stateStack.push(old);
  5891. this.current = old.clone();
  5892. }
  5893. restore() {
  5894. if (this.stateStack.length === 0 && this.inSMaskMode) {
  5895. this.endSMaskMode();
  5896. }
  5897. if (this.stateStack.length !== 0) {
  5898. this.current = this.stateStack.pop();
  5899. if (this.inSMaskMode) {
  5900. this.suspendedCtx.restore();
  5901. copyCtxState(this.suspendedCtx, this.ctx);
  5902. } else {
  5903. this.ctx.restore();
  5904. }
  5905. this.checkSMaskState();
  5906. this.pendingClip = null;
  5907. this._cachedScaleForStroking = null;
  5908. this._cachedGetSinglePixelWidth = null;
  5909. }
  5910. }
  5911. transform(a, b, c, d, e, f) {
  5912. this.ctx.transform(a, b, c, d, e, f);
  5913. this._cachedScaleForStroking = null;
  5914. this._cachedGetSinglePixelWidth = null;
  5915. }
  5916. constructPath(ops, args, minMax) {
  5917. const ctx = this.ctx;
  5918. const current = this.current;
  5919. let x = current.x,
  5920. y = current.y;
  5921. let startX, startY;
  5922. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  5923. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  5924. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  5925. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  5926. switch (ops[i] | 0) {
  5927. case _util.OPS.rectangle:
  5928. x = args[j++];
  5929. y = args[j++];
  5930. const width = args[j++];
  5931. const height = args[j++];
  5932. const xw = x + width;
  5933. const yh = y + height;
  5934. ctx.moveTo(x, y);
  5935. if (width === 0 || height === 0) {
  5936. ctx.lineTo(xw, yh);
  5937. } else {
  5938. ctx.lineTo(xw, y);
  5939. ctx.lineTo(xw, yh);
  5940. ctx.lineTo(x, yh);
  5941. }
  5942. if (!isScalingMatrix) {
  5943. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  5944. }
  5945. ctx.closePath();
  5946. break;
  5947. case _util.OPS.moveTo:
  5948. x = args[j++];
  5949. y = args[j++];
  5950. ctx.moveTo(x, y);
  5951. if (!isScalingMatrix) {
  5952. current.updatePathMinMax(currentTransform, x, y);
  5953. }
  5954. break;
  5955. case _util.OPS.lineTo:
  5956. x = args[j++];
  5957. y = args[j++];
  5958. ctx.lineTo(x, y);
  5959. if (!isScalingMatrix) {
  5960. current.updatePathMinMax(currentTransform, x, y);
  5961. }
  5962. break;
  5963. case _util.OPS.curveTo:
  5964. startX = x;
  5965. startY = y;
  5966. x = args[j + 4];
  5967. y = args[j + 5];
  5968. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  5969. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  5970. j += 6;
  5971. break;
  5972. case _util.OPS.curveTo2:
  5973. startX = x;
  5974. startY = y;
  5975. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  5976. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  5977. x = args[j + 2];
  5978. y = args[j + 3];
  5979. j += 4;
  5980. break;
  5981. case _util.OPS.curveTo3:
  5982. startX = x;
  5983. startY = y;
  5984. x = args[j + 2];
  5985. y = args[j + 3];
  5986. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  5987. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  5988. j += 4;
  5989. break;
  5990. case _util.OPS.closePath:
  5991. ctx.closePath();
  5992. break;
  5993. }
  5994. }
  5995. if (isScalingMatrix) {
  5996. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  5997. }
  5998. current.setCurrentPoint(x, y);
  5999. }
  6000. closePath() {
  6001. this.ctx.closePath();
  6002. }
  6003. stroke(consumePath) {
  6004. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  6005. const ctx = this.ctx;
  6006. const strokeColor = this.current.strokeColor;
  6007. ctx.globalAlpha = this.current.strokeAlpha;
  6008. if (this.contentVisible) {
  6009. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  6010. ctx.save();
  6011. ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
  6012. this.rescaleAndStroke(false);
  6013. ctx.restore();
  6014. } else {
  6015. this.rescaleAndStroke(true);
  6016. }
  6017. }
  6018. if (consumePath) {
  6019. this.consumePath(this.current.getClippedPathBoundingBox());
  6020. }
  6021. ctx.globalAlpha = this.current.fillAlpha;
  6022. }
  6023. closeStroke() {
  6024. this.closePath();
  6025. this.stroke();
  6026. }
  6027. fill(consumePath) {
  6028. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  6029. const ctx = this.ctx;
  6030. const fillColor = this.current.fillColor;
  6031. const isPatternFill = this.current.patternFill;
  6032. let needRestore = false;
  6033. if (isPatternFill) {
  6034. ctx.save();
  6035. ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6036. needRestore = true;
  6037. }
  6038. const intersect = this.current.getClippedPathBoundingBox();
  6039. if (this.contentVisible && intersect !== null) {
  6040. if (this.pendingEOFill) {
  6041. ctx.fill("evenodd");
  6042. this.pendingEOFill = false;
  6043. } else {
  6044. ctx.fill();
  6045. }
  6046. }
  6047. if (needRestore) {
  6048. ctx.restore();
  6049. }
  6050. if (consumePath) {
  6051. this.consumePath(intersect);
  6052. }
  6053. }
  6054. eoFill() {
  6055. this.pendingEOFill = true;
  6056. this.fill();
  6057. }
  6058. fillStroke() {
  6059. this.fill(false);
  6060. this.stroke(false);
  6061. this.consumePath();
  6062. }
  6063. eoFillStroke() {
  6064. this.pendingEOFill = true;
  6065. this.fillStroke();
  6066. }
  6067. closeFillStroke() {
  6068. this.closePath();
  6069. this.fillStroke();
  6070. }
  6071. closeEOFillStroke() {
  6072. this.pendingEOFill = true;
  6073. this.closePath();
  6074. this.fillStroke();
  6075. }
  6076. endPath() {
  6077. this.consumePath();
  6078. }
  6079. clip() {
  6080. this.pendingClip = NORMAL_CLIP;
  6081. }
  6082. eoClip() {
  6083. this.pendingClip = EO_CLIP;
  6084. }
  6085. beginText() {
  6086. this.current.textMatrix = _util.IDENTITY_MATRIX;
  6087. this.current.textMatrixScale = 1;
  6088. this.current.x = this.current.lineX = 0;
  6089. this.current.y = this.current.lineY = 0;
  6090. }
  6091. endText() {
  6092. const paths = this.pendingTextPaths;
  6093. const ctx = this.ctx;
  6094. if (paths === undefined) {
  6095. ctx.beginPath();
  6096. return;
  6097. }
  6098. ctx.save();
  6099. ctx.beginPath();
  6100. for (const path of paths) {
  6101. ctx.setTransform(...path.transform);
  6102. ctx.translate(path.x, path.y);
  6103. path.addToPath(ctx, path.fontSize);
  6104. }
  6105. ctx.restore();
  6106. ctx.clip();
  6107. ctx.beginPath();
  6108. delete this.pendingTextPaths;
  6109. }
  6110. setCharSpacing(spacing) {
  6111. this.current.charSpacing = spacing;
  6112. }
  6113. setWordSpacing(spacing) {
  6114. this.current.wordSpacing = spacing;
  6115. }
  6116. setHScale(scale) {
  6117. this.current.textHScale = scale / 100;
  6118. }
  6119. setLeading(leading) {
  6120. this.current.leading = -leading;
  6121. }
  6122. setFont(fontRefName, size) {
  6123. const fontObj = this.commonObjs.get(fontRefName);
  6124. const current = this.current;
  6125. if (!fontObj) {
  6126. throw new Error(`Can't find font for ${fontRefName}`);
  6127. }
  6128. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6129. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  6130. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  6131. }
  6132. if (size < 0) {
  6133. size = -size;
  6134. current.fontDirection = -1;
  6135. } else {
  6136. current.fontDirection = 1;
  6137. }
  6138. this.current.font = fontObj;
  6139. this.current.fontSize = size;
  6140. if (fontObj.isType3Font) {
  6141. return;
  6142. }
  6143. const name = fontObj.loadedName || "sans-serif";
  6144. let bold = "normal";
  6145. if (fontObj.black) {
  6146. bold = "900";
  6147. } else if (fontObj.bold) {
  6148. bold = "bold";
  6149. }
  6150. const italic = fontObj.italic ? "italic" : "normal";
  6151. const typeface = `"${name}", ${fontObj.fallbackName}`;
  6152. let browserFontSize = size;
  6153. if (size < MIN_FONT_SIZE) {
  6154. browserFontSize = MIN_FONT_SIZE;
  6155. } else if (size > MAX_FONT_SIZE) {
  6156. browserFontSize = MAX_FONT_SIZE;
  6157. }
  6158. this.current.fontSizeScale = size / browserFontSize;
  6159. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  6160. }
  6161. setTextRenderingMode(mode) {
  6162. this.current.textRenderingMode = mode;
  6163. }
  6164. setTextRise(rise) {
  6165. this.current.textRise = rise;
  6166. }
  6167. moveText(x, y) {
  6168. this.current.x = this.current.lineX += x;
  6169. this.current.y = this.current.lineY += y;
  6170. }
  6171. setLeadingMoveText(x, y) {
  6172. this.setLeading(-y);
  6173. this.moveText(x, y);
  6174. }
  6175. setTextMatrix(a, b, c, d, e, f) {
  6176. this.current.textMatrix = [a, b, c, d, e, f];
  6177. this.current.textMatrixScale = Math.hypot(a, b);
  6178. this.current.x = this.current.lineX = 0;
  6179. this.current.y = this.current.lineY = 0;
  6180. }
  6181. nextLine() {
  6182. this.moveText(0, this.current.leading);
  6183. }
  6184. paintChar(character, x, y, patternTransform) {
  6185. const ctx = this.ctx;
  6186. const current = this.current;
  6187. const font = current.font;
  6188. const textRenderingMode = current.textRenderingMode;
  6189. const fontSize = current.fontSize / current.fontSizeScale;
  6190. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6191. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  6192. const patternFill = current.patternFill && !font.missingFile;
  6193. let addToPath;
  6194. if (font.disableFontFace || isAddToPathSet || patternFill) {
  6195. addToPath = font.getPathGenerator(this.commonObjs, character);
  6196. }
  6197. if (font.disableFontFace || patternFill) {
  6198. ctx.save();
  6199. ctx.translate(x, y);
  6200. ctx.beginPath();
  6201. addToPath(ctx, fontSize);
  6202. if (patternTransform) {
  6203. ctx.setTransform(...patternTransform);
  6204. }
  6205. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6206. ctx.fill();
  6207. }
  6208. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6209. ctx.stroke();
  6210. }
  6211. ctx.restore();
  6212. } else {
  6213. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6214. ctx.fillText(character, x, y);
  6215. }
  6216. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6217. ctx.strokeText(character, x, y);
  6218. }
  6219. }
  6220. if (isAddToPathSet) {
  6221. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6222. paths.push({
  6223. transform: (0, _display_utils.getCurrentTransform)(ctx),
  6224. x,
  6225. y,
  6226. fontSize,
  6227. addToPath
  6228. });
  6229. }
  6230. }
  6231. get isFontSubpixelAAEnabled() {
  6232. const {
  6233. context: ctx
  6234. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  6235. ctx.scale(1.5, 1);
  6236. ctx.fillText("I", 0, 10);
  6237. const data = ctx.getImageData(0, 0, 10, 10).data;
  6238. let enabled = false;
  6239. for (let i = 3; i < data.length; i += 4) {
  6240. if (data[i] > 0 && data[i] < 255) {
  6241. enabled = true;
  6242. break;
  6243. }
  6244. }
  6245. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  6246. }
  6247. showText(glyphs) {
  6248. const current = this.current;
  6249. const font = current.font;
  6250. if (font.isType3Font) {
  6251. return this.showType3Text(glyphs);
  6252. }
  6253. const fontSize = current.fontSize;
  6254. if (fontSize === 0) {
  6255. return undefined;
  6256. }
  6257. const ctx = this.ctx;
  6258. const fontSizeScale = current.fontSizeScale;
  6259. const charSpacing = current.charSpacing;
  6260. const wordSpacing = current.wordSpacing;
  6261. const fontDirection = current.fontDirection;
  6262. const textHScale = current.textHScale * fontDirection;
  6263. const glyphsLength = glyphs.length;
  6264. const vertical = font.vertical;
  6265. const spacingDir = vertical ? 1 : -1;
  6266. const defaultVMetrics = font.defaultVMetrics;
  6267. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  6268. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  6269. ctx.save();
  6270. ctx.transform(...current.textMatrix);
  6271. ctx.translate(current.x, current.y + current.textRise);
  6272. if (fontDirection > 0) {
  6273. ctx.scale(textHScale, -1);
  6274. } else {
  6275. ctx.scale(textHScale, 1);
  6276. }
  6277. let patternTransform;
  6278. if (current.patternFill) {
  6279. ctx.save();
  6280. const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6281. patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6282. ctx.restore();
  6283. ctx.fillStyle = pattern;
  6284. }
  6285. let lineWidth = current.lineWidth;
  6286. const scale = current.textMatrixScale;
  6287. if (scale === 0 || lineWidth === 0) {
  6288. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6289. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6290. lineWidth = this.getSinglePixelWidth();
  6291. }
  6292. } else {
  6293. lineWidth /= scale;
  6294. }
  6295. if (fontSizeScale !== 1.0) {
  6296. ctx.scale(fontSizeScale, fontSizeScale);
  6297. lineWidth /= fontSizeScale;
  6298. }
  6299. ctx.lineWidth = lineWidth;
  6300. if (font.isInvalidPDFjsFont) {
  6301. const chars = [];
  6302. let width = 0;
  6303. for (const glyph of glyphs) {
  6304. chars.push(glyph.unicode);
  6305. width += glyph.width;
  6306. }
  6307. ctx.fillText(chars.join(""), 0, 0);
  6308. current.x += width * widthAdvanceScale * textHScale;
  6309. ctx.restore();
  6310. this.compose();
  6311. return undefined;
  6312. }
  6313. let x = 0,
  6314. i;
  6315. for (i = 0; i < glyphsLength; ++i) {
  6316. const glyph = glyphs[i];
  6317. if (typeof glyph === "number") {
  6318. x += spacingDir * glyph * fontSize / 1000;
  6319. continue;
  6320. }
  6321. let restoreNeeded = false;
  6322. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6323. const character = glyph.fontChar;
  6324. const accent = glyph.accent;
  6325. let scaledX, scaledY;
  6326. let width = glyph.width;
  6327. if (vertical) {
  6328. const vmetric = glyph.vmetric || defaultVMetrics;
  6329. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  6330. const vy = vmetric[2] * widthAdvanceScale;
  6331. width = vmetric ? -vmetric[0] : width;
  6332. scaledX = vx / fontSizeScale;
  6333. scaledY = (x + vy) / fontSizeScale;
  6334. } else {
  6335. scaledX = x / fontSizeScale;
  6336. scaledY = 0;
  6337. }
  6338. if (font.remeasure && width > 0) {
  6339. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  6340. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6341. const characterScaleX = width / measuredWidth;
  6342. restoreNeeded = true;
  6343. ctx.save();
  6344. ctx.scale(characterScaleX, 1);
  6345. scaledX /= characterScaleX;
  6346. } else if (width !== measuredWidth) {
  6347. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  6348. }
  6349. }
  6350. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  6351. if (simpleFillText && !accent) {
  6352. ctx.fillText(character, scaledX, scaledY);
  6353. } else {
  6354. this.paintChar(character, scaledX, scaledY, patternTransform);
  6355. if (accent) {
  6356. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  6357. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  6358. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  6359. }
  6360. }
  6361. }
  6362. let charWidth;
  6363. if (vertical) {
  6364. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  6365. } else {
  6366. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6367. }
  6368. x += charWidth;
  6369. if (restoreNeeded) {
  6370. ctx.restore();
  6371. }
  6372. }
  6373. if (vertical) {
  6374. current.y -= x;
  6375. } else {
  6376. current.x += x * textHScale;
  6377. }
  6378. ctx.restore();
  6379. this.compose();
  6380. return undefined;
  6381. }
  6382. showType3Text(glyphs) {
  6383. const ctx = this.ctx;
  6384. const current = this.current;
  6385. const font = current.font;
  6386. const fontSize = current.fontSize;
  6387. const fontDirection = current.fontDirection;
  6388. const spacingDir = font.vertical ? 1 : -1;
  6389. const charSpacing = current.charSpacing;
  6390. const wordSpacing = current.wordSpacing;
  6391. const textHScale = current.textHScale * fontDirection;
  6392. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6393. const glyphsLength = glyphs.length;
  6394. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  6395. let i, glyph, width, spacingLength;
  6396. if (isTextInvisible || fontSize === 0) {
  6397. return;
  6398. }
  6399. this._cachedScaleForStroking = null;
  6400. this._cachedGetSinglePixelWidth = null;
  6401. ctx.save();
  6402. ctx.transform(...current.textMatrix);
  6403. ctx.translate(current.x, current.y);
  6404. ctx.scale(textHScale, fontDirection);
  6405. for (i = 0; i < glyphsLength; ++i) {
  6406. glyph = glyphs[i];
  6407. if (typeof glyph === "number") {
  6408. spacingLength = spacingDir * glyph * fontSize / 1000;
  6409. this.ctx.translate(spacingLength, 0);
  6410. current.x += spacingLength * textHScale;
  6411. continue;
  6412. }
  6413. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6414. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  6415. if (!operatorList) {
  6416. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  6417. continue;
  6418. }
  6419. if (this.contentVisible) {
  6420. this.processingType3 = glyph;
  6421. this.save();
  6422. ctx.scale(fontSize, fontSize);
  6423. ctx.transform(...fontMatrix);
  6424. this.executeOperatorList(operatorList);
  6425. this.restore();
  6426. }
  6427. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  6428. width = transformed[0] * fontSize + spacing;
  6429. ctx.translate(width, 0);
  6430. current.x += width * textHScale;
  6431. }
  6432. ctx.restore();
  6433. this.processingType3 = null;
  6434. }
  6435. setCharWidth(xWidth, yWidth) {}
  6436. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  6437. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  6438. this.ctx.clip();
  6439. this.endPath();
  6440. }
  6441. getColorN_Pattern(IR) {
  6442. let pattern;
  6443. if (IR[0] === "TilingPattern") {
  6444. const color = IR[1];
  6445. const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
  6446. const canvasGraphicsFactory = {
  6447. createCanvasGraphics: ctx => {
  6448. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, {
  6449. optionalContentConfig: this.optionalContentConfig,
  6450. markedContentStack: this.markedContentStack
  6451. });
  6452. }
  6453. };
  6454. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  6455. } else {
  6456. pattern = this._getPattern(IR[1], IR[2]);
  6457. }
  6458. return pattern;
  6459. }
  6460. setStrokeColorN() {
  6461. this.current.strokeColor = this.getColorN_Pattern(arguments);
  6462. }
  6463. setFillColorN() {
  6464. this.current.fillColor = this.getColorN_Pattern(arguments);
  6465. this.current.patternFill = true;
  6466. }
  6467. setStrokeRGBColor(r, g, b) {
  6468. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6469. this.ctx.strokeStyle = color;
  6470. this.current.strokeColor = color;
  6471. }
  6472. setFillRGBColor(r, g, b) {
  6473. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6474. this.ctx.fillStyle = color;
  6475. this.current.fillColor = color;
  6476. this.current.patternFill = false;
  6477. }
  6478. _getPattern(objId, matrix = null) {
  6479. let pattern;
  6480. if (this.cachedPatterns.has(objId)) {
  6481. pattern = this.cachedPatterns.get(objId);
  6482. } else {
  6483. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  6484. this.cachedPatterns.set(objId, pattern);
  6485. }
  6486. if (matrix) {
  6487. pattern.matrix = matrix;
  6488. }
  6489. return pattern;
  6490. }
  6491. shadingFill(objId) {
  6492. if (!this.contentVisible) {
  6493. return;
  6494. }
  6495. const ctx = this.ctx;
  6496. this.save();
  6497. const pattern = this._getPattern(objId);
  6498. ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
  6499. const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
  6500. if (inv) {
  6501. const canvas = ctx.canvas;
  6502. const width = canvas.width;
  6503. const height = canvas.height;
  6504. const bl = _util.Util.applyTransform([0, 0], inv);
  6505. const br = _util.Util.applyTransform([0, height], inv);
  6506. const ul = _util.Util.applyTransform([width, 0], inv);
  6507. const ur = _util.Util.applyTransform([width, height], inv);
  6508. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6509. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6510. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6511. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6512. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6513. } else {
  6514. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6515. }
  6516. this.compose(this.current.getClippedPathBoundingBox());
  6517. this.restore();
  6518. }
  6519. beginInlineImage() {
  6520. (0, _util.unreachable)("Should not call beginInlineImage");
  6521. }
  6522. beginImageData() {
  6523. (0, _util.unreachable)("Should not call beginImageData");
  6524. }
  6525. paintFormXObjectBegin(matrix, bbox) {
  6526. if (!this.contentVisible) {
  6527. return;
  6528. }
  6529. this.save();
  6530. this.baseTransformStack.push(this.baseTransform);
  6531. if (Array.isArray(matrix) && matrix.length === 6) {
  6532. this.transform(...matrix);
  6533. }
  6534. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  6535. if (bbox) {
  6536. const width = bbox[2] - bbox[0];
  6537. const height = bbox[3] - bbox[1];
  6538. this.ctx.rect(bbox[0], bbox[1], width, height);
  6539. this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
  6540. this.clip();
  6541. this.endPath();
  6542. }
  6543. }
  6544. paintFormXObjectEnd() {
  6545. if (!this.contentVisible) {
  6546. return;
  6547. }
  6548. this.restore();
  6549. this.baseTransform = this.baseTransformStack.pop();
  6550. }
  6551. beginGroup(group) {
  6552. if (!this.contentVisible) {
  6553. return;
  6554. }
  6555. this.save();
  6556. if (this.inSMaskMode) {
  6557. this.endSMaskMode();
  6558. this.current.activeSMask = null;
  6559. }
  6560. const currentCtx = this.ctx;
  6561. if (!group.isolated) {
  6562. (0, _util.info)("TODO: Support non-isolated groups.");
  6563. }
  6564. if (group.knockout) {
  6565. (0, _util.warn)("Knockout groups not supported.");
  6566. }
  6567. const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
  6568. if (group.matrix) {
  6569. currentCtx.transform(...group.matrix);
  6570. }
  6571. if (!group.bbox) {
  6572. throw new Error("Bounding box is required.");
  6573. }
  6574. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
  6575. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  6576. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6577. const offsetX = Math.floor(bounds[0]);
  6578. const offsetY = Math.floor(bounds[1]);
  6579. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6580. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6581. let scaleX = 1,
  6582. scaleY = 1;
  6583. if (drawnWidth > MAX_GROUP_SIZE) {
  6584. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6585. drawnWidth = MAX_GROUP_SIZE;
  6586. }
  6587. if (drawnHeight > MAX_GROUP_SIZE) {
  6588. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6589. drawnHeight = MAX_GROUP_SIZE;
  6590. }
  6591. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  6592. let cacheId = "groupAt" + this.groupLevel;
  6593. if (group.smask) {
  6594. cacheId += "_smask_" + this.smaskCounter++ % 2;
  6595. }
  6596. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  6597. const groupCtx = scratchCanvas.context;
  6598. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6599. groupCtx.translate(-offsetX, -offsetY);
  6600. groupCtx.transform(...currentTransform);
  6601. if (group.smask) {
  6602. this.smaskStack.push({
  6603. canvas: scratchCanvas.canvas,
  6604. context: groupCtx,
  6605. offsetX,
  6606. offsetY,
  6607. scaleX,
  6608. scaleY,
  6609. subtype: group.smask.subtype,
  6610. backdrop: group.smask.backdrop,
  6611. transferMap: group.smask.transferMap || null,
  6612. startTransformInverse: null
  6613. });
  6614. } else {
  6615. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6616. currentCtx.translate(offsetX, offsetY);
  6617. currentCtx.scale(scaleX, scaleY);
  6618. currentCtx.save();
  6619. }
  6620. copyCtxState(currentCtx, groupCtx);
  6621. this.ctx = groupCtx;
  6622. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  6623. this.groupStack.push(currentCtx);
  6624. this.groupLevel++;
  6625. }
  6626. endGroup(group) {
  6627. if (!this.contentVisible) {
  6628. return;
  6629. }
  6630. this.groupLevel--;
  6631. const groupCtx = this.ctx;
  6632. const ctx = this.groupStack.pop();
  6633. this.ctx = ctx;
  6634. this.ctx.imageSmoothingEnabled = false;
  6635. if (group.smask) {
  6636. this.tempSMask = this.smaskStack.pop();
  6637. this.restore();
  6638. } else {
  6639. this.ctx.restore();
  6640. const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
  6641. this.restore();
  6642. this.ctx.save();
  6643. this.ctx.setTransform(...currentMtx);
  6644. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  6645. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6646. this.ctx.restore();
  6647. this.compose(dirtyBox);
  6648. }
  6649. }
  6650. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  6651. this.#restoreInitialState();
  6652. resetCtxToDefault(this.ctx, this.foregroundColor);
  6653. this.ctx.save();
  6654. this.save();
  6655. if (this.baseTransform) {
  6656. this.ctx.setTransform(...this.baseTransform);
  6657. }
  6658. if (Array.isArray(rect) && rect.length === 4) {
  6659. const width = rect[2] - rect[0];
  6660. const height = rect[3] - rect[1];
  6661. if (hasOwnCanvas && this.annotationCanvasMap) {
  6662. transform = transform.slice();
  6663. transform[4] -= rect[0];
  6664. transform[5] -= rect[1];
  6665. rect = rect.slice();
  6666. rect[0] = rect[1] = 0;
  6667. rect[2] = width;
  6668. rect[3] = height;
  6669. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
  6670. const {
  6671. viewportScale
  6672. } = this;
  6673. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  6674. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  6675. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  6676. const {
  6677. canvas,
  6678. context
  6679. } = this.annotationCanvas;
  6680. this.annotationCanvasMap.set(id, canvas);
  6681. this.annotationCanvas.savedCtx = this.ctx;
  6682. this.ctx = context;
  6683. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  6684. resetCtxToDefault(this.ctx, this.foregroundColor);
  6685. } else {
  6686. resetCtxToDefault(this.ctx, this.foregroundColor);
  6687. this.ctx.rect(rect[0], rect[1], width, height);
  6688. this.ctx.clip();
  6689. this.endPath();
  6690. }
  6691. }
  6692. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  6693. this.transform(...transform);
  6694. this.transform(...matrix);
  6695. }
  6696. endAnnotation() {
  6697. if (this.annotationCanvas) {
  6698. this.ctx = this.annotationCanvas.savedCtx;
  6699. delete this.annotationCanvas.savedCtx;
  6700. delete this.annotationCanvas;
  6701. }
  6702. }
  6703. paintImageMaskXObject(img) {
  6704. if (!this.contentVisible) {
  6705. return;
  6706. }
  6707. const count = img.count;
  6708. img = this.getObject(img.data, img);
  6709. img.count = count;
  6710. const ctx = this.ctx;
  6711. const glyph = this.processingType3;
  6712. if (glyph) {
  6713. if (glyph.compiled === undefined) {
  6714. glyph.compiled = compileType3Glyph(img);
  6715. }
  6716. if (glyph.compiled) {
  6717. glyph.compiled(ctx);
  6718. return;
  6719. }
  6720. }
  6721. const mask = this._createMaskCanvas(img);
  6722. const maskCanvas = mask.canvas;
  6723. ctx.save();
  6724. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6725. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  6726. ctx.restore();
  6727. this.compose();
  6728. }
  6729. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  6730. if (!this.contentVisible) {
  6731. return;
  6732. }
  6733. img = this.getObject(img.data, img);
  6734. const ctx = this.ctx;
  6735. ctx.save();
  6736. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6737. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  6738. const mask = this._createMaskCanvas(img);
  6739. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  6740. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6741. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  6742. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  6743. ctx.drawImage(mask.canvas, x, y);
  6744. }
  6745. ctx.restore();
  6746. this.compose();
  6747. }
  6748. paintImageMaskXObjectGroup(images) {
  6749. if (!this.contentVisible) {
  6750. return;
  6751. }
  6752. const ctx = this.ctx;
  6753. const fillColor = this.current.fillColor;
  6754. const isPatternFill = this.current.patternFill;
  6755. for (const image of images) {
  6756. const {
  6757. data,
  6758. width,
  6759. height,
  6760. transform
  6761. } = image;
  6762. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  6763. const maskCtx = maskCanvas.context;
  6764. maskCtx.save();
  6765. const img = this.getObject(data, image);
  6766. putBinaryImageMask(maskCtx, img);
  6767. maskCtx.globalCompositeOperation = "source-in";
  6768. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
  6769. maskCtx.fillRect(0, 0, width, height);
  6770. maskCtx.restore();
  6771. ctx.save();
  6772. ctx.transform(...transform);
  6773. ctx.scale(1, -1);
  6774. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  6775. ctx.restore();
  6776. }
  6777. this.compose();
  6778. }
  6779. paintImageXObject(objId) {
  6780. if (!this.contentVisible) {
  6781. return;
  6782. }
  6783. const imgData = this.getObject(objId);
  6784. if (!imgData) {
  6785. (0, _util.warn)("Dependent image isn't ready yet");
  6786. return;
  6787. }
  6788. this.paintInlineImageXObject(imgData);
  6789. }
  6790. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  6791. if (!this.contentVisible) {
  6792. return;
  6793. }
  6794. const imgData = this.getObject(objId);
  6795. if (!imgData) {
  6796. (0, _util.warn)("Dependent image isn't ready yet");
  6797. return;
  6798. }
  6799. const width = imgData.width;
  6800. const height = imgData.height;
  6801. const map = [];
  6802. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6803. map.push({
  6804. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  6805. x: 0,
  6806. y: 0,
  6807. w: width,
  6808. h: height
  6809. });
  6810. }
  6811. this.paintInlineImageXObjectGroup(imgData, map);
  6812. }
  6813. paintInlineImageXObject(imgData) {
  6814. if (!this.contentVisible) {
  6815. return;
  6816. }
  6817. const width = imgData.width;
  6818. const height = imgData.height;
  6819. const ctx = this.ctx;
  6820. this.save();
  6821. ctx.scale(1 / width, -1 / height);
  6822. let imgToPaint;
  6823. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  6824. imgToPaint = imgData;
  6825. } else {
  6826. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  6827. const tmpCtx = tmpCanvas.context;
  6828. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  6829. imgToPaint = tmpCanvas.canvas;
  6830. }
  6831. const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
  6832. ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
  6833. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  6834. this.compose();
  6835. this.restore();
  6836. }
  6837. paintInlineImageXObjectGroup(imgData, map) {
  6838. if (!this.contentVisible) {
  6839. return;
  6840. }
  6841. const ctx = this.ctx;
  6842. const w = imgData.width;
  6843. const h = imgData.height;
  6844. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  6845. const tmpCtx = tmpCanvas.context;
  6846. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  6847. for (const entry of map) {
  6848. ctx.save();
  6849. ctx.transform(...entry.transform);
  6850. ctx.scale(1, -1);
  6851. drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  6852. ctx.restore();
  6853. }
  6854. this.compose();
  6855. }
  6856. paintSolidColorImageMask() {
  6857. if (!this.contentVisible) {
  6858. return;
  6859. }
  6860. this.ctx.fillRect(0, 0, 1, 1);
  6861. this.compose();
  6862. }
  6863. markPoint(tag) {}
  6864. markPointProps(tag, properties) {}
  6865. beginMarkedContent(tag) {
  6866. this.markedContentStack.push({
  6867. visible: true
  6868. });
  6869. }
  6870. beginMarkedContentProps(tag, properties) {
  6871. if (tag === "OC") {
  6872. this.markedContentStack.push({
  6873. visible: this.optionalContentConfig.isVisible(properties)
  6874. });
  6875. } else {
  6876. this.markedContentStack.push({
  6877. visible: true
  6878. });
  6879. }
  6880. this.contentVisible = this.isContentVisible();
  6881. }
  6882. endMarkedContent() {
  6883. this.markedContentStack.pop();
  6884. this.contentVisible = this.isContentVisible();
  6885. }
  6886. beginCompat() {}
  6887. endCompat() {}
  6888. consumePath(clipBox) {
  6889. const isEmpty = this.current.isEmptyClip();
  6890. if (this.pendingClip) {
  6891. this.current.updateClipFromPath();
  6892. }
  6893. if (!this.pendingClip) {
  6894. this.compose(clipBox);
  6895. }
  6896. const ctx = this.ctx;
  6897. if (this.pendingClip) {
  6898. if (!isEmpty) {
  6899. if (this.pendingClip === EO_CLIP) {
  6900. ctx.clip("evenodd");
  6901. } else {
  6902. ctx.clip();
  6903. }
  6904. }
  6905. this.pendingClip = null;
  6906. }
  6907. this.current.startNewPathAndClipBox(this.current.clipBox);
  6908. ctx.beginPath();
  6909. }
  6910. getSinglePixelWidth() {
  6911. if (!this._cachedGetSinglePixelWidth) {
  6912. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  6913. if (m[1] === 0 && m[2] === 0) {
  6914. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  6915. } else {
  6916. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  6917. const normX = Math.hypot(m[0], m[2]);
  6918. const normY = Math.hypot(m[1], m[3]);
  6919. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  6920. }
  6921. }
  6922. return this._cachedGetSinglePixelWidth;
  6923. }
  6924. getScaleForStroking() {
  6925. if (!this._cachedScaleForStroking) {
  6926. const {
  6927. lineWidth
  6928. } = this.current;
  6929. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  6930. let scaleX, scaleY;
  6931. if (m[1] === 0 && m[2] === 0) {
  6932. const normX = Math.abs(m[0]);
  6933. const normY = Math.abs(m[3]);
  6934. if (lineWidth === 0) {
  6935. scaleX = 1 / normX;
  6936. scaleY = 1 / normY;
  6937. } else {
  6938. const scaledXLineWidth = normX * lineWidth;
  6939. const scaledYLineWidth = normY * lineWidth;
  6940. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  6941. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  6942. }
  6943. } else {
  6944. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  6945. const normX = Math.hypot(m[0], m[1]);
  6946. const normY = Math.hypot(m[2], m[3]);
  6947. if (lineWidth === 0) {
  6948. scaleX = normY / absDet;
  6949. scaleY = normX / absDet;
  6950. } else {
  6951. const baseArea = lineWidth * absDet;
  6952. scaleX = normY > baseArea ? normY / baseArea : 1;
  6953. scaleY = normX > baseArea ? normX / baseArea : 1;
  6954. }
  6955. }
  6956. this._cachedScaleForStroking = [scaleX, scaleY];
  6957. }
  6958. return this._cachedScaleForStroking;
  6959. }
  6960. rescaleAndStroke(saveRestore) {
  6961. const {
  6962. ctx
  6963. } = this;
  6964. const {
  6965. lineWidth
  6966. } = this.current;
  6967. const [scaleX, scaleY] = this.getScaleForStroking();
  6968. ctx.lineWidth = lineWidth || 1;
  6969. if (scaleX === 1 && scaleY === 1) {
  6970. ctx.stroke();
  6971. return;
  6972. }
  6973. let savedMatrix, savedDashes, savedDashOffset;
  6974. if (saveRestore) {
  6975. savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
  6976. savedDashes = ctx.getLineDash().slice();
  6977. savedDashOffset = ctx.lineDashOffset;
  6978. }
  6979. ctx.scale(scaleX, scaleY);
  6980. const scale = Math.max(scaleX, scaleY);
  6981. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  6982. ctx.lineDashOffset /= scale;
  6983. ctx.stroke();
  6984. if (saveRestore) {
  6985. ctx.setTransform(...savedMatrix);
  6986. ctx.setLineDash(savedDashes);
  6987. ctx.lineDashOffset = savedDashOffset;
  6988. }
  6989. }
  6990. isContentVisible() {
  6991. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  6992. if (!this.markedContentStack[i].visible) {
  6993. return false;
  6994. }
  6995. }
  6996. return true;
  6997. }
  6998. }
  6999. exports.CanvasGraphics = CanvasGraphics;
  7000. for (const op in _util.OPS) {
  7001. if (CanvasGraphics.prototype[op] !== undefined) {
  7002. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  7003. }
  7004. }
  7005. /***/ }),
  7006. /* 11 */
  7007. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7008. Object.defineProperty(exports, "__esModule", ({
  7009. value: true
  7010. }));
  7011. exports.TilingPattern = exports.PathType = void 0;
  7012. exports.getShadingPattern = getShadingPattern;
  7013. var _util = __w_pdfjs_require__(1);
  7014. var _display_utils = __w_pdfjs_require__(6);
  7015. var _is_node = __w_pdfjs_require__(12);
  7016. const PathType = {
  7017. FILL: "Fill",
  7018. STROKE: "Stroke",
  7019. SHADING: "Shading"
  7020. };
  7021. exports.PathType = PathType;
  7022. function applyBoundingBox(ctx, bbox) {
  7023. if (!bbox || _is_node.isNodeJS) {
  7024. return;
  7025. }
  7026. const width = bbox[2] - bbox[0];
  7027. const height = bbox[3] - bbox[1];
  7028. const region = new Path2D();
  7029. region.rect(bbox[0], bbox[1], width, height);
  7030. ctx.clip(region);
  7031. }
  7032. class BaseShadingPattern {
  7033. constructor() {
  7034. if (this.constructor === BaseShadingPattern) {
  7035. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  7036. }
  7037. }
  7038. getPattern() {
  7039. (0, _util.unreachable)("Abstract method `getPattern` called.");
  7040. }
  7041. }
  7042. class RadialAxialShadingPattern extends BaseShadingPattern {
  7043. constructor(IR) {
  7044. super();
  7045. this._type = IR[1];
  7046. this._bbox = IR[2];
  7047. this._colorStops = IR[3];
  7048. this._p0 = IR[4];
  7049. this._p1 = IR[5];
  7050. this._r0 = IR[6];
  7051. this._r1 = IR[7];
  7052. this.matrix = null;
  7053. }
  7054. _createGradient(ctx) {
  7055. let grad;
  7056. if (this._type === "axial") {
  7057. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  7058. } else if (this._type === "radial") {
  7059. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  7060. }
  7061. for (const colorStop of this._colorStops) {
  7062. grad.addColorStop(colorStop[0], colorStop[1]);
  7063. }
  7064. return grad;
  7065. }
  7066. getPattern(ctx, owner, inverse, pathType) {
  7067. let pattern;
  7068. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  7069. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
  7070. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  7071. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  7072. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  7073. const tmpCtx = tmpCanvas.context;
  7074. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7075. tmpCtx.beginPath();
  7076. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7077. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  7078. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  7079. tmpCtx.transform(...owner.baseTransform);
  7080. if (this.matrix) {
  7081. tmpCtx.transform(...this.matrix);
  7082. }
  7083. applyBoundingBox(tmpCtx, this._bbox);
  7084. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  7085. tmpCtx.fill();
  7086. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  7087. const domMatrix = new DOMMatrix(inverse);
  7088. pattern.setTransform(domMatrix);
  7089. } else {
  7090. applyBoundingBox(ctx, this._bbox);
  7091. pattern = this._createGradient(ctx);
  7092. }
  7093. return pattern;
  7094. }
  7095. }
  7096. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  7097. const coords = context.coords,
  7098. colors = context.colors;
  7099. const bytes = data.data,
  7100. rowSize = data.width * 4;
  7101. let tmp;
  7102. if (coords[p1 + 1] > coords[p2 + 1]) {
  7103. tmp = p1;
  7104. p1 = p2;
  7105. p2 = tmp;
  7106. tmp = c1;
  7107. c1 = c2;
  7108. c2 = tmp;
  7109. }
  7110. if (coords[p2 + 1] > coords[p3 + 1]) {
  7111. tmp = p2;
  7112. p2 = p3;
  7113. p3 = tmp;
  7114. tmp = c2;
  7115. c2 = c3;
  7116. c3 = tmp;
  7117. }
  7118. if (coords[p1 + 1] > coords[p2 + 1]) {
  7119. tmp = p1;
  7120. p1 = p2;
  7121. p2 = tmp;
  7122. tmp = c1;
  7123. c1 = c2;
  7124. c2 = tmp;
  7125. }
  7126. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  7127. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  7128. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  7129. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  7130. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  7131. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  7132. if (y1 >= y3) {
  7133. return;
  7134. }
  7135. const c1r = colors[c1],
  7136. c1g = colors[c1 + 1],
  7137. c1b = colors[c1 + 2];
  7138. const c2r = colors[c2],
  7139. c2g = colors[c2 + 1],
  7140. c2b = colors[c2 + 2];
  7141. const c3r = colors[c3],
  7142. c3g = colors[c3 + 1],
  7143. c3b = colors[c3 + 2];
  7144. const minY = Math.round(y1),
  7145. maxY = Math.round(y3);
  7146. let xa, car, cag, cab;
  7147. let xb, cbr, cbg, cbb;
  7148. for (let y = minY; y <= maxY; y++) {
  7149. if (y < y2) {
  7150. let k;
  7151. if (y < y1) {
  7152. k = 0;
  7153. } else {
  7154. k = (y1 - y) / (y1 - y2);
  7155. }
  7156. xa = x1 - (x1 - x2) * k;
  7157. car = c1r - (c1r - c2r) * k;
  7158. cag = c1g - (c1g - c2g) * k;
  7159. cab = c1b - (c1b - c2b) * k;
  7160. } else {
  7161. let k;
  7162. if (y > y3) {
  7163. k = 1;
  7164. } else if (y2 === y3) {
  7165. k = 0;
  7166. } else {
  7167. k = (y2 - y) / (y2 - y3);
  7168. }
  7169. xa = x2 - (x2 - x3) * k;
  7170. car = c2r - (c2r - c3r) * k;
  7171. cag = c2g - (c2g - c3g) * k;
  7172. cab = c2b - (c2b - c3b) * k;
  7173. }
  7174. let k;
  7175. if (y < y1) {
  7176. k = 0;
  7177. } else if (y > y3) {
  7178. k = 1;
  7179. } else {
  7180. k = (y1 - y) / (y1 - y3);
  7181. }
  7182. xb = x1 - (x1 - x3) * k;
  7183. cbr = c1r - (c1r - c3r) * k;
  7184. cbg = c1g - (c1g - c3g) * k;
  7185. cbb = c1b - (c1b - c3b) * k;
  7186. const x1_ = Math.round(Math.min(xa, xb));
  7187. const x2_ = Math.round(Math.max(xa, xb));
  7188. let j = rowSize * y + x1_ * 4;
  7189. for (let x = x1_; x <= x2_; x++) {
  7190. k = (xa - x) / (xa - xb);
  7191. if (k < 0) {
  7192. k = 0;
  7193. } else if (k > 1) {
  7194. k = 1;
  7195. }
  7196. bytes[j++] = car - (car - cbr) * k | 0;
  7197. bytes[j++] = cag - (cag - cbg) * k | 0;
  7198. bytes[j++] = cab - (cab - cbb) * k | 0;
  7199. bytes[j++] = 255;
  7200. }
  7201. }
  7202. }
  7203. function drawFigure(data, figure, context) {
  7204. const ps = figure.coords;
  7205. const cs = figure.colors;
  7206. let i, ii;
  7207. switch (figure.type) {
  7208. case "lattice":
  7209. const verticesPerRow = figure.verticesPerRow;
  7210. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  7211. const cols = verticesPerRow - 1;
  7212. for (i = 0; i < rows; i++) {
  7213. let q = i * verticesPerRow;
  7214. for (let j = 0; j < cols; j++, q++) {
  7215. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  7216. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  7217. }
  7218. }
  7219. break;
  7220. case "triangles":
  7221. for (i = 0, ii = ps.length; i < ii; i += 3) {
  7222. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  7223. }
  7224. break;
  7225. default:
  7226. throw new Error("illegal figure");
  7227. }
  7228. }
  7229. class MeshShadingPattern extends BaseShadingPattern {
  7230. constructor(IR) {
  7231. super();
  7232. this._coords = IR[2];
  7233. this._colors = IR[3];
  7234. this._figures = IR[4];
  7235. this._bounds = IR[5];
  7236. this._bbox = IR[7];
  7237. this._background = IR[8];
  7238. this.matrix = null;
  7239. }
  7240. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  7241. const EXPECTED_SCALE = 1.1;
  7242. const MAX_PATTERN_SIZE = 3000;
  7243. const BORDER_SIZE = 2;
  7244. const offsetX = Math.floor(this._bounds[0]);
  7245. const offsetY = Math.floor(this._bounds[1]);
  7246. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  7247. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  7248. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7249. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7250. const scaleX = boundsWidth / width;
  7251. const scaleY = boundsHeight / height;
  7252. const context = {
  7253. coords: this._coords,
  7254. colors: this._colors,
  7255. offsetX: -offsetX,
  7256. offsetY: -offsetY,
  7257. scaleX: 1 / scaleX,
  7258. scaleY: 1 / scaleY
  7259. };
  7260. const paddedWidth = width + BORDER_SIZE * 2;
  7261. const paddedHeight = height + BORDER_SIZE * 2;
  7262. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  7263. const tmpCtx = tmpCanvas.context;
  7264. const data = tmpCtx.createImageData(width, height);
  7265. if (backgroundColor) {
  7266. const bytes = data.data;
  7267. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  7268. bytes[i] = backgroundColor[0];
  7269. bytes[i + 1] = backgroundColor[1];
  7270. bytes[i + 2] = backgroundColor[2];
  7271. bytes[i + 3] = 255;
  7272. }
  7273. }
  7274. for (const figure of this._figures) {
  7275. drawFigure(data, figure, context);
  7276. }
  7277. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  7278. const canvas = tmpCanvas.canvas;
  7279. return {
  7280. canvas,
  7281. offsetX: offsetX - BORDER_SIZE * scaleX,
  7282. offsetY: offsetY - BORDER_SIZE * scaleY,
  7283. scaleX,
  7284. scaleY
  7285. };
  7286. }
  7287. getPattern(ctx, owner, inverse, pathType) {
  7288. applyBoundingBox(ctx, this._bbox);
  7289. let scale;
  7290. if (pathType === PathType.SHADING) {
  7291. scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
  7292. } else {
  7293. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  7294. if (this.matrix) {
  7295. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7296. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  7297. }
  7298. }
  7299. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  7300. if (pathType !== PathType.SHADING) {
  7301. ctx.setTransform(...owner.baseTransform);
  7302. if (this.matrix) {
  7303. ctx.transform(...this.matrix);
  7304. }
  7305. }
  7306. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7307. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  7308. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  7309. }
  7310. }
  7311. class DummyShadingPattern extends BaseShadingPattern {
  7312. getPattern() {
  7313. return "hotpink";
  7314. }
  7315. }
  7316. function getShadingPattern(IR) {
  7317. switch (IR[0]) {
  7318. case "RadialAxial":
  7319. return new RadialAxialShadingPattern(IR);
  7320. case "Mesh":
  7321. return new MeshShadingPattern(IR);
  7322. case "Dummy":
  7323. return new DummyShadingPattern();
  7324. }
  7325. throw new Error(`Unknown IR type: ${IR[0]}`);
  7326. }
  7327. const PaintType = {
  7328. COLORED: 1,
  7329. UNCOLORED: 2
  7330. };
  7331. class TilingPattern {
  7332. static get MAX_PATTERN_SIZE() {
  7333. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  7334. }
  7335. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  7336. this.operatorList = IR[2];
  7337. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  7338. this.bbox = IR[4];
  7339. this.xstep = IR[5];
  7340. this.ystep = IR[6];
  7341. this.paintType = IR[7];
  7342. this.tilingType = IR[8];
  7343. this.color = color;
  7344. this.ctx = ctx;
  7345. this.canvasGraphicsFactory = canvasGraphicsFactory;
  7346. this.baseTransform = baseTransform;
  7347. }
  7348. createPatternCanvas(owner) {
  7349. const operatorList = this.operatorList;
  7350. const bbox = this.bbox;
  7351. const xstep = this.xstep;
  7352. const ystep = this.ystep;
  7353. const paintType = this.paintType;
  7354. const tilingType = this.tilingType;
  7355. const color = this.color;
  7356. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  7357. (0, _util.info)("TilingType: " + tilingType);
  7358. const x0 = bbox[0],
  7359. y0 = bbox[1],
  7360. x1 = bbox[2],
  7361. y1 = bbox[3];
  7362. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7363. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  7364. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  7365. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  7366. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  7367. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  7368. const tmpCtx = tmpCanvas.context;
  7369. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  7370. graphics.groupLevel = owner.groupLevel;
  7371. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  7372. let adjustedX0 = x0;
  7373. let adjustedY0 = y0;
  7374. let adjustedX1 = x1;
  7375. let adjustedY1 = y1;
  7376. if (x0 < 0) {
  7377. adjustedX0 = 0;
  7378. adjustedX1 += Math.abs(x0);
  7379. }
  7380. if (y0 < 0) {
  7381. adjustedY0 = 0;
  7382. adjustedY1 += Math.abs(y0);
  7383. }
  7384. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  7385. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  7386. tmpCtx.save();
  7387. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  7388. graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
  7389. graphics.executeOperatorList(operatorList);
  7390. graphics.endDrawing();
  7391. return {
  7392. canvas: tmpCanvas.canvas,
  7393. scaleX: dimx.scale,
  7394. scaleY: dimy.scale,
  7395. offsetX: adjustedX0,
  7396. offsetY: adjustedY0
  7397. };
  7398. }
  7399. getSizeAndScale(step, realOutputSize, scale) {
  7400. step = Math.abs(step);
  7401. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  7402. let size = Math.ceil(step * scale);
  7403. if (size >= maxSize) {
  7404. size = maxSize;
  7405. } else {
  7406. scale = size / step;
  7407. }
  7408. return {
  7409. scale,
  7410. size
  7411. };
  7412. }
  7413. clipBbox(graphics, x0, y0, x1, y1) {
  7414. const bboxWidth = x1 - x0;
  7415. const bboxHeight = y1 - y0;
  7416. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  7417. graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
  7418. graphics.clip();
  7419. graphics.endPath();
  7420. }
  7421. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  7422. const context = graphics.ctx,
  7423. current = graphics.current;
  7424. switch (paintType) {
  7425. case PaintType.COLORED:
  7426. const ctx = this.ctx;
  7427. context.fillStyle = ctx.fillStyle;
  7428. context.strokeStyle = ctx.strokeStyle;
  7429. current.fillColor = ctx.fillStyle;
  7430. current.strokeColor = ctx.strokeStyle;
  7431. break;
  7432. case PaintType.UNCOLORED:
  7433. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  7434. context.fillStyle = cssColor;
  7435. context.strokeStyle = cssColor;
  7436. current.fillColor = cssColor;
  7437. current.strokeColor = cssColor;
  7438. break;
  7439. default:
  7440. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  7441. }
  7442. }
  7443. getPattern(ctx, owner, inverse, pathType) {
  7444. let matrix = inverse;
  7445. if (pathType !== PathType.SHADING) {
  7446. matrix = _util.Util.transform(matrix, owner.baseTransform);
  7447. if (this.matrix) {
  7448. matrix = _util.Util.transform(matrix, this.matrix);
  7449. }
  7450. }
  7451. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  7452. let domMatrix = new DOMMatrix(matrix);
  7453. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7454. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  7455. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  7456. pattern.setTransform(domMatrix);
  7457. return pattern;
  7458. }
  7459. }
  7460. exports.TilingPattern = TilingPattern;
  7461. /***/ }),
  7462. /* 12 */
  7463. /***/ ((__unused_webpack_module, exports) => {
  7464. Object.defineProperty(exports, "__esModule", ({
  7465. value: true
  7466. }));
  7467. exports.isNodeJS = void 0;
  7468. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  7469. exports.isNodeJS = isNodeJS;
  7470. /***/ }),
  7471. /* 13 */
  7472. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7473. Object.defineProperty(exports, "__esModule", ({
  7474. value: true
  7475. }));
  7476. exports.applyMaskImageData = applyMaskImageData;
  7477. var _util = __w_pdfjs_require__(1);
  7478. function applyMaskImageData({
  7479. src,
  7480. srcPos = 0,
  7481. dest,
  7482. destPos = 0,
  7483. width,
  7484. height,
  7485. inverseDecode = false
  7486. }) {
  7487. const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  7488. const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
  7489. const widthInSource = width >> 3;
  7490. const widthRemainder = width & 7;
  7491. const srcLength = src.length;
  7492. dest = new Uint32Array(dest.buffer);
  7493. for (let i = 0; i < height; i++) {
  7494. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  7495. const elem = srcPos < srcLength ? src[srcPos] : 255;
  7496. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  7497. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  7498. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  7499. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  7500. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  7501. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  7502. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  7503. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  7504. }
  7505. if (widthRemainder === 0) {
  7506. continue;
  7507. }
  7508. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  7509. for (let j = 0; j < widthRemainder; j++) {
  7510. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  7511. }
  7512. }
  7513. return {
  7514. srcPos,
  7515. destPos
  7516. };
  7517. }
  7518. /***/ }),
  7519. /* 14 */
  7520. /***/ ((__unused_webpack_module, exports) => {
  7521. Object.defineProperty(exports, "__esModule", ({
  7522. value: true
  7523. }));
  7524. exports.GlobalWorkerOptions = void 0;
  7525. const GlobalWorkerOptions = Object.create(null);
  7526. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  7527. GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
  7528. GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
  7529. /***/ }),
  7530. /* 15 */
  7531. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7532. Object.defineProperty(exports, "__esModule", ({
  7533. value: true
  7534. }));
  7535. exports.MessageHandler = void 0;
  7536. var _util = __w_pdfjs_require__(1);
  7537. const CallbackKind = {
  7538. UNKNOWN: 0,
  7539. DATA: 1,
  7540. ERROR: 2
  7541. };
  7542. const StreamKind = {
  7543. UNKNOWN: 0,
  7544. CANCEL: 1,
  7545. CANCEL_COMPLETE: 2,
  7546. CLOSE: 3,
  7547. ENQUEUE: 4,
  7548. ERROR: 5,
  7549. PULL: 6,
  7550. PULL_COMPLETE: 7,
  7551. START_COMPLETE: 8
  7552. };
  7553. function wrapReason(reason) {
  7554. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  7555. (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  7556. }
  7557. switch (reason.name) {
  7558. case "AbortException":
  7559. return new _util.AbortException(reason.message);
  7560. case "MissingPDFException":
  7561. return new _util.MissingPDFException(reason.message);
  7562. case "PasswordException":
  7563. return new _util.PasswordException(reason.message, reason.code);
  7564. case "UnexpectedResponseException":
  7565. return new _util.UnexpectedResponseException(reason.message, reason.status);
  7566. case "UnknownErrorException":
  7567. return new _util.UnknownErrorException(reason.message, reason.details);
  7568. default:
  7569. return new _util.UnknownErrorException(reason.message, reason.toString());
  7570. }
  7571. }
  7572. class MessageHandler {
  7573. constructor(sourceName, targetName, comObj) {
  7574. this.sourceName = sourceName;
  7575. this.targetName = targetName;
  7576. this.comObj = comObj;
  7577. this.callbackId = 1;
  7578. this.streamId = 1;
  7579. this.streamSinks = Object.create(null);
  7580. this.streamControllers = Object.create(null);
  7581. this.callbackCapabilities = Object.create(null);
  7582. this.actionHandler = Object.create(null);
  7583. this._onComObjOnMessage = event => {
  7584. const data = event.data;
  7585. if (data.targetName !== this.sourceName) {
  7586. return;
  7587. }
  7588. if (data.stream) {
  7589. this._processStreamMessage(data);
  7590. return;
  7591. }
  7592. if (data.callback) {
  7593. const callbackId = data.callbackId;
  7594. const capability = this.callbackCapabilities[callbackId];
  7595. if (!capability) {
  7596. throw new Error(`Cannot resolve callback ${callbackId}`);
  7597. }
  7598. delete this.callbackCapabilities[callbackId];
  7599. if (data.callback === CallbackKind.DATA) {
  7600. capability.resolve(data.data);
  7601. } else if (data.callback === CallbackKind.ERROR) {
  7602. capability.reject(wrapReason(data.reason));
  7603. } else {
  7604. throw new Error("Unexpected callback case");
  7605. }
  7606. return;
  7607. }
  7608. const action = this.actionHandler[data.action];
  7609. if (!action) {
  7610. throw new Error(`Unknown action from worker: ${data.action}`);
  7611. }
  7612. if (data.callbackId) {
  7613. const cbSourceName = this.sourceName;
  7614. const cbTargetName = data.sourceName;
  7615. new Promise(function (resolve) {
  7616. resolve(action(data.data));
  7617. }).then(function (result) {
  7618. comObj.postMessage({
  7619. sourceName: cbSourceName,
  7620. targetName: cbTargetName,
  7621. callback: CallbackKind.DATA,
  7622. callbackId: data.callbackId,
  7623. data: result
  7624. });
  7625. }, function (reason) {
  7626. comObj.postMessage({
  7627. sourceName: cbSourceName,
  7628. targetName: cbTargetName,
  7629. callback: CallbackKind.ERROR,
  7630. callbackId: data.callbackId,
  7631. reason: wrapReason(reason)
  7632. });
  7633. });
  7634. return;
  7635. }
  7636. if (data.streamId) {
  7637. this._createStreamSink(data);
  7638. return;
  7639. }
  7640. action(data.data);
  7641. };
  7642. comObj.addEventListener("message", this._onComObjOnMessage);
  7643. }
  7644. on(actionName, handler) {
  7645. const ah = this.actionHandler;
  7646. if (ah[actionName]) {
  7647. throw new Error(`There is already an actionName called "${actionName}"`);
  7648. }
  7649. ah[actionName] = handler;
  7650. }
  7651. send(actionName, data, transfers) {
  7652. this.comObj.postMessage({
  7653. sourceName: this.sourceName,
  7654. targetName: this.targetName,
  7655. action: actionName,
  7656. data
  7657. }, transfers);
  7658. }
  7659. sendWithPromise(actionName, data, transfers) {
  7660. const callbackId = this.callbackId++;
  7661. const capability = (0, _util.createPromiseCapability)();
  7662. this.callbackCapabilities[callbackId] = capability;
  7663. try {
  7664. this.comObj.postMessage({
  7665. sourceName: this.sourceName,
  7666. targetName: this.targetName,
  7667. action: actionName,
  7668. callbackId,
  7669. data
  7670. }, transfers);
  7671. } catch (ex) {
  7672. capability.reject(ex);
  7673. }
  7674. return capability.promise;
  7675. }
  7676. sendWithStream(actionName, data, queueingStrategy, transfers) {
  7677. const streamId = this.streamId++,
  7678. sourceName = this.sourceName,
  7679. targetName = this.targetName,
  7680. comObj = this.comObj;
  7681. return new ReadableStream({
  7682. start: controller => {
  7683. const startCapability = (0, _util.createPromiseCapability)();
  7684. this.streamControllers[streamId] = {
  7685. controller,
  7686. startCall: startCapability,
  7687. pullCall: null,
  7688. cancelCall: null,
  7689. isClosed: false
  7690. };
  7691. comObj.postMessage({
  7692. sourceName,
  7693. targetName,
  7694. action: actionName,
  7695. streamId,
  7696. data,
  7697. desiredSize: controller.desiredSize
  7698. }, transfers);
  7699. return startCapability.promise;
  7700. },
  7701. pull: controller => {
  7702. const pullCapability = (0, _util.createPromiseCapability)();
  7703. this.streamControllers[streamId].pullCall = pullCapability;
  7704. comObj.postMessage({
  7705. sourceName,
  7706. targetName,
  7707. stream: StreamKind.PULL,
  7708. streamId,
  7709. desiredSize: controller.desiredSize
  7710. });
  7711. return pullCapability.promise;
  7712. },
  7713. cancel: reason => {
  7714. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  7715. const cancelCapability = (0, _util.createPromiseCapability)();
  7716. this.streamControllers[streamId].cancelCall = cancelCapability;
  7717. this.streamControllers[streamId].isClosed = true;
  7718. comObj.postMessage({
  7719. sourceName,
  7720. targetName,
  7721. stream: StreamKind.CANCEL,
  7722. streamId,
  7723. reason: wrapReason(reason)
  7724. });
  7725. return cancelCapability.promise;
  7726. }
  7727. }, queueingStrategy);
  7728. }
  7729. _createStreamSink(data) {
  7730. const streamId = data.streamId,
  7731. sourceName = this.sourceName,
  7732. targetName = data.sourceName,
  7733. comObj = this.comObj;
  7734. const self = this,
  7735. action = this.actionHandler[data.action];
  7736. const streamSink = {
  7737. enqueue(chunk, size = 1, transfers) {
  7738. if (this.isCancelled) {
  7739. return;
  7740. }
  7741. const lastDesiredSize = this.desiredSize;
  7742. this.desiredSize -= size;
  7743. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  7744. this.sinkCapability = (0, _util.createPromiseCapability)();
  7745. this.ready = this.sinkCapability.promise;
  7746. }
  7747. comObj.postMessage({
  7748. sourceName,
  7749. targetName,
  7750. stream: StreamKind.ENQUEUE,
  7751. streamId,
  7752. chunk
  7753. }, transfers);
  7754. },
  7755. close() {
  7756. if (this.isCancelled) {
  7757. return;
  7758. }
  7759. this.isCancelled = true;
  7760. comObj.postMessage({
  7761. sourceName,
  7762. targetName,
  7763. stream: StreamKind.CLOSE,
  7764. streamId
  7765. });
  7766. delete self.streamSinks[streamId];
  7767. },
  7768. error(reason) {
  7769. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  7770. if (this.isCancelled) {
  7771. return;
  7772. }
  7773. this.isCancelled = true;
  7774. comObj.postMessage({
  7775. sourceName,
  7776. targetName,
  7777. stream: StreamKind.ERROR,
  7778. streamId,
  7779. reason: wrapReason(reason)
  7780. });
  7781. },
  7782. sinkCapability: (0, _util.createPromiseCapability)(),
  7783. onPull: null,
  7784. onCancel: null,
  7785. isCancelled: false,
  7786. desiredSize: data.desiredSize,
  7787. ready: null
  7788. };
  7789. streamSink.sinkCapability.resolve();
  7790. streamSink.ready = streamSink.sinkCapability.promise;
  7791. this.streamSinks[streamId] = streamSink;
  7792. new Promise(function (resolve) {
  7793. resolve(action(data.data, streamSink));
  7794. }).then(function () {
  7795. comObj.postMessage({
  7796. sourceName,
  7797. targetName,
  7798. stream: StreamKind.START_COMPLETE,
  7799. streamId,
  7800. success: true
  7801. });
  7802. }, function (reason) {
  7803. comObj.postMessage({
  7804. sourceName,
  7805. targetName,
  7806. stream: StreamKind.START_COMPLETE,
  7807. streamId,
  7808. reason: wrapReason(reason)
  7809. });
  7810. });
  7811. }
  7812. _processStreamMessage(data) {
  7813. const streamId = data.streamId,
  7814. sourceName = this.sourceName,
  7815. targetName = data.sourceName,
  7816. comObj = this.comObj;
  7817. const streamController = this.streamControllers[streamId],
  7818. streamSink = this.streamSinks[streamId];
  7819. switch (data.stream) {
  7820. case StreamKind.START_COMPLETE:
  7821. if (data.success) {
  7822. streamController.startCall.resolve();
  7823. } else {
  7824. streamController.startCall.reject(wrapReason(data.reason));
  7825. }
  7826. break;
  7827. case StreamKind.PULL_COMPLETE:
  7828. if (data.success) {
  7829. streamController.pullCall.resolve();
  7830. } else {
  7831. streamController.pullCall.reject(wrapReason(data.reason));
  7832. }
  7833. break;
  7834. case StreamKind.PULL:
  7835. if (!streamSink) {
  7836. comObj.postMessage({
  7837. sourceName,
  7838. targetName,
  7839. stream: StreamKind.PULL_COMPLETE,
  7840. streamId,
  7841. success: true
  7842. });
  7843. break;
  7844. }
  7845. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  7846. streamSink.sinkCapability.resolve();
  7847. }
  7848. streamSink.desiredSize = data.desiredSize;
  7849. new Promise(function (resolve) {
  7850. resolve(streamSink.onPull && streamSink.onPull());
  7851. }).then(function () {
  7852. comObj.postMessage({
  7853. sourceName,
  7854. targetName,
  7855. stream: StreamKind.PULL_COMPLETE,
  7856. streamId,
  7857. success: true
  7858. });
  7859. }, function (reason) {
  7860. comObj.postMessage({
  7861. sourceName,
  7862. targetName,
  7863. stream: StreamKind.PULL_COMPLETE,
  7864. streamId,
  7865. reason: wrapReason(reason)
  7866. });
  7867. });
  7868. break;
  7869. case StreamKind.ENQUEUE:
  7870. (0, _util.assert)(streamController, "enqueue should have stream controller");
  7871. if (streamController.isClosed) {
  7872. break;
  7873. }
  7874. streamController.controller.enqueue(data.chunk);
  7875. break;
  7876. case StreamKind.CLOSE:
  7877. (0, _util.assert)(streamController, "close should have stream controller");
  7878. if (streamController.isClosed) {
  7879. break;
  7880. }
  7881. streamController.isClosed = true;
  7882. streamController.controller.close();
  7883. this._deleteStreamController(streamController, streamId);
  7884. break;
  7885. case StreamKind.ERROR:
  7886. (0, _util.assert)(streamController, "error should have stream controller");
  7887. streamController.controller.error(wrapReason(data.reason));
  7888. this._deleteStreamController(streamController, streamId);
  7889. break;
  7890. case StreamKind.CANCEL_COMPLETE:
  7891. if (data.success) {
  7892. streamController.cancelCall.resolve();
  7893. } else {
  7894. streamController.cancelCall.reject(wrapReason(data.reason));
  7895. }
  7896. this._deleteStreamController(streamController, streamId);
  7897. break;
  7898. case StreamKind.CANCEL:
  7899. if (!streamSink) {
  7900. break;
  7901. }
  7902. new Promise(function (resolve) {
  7903. resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
  7904. }).then(function () {
  7905. comObj.postMessage({
  7906. sourceName,
  7907. targetName,
  7908. stream: StreamKind.CANCEL_COMPLETE,
  7909. streamId,
  7910. success: true
  7911. });
  7912. }, function (reason) {
  7913. comObj.postMessage({
  7914. sourceName,
  7915. targetName,
  7916. stream: StreamKind.CANCEL_COMPLETE,
  7917. streamId,
  7918. reason: wrapReason(reason)
  7919. });
  7920. });
  7921. streamSink.sinkCapability.reject(wrapReason(data.reason));
  7922. streamSink.isCancelled = true;
  7923. delete this.streamSinks[streamId];
  7924. break;
  7925. default:
  7926. throw new Error("Unexpected stream case");
  7927. }
  7928. }
  7929. async _deleteStreamController(streamController, streamId) {
  7930. await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
  7931. delete this.streamControllers[streamId];
  7932. }
  7933. destroy() {
  7934. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  7935. }
  7936. }
  7937. exports.MessageHandler = MessageHandler;
  7938. /***/ }),
  7939. /* 16 */
  7940. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7941. Object.defineProperty(exports, "__esModule", ({
  7942. value: true
  7943. }));
  7944. exports.Metadata = void 0;
  7945. var _util = __w_pdfjs_require__(1);
  7946. class Metadata {
  7947. #metadataMap;
  7948. #data;
  7949. constructor({
  7950. parsedData,
  7951. rawData
  7952. }) {
  7953. this.#metadataMap = parsedData;
  7954. this.#data = rawData;
  7955. }
  7956. getRaw() {
  7957. return this.#data;
  7958. }
  7959. get(name) {
  7960. return this.#metadataMap.get(name) ?? null;
  7961. }
  7962. getAll() {
  7963. return (0, _util.objectFromMap)(this.#metadataMap);
  7964. }
  7965. has(name) {
  7966. return this.#metadataMap.has(name);
  7967. }
  7968. }
  7969. exports.Metadata = Metadata;
  7970. /***/ }),
  7971. /* 17 */
  7972. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7973. Object.defineProperty(exports, "__esModule", ({
  7974. value: true
  7975. }));
  7976. exports.OptionalContentConfig = void 0;
  7977. var _util = __w_pdfjs_require__(1);
  7978. var _murmurhash = __w_pdfjs_require__(8);
  7979. const INTERNAL = Symbol("INTERNAL");
  7980. class OptionalContentGroup {
  7981. #visible = true;
  7982. constructor(name, intent) {
  7983. this.name = name;
  7984. this.intent = intent;
  7985. }
  7986. get visible() {
  7987. return this.#visible;
  7988. }
  7989. _setVisible(internal, visible) {
  7990. if (internal !== INTERNAL) {
  7991. (0, _util.unreachable)("Internal method `_setVisible` called.");
  7992. }
  7993. this.#visible = visible;
  7994. }
  7995. }
  7996. class OptionalContentConfig {
  7997. #cachedGetHash = null;
  7998. #groups = new Map();
  7999. #initialHash = null;
  8000. #order = null;
  8001. constructor(data) {
  8002. this.name = null;
  8003. this.creator = null;
  8004. if (data === null) {
  8005. return;
  8006. }
  8007. this.name = data.name;
  8008. this.creator = data.creator;
  8009. this.#order = data.order;
  8010. for (const group of data.groups) {
  8011. this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  8012. }
  8013. if (data.baseState === "OFF") {
  8014. for (const group of this.#groups.values()) {
  8015. group._setVisible(INTERNAL, false);
  8016. }
  8017. }
  8018. for (const on of data.on) {
  8019. this.#groups.get(on)._setVisible(INTERNAL, true);
  8020. }
  8021. for (const off of data.off) {
  8022. this.#groups.get(off)._setVisible(INTERNAL, false);
  8023. }
  8024. this.#initialHash = this.getHash();
  8025. }
  8026. #evaluateVisibilityExpression(array) {
  8027. const length = array.length;
  8028. if (length < 2) {
  8029. return true;
  8030. }
  8031. const operator = array[0];
  8032. for (let i = 1; i < length; i++) {
  8033. const element = array[i];
  8034. let state;
  8035. if (Array.isArray(element)) {
  8036. state = this.#evaluateVisibilityExpression(element);
  8037. } else if (this.#groups.has(element)) {
  8038. state = this.#groups.get(element).visible;
  8039. } else {
  8040. (0, _util.warn)(`Optional content group not found: ${element}`);
  8041. return true;
  8042. }
  8043. switch (operator) {
  8044. case "And":
  8045. if (!state) {
  8046. return false;
  8047. }
  8048. break;
  8049. case "Or":
  8050. if (state) {
  8051. return true;
  8052. }
  8053. break;
  8054. case "Not":
  8055. return !state;
  8056. default:
  8057. return true;
  8058. }
  8059. }
  8060. return operator === "And";
  8061. }
  8062. isVisible(group) {
  8063. if (this.#groups.size === 0) {
  8064. return true;
  8065. }
  8066. if (!group) {
  8067. (0, _util.warn)("Optional content group not defined.");
  8068. return true;
  8069. }
  8070. if (group.type === "OCG") {
  8071. if (!this.#groups.has(group.id)) {
  8072. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  8073. return true;
  8074. }
  8075. return this.#groups.get(group.id).visible;
  8076. } else if (group.type === "OCMD") {
  8077. if (group.expression) {
  8078. return this.#evaluateVisibilityExpression(group.expression);
  8079. }
  8080. if (!group.policy || group.policy === "AnyOn") {
  8081. for (const id of group.ids) {
  8082. if (!this.#groups.has(id)) {
  8083. (0, _util.warn)(`Optional content group not found: ${id}`);
  8084. return true;
  8085. }
  8086. if (this.#groups.get(id).visible) {
  8087. return true;
  8088. }
  8089. }
  8090. return false;
  8091. } else if (group.policy === "AllOn") {
  8092. for (const id of group.ids) {
  8093. if (!this.#groups.has(id)) {
  8094. (0, _util.warn)(`Optional content group not found: ${id}`);
  8095. return true;
  8096. }
  8097. if (!this.#groups.get(id).visible) {
  8098. return false;
  8099. }
  8100. }
  8101. return true;
  8102. } else if (group.policy === "AnyOff") {
  8103. for (const id of group.ids) {
  8104. if (!this.#groups.has(id)) {
  8105. (0, _util.warn)(`Optional content group not found: ${id}`);
  8106. return true;
  8107. }
  8108. if (!this.#groups.get(id).visible) {
  8109. return true;
  8110. }
  8111. }
  8112. return false;
  8113. } else if (group.policy === "AllOff") {
  8114. for (const id of group.ids) {
  8115. if (!this.#groups.has(id)) {
  8116. (0, _util.warn)(`Optional content group not found: ${id}`);
  8117. return true;
  8118. }
  8119. if (this.#groups.get(id).visible) {
  8120. return false;
  8121. }
  8122. }
  8123. return true;
  8124. }
  8125. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  8126. return true;
  8127. }
  8128. (0, _util.warn)(`Unknown group type ${group.type}.`);
  8129. return true;
  8130. }
  8131. setVisibility(id, visible = true) {
  8132. if (!this.#groups.has(id)) {
  8133. (0, _util.warn)(`Optional content group not found: ${id}`);
  8134. return;
  8135. }
  8136. this.#groups.get(id)._setVisible(INTERNAL, !!visible);
  8137. this.#cachedGetHash = null;
  8138. }
  8139. get hasInitialVisibility() {
  8140. return this.getHash() === this.#initialHash;
  8141. }
  8142. getOrder() {
  8143. if (!this.#groups.size) {
  8144. return null;
  8145. }
  8146. if (this.#order) {
  8147. return this.#order.slice();
  8148. }
  8149. return [...this.#groups.keys()];
  8150. }
  8151. getGroups() {
  8152. return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
  8153. }
  8154. getGroup(id) {
  8155. return this.#groups.get(id) || null;
  8156. }
  8157. getHash() {
  8158. if (this.#cachedGetHash !== null) {
  8159. return this.#cachedGetHash;
  8160. }
  8161. const hash = new _murmurhash.MurmurHash3_64();
  8162. for (const [id, group] of this.#groups) {
  8163. hash.update(`${id}:${group.visible}`);
  8164. }
  8165. return this.#cachedGetHash = hash.hexdigest();
  8166. }
  8167. }
  8168. exports.OptionalContentConfig = OptionalContentConfig;
  8169. /***/ }),
  8170. /* 18 */
  8171. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8172. Object.defineProperty(exports, "__esModule", ({
  8173. value: true
  8174. }));
  8175. exports.PDFDataTransportStream = void 0;
  8176. var _util = __w_pdfjs_require__(1);
  8177. var _display_utils = __w_pdfjs_require__(6);
  8178. class PDFDataTransportStream {
  8179. constructor(params, pdfDataRangeTransport) {
  8180. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  8181. this._queuedChunks = [];
  8182. this._progressiveDone = params.progressiveDone || false;
  8183. this._contentDispositionFilename = params.contentDispositionFilename || null;
  8184. const initialData = params.initialData;
  8185. if (initialData?.length > 0) {
  8186. const buffer = new Uint8Array(initialData).buffer;
  8187. this._queuedChunks.push(buffer);
  8188. }
  8189. this._pdfDataRangeTransport = pdfDataRangeTransport;
  8190. this._isStreamingSupported = !params.disableStream;
  8191. this._isRangeSupported = !params.disableRange;
  8192. this._contentLength = params.length;
  8193. this._fullRequestReader = null;
  8194. this._rangeReaders = [];
  8195. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  8196. this._onReceiveData({
  8197. begin,
  8198. chunk
  8199. });
  8200. });
  8201. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  8202. this._onProgress({
  8203. loaded,
  8204. total
  8205. });
  8206. });
  8207. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  8208. this._onReceiveData({
  8209. chunk
  8210. });
  8211. });
  8212. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  8213. this._onProgressiveDone();
  8214. });
  8215. this._pdfDataRangeTransport.transportReady();
  8216. }
  8217. _onReceiveData(args) {
  8218. const buffer = new Uint8Array(args.chunk).buffer;
  8219. if (args.begin === undefined) {
  8220. if (this._fullRequestReader) {
  8221. this._fullRequestReader._enqueue(buffer);
  8222. } else {
  8223. this._queuedChunks.push(buffer);
  8224. }
  8225. } else {
  8226. const found = this._rangeReaders.some(function (rangeReader) {
  8227. if (rangeReader._begin !== args.begin) {
  8228. return false;
  8229. }
  8230. rangeReader._enqueue(buffer);
  8231. return true;
  8232. });
  8233. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  8234. }
  8235. }
  8236. get _progressiveDataLength() {
  8237. return this._fullRequestReader?._loaded ?? 0;
  8238. }
  8239. _onProgress(evt) {
  8240. if (evt.total === undefined) {
  8241. this._rangeReaders[0]?.onProgress?.({
  8242. loaded: evt.loaded
  8243. });
  8244. } else {
  8245. this._fullRequestReader?.onProgress?.({
  8246. loaded: evt.loaded,
  8247. total: evt.total
  8248. });
  8249. }
  8250. }
  8251. _onProgressiveDone() {
  8252. this._fullRequestReader?.progressiveDone();
  8253. this._progressiveDone = true;
  8254. }
  8255. _removeRangeReader(reader) {
  8256. const i = this._rangeReaders.indexOf(reader);
  8257. if (i >= 0) {
  8258. this._rangeReaders.splice(i, 1);
  8259. }
  8260. }
  8261. getFullReader() {
  8262. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  8263. const queuedChunks = this._queuedChunks;
  8264. this._queuedChunks = null;
  8265. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  8266. }
  8267. getRangeReader(begin, end) {
  8268. if (end <= this._progressiveDataLength) {
  8269. return null;
  8270. }
  8271. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  8272. this._pdfDataRangeTransport.requestDataRange(begin, end);
  8273. this._rangeReaders.push(reader);
  8274. return reader;
  8275. }
  8276. cancelAllRequests(reason) {
  8277. this._fullRequestReader?.cancel(reason);
  8278. for (const reader of this._rangeReaders.slice(0)) {
  8279. reader.cancel(reason);
  8280. }
  8281. this._pdfDataRangeTransport.abort();
  8282. }
  8283. }
  8284. exports.PDFDataTransportStream = PDFDataTransportStream;
  8285. class PDFDataTransportStreamReader {
  8286. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  8287. this._stream = stream;
  8288. this._done = progressiveDone || false;
  8289. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  8290. this._queuedChunks = queuedChunks || [];
  8291. this._loaded = 0;
  8292. for (const chunk of this._queuedChunks) {
  8293. this._loaded += chunk.byteLength;
  8294. }
  8295. this._requests = [];
  8296. this._headersReady = Promise.resolve();
  8297. stream._fullRequestReader = this;
  8298. this.onProgress = null;
  8299. }
  8300. _enqueue(chunk) {
  8301. if (this._done) {
  8302. return;
  8303. }
  8304. if (this._requests.length > 0) {
  8305. const requestCapability = this._requests.shift();
  8306. requestCapability.resolve({
  8307. value: chunk,
  8308. done: false
  8309. });
  8310. } else {
  8311. this._queuedChunks.push(chunk);
  8312. }
  8313. this._loaded += chunk.byteLength;
  8314. }
  8315. get headersReady() {
  8316. return this._headersReady;
  8317. }
  8318. get filename() {
  8319. return this._filename;
  8320. }
  8321. get isRangeSupported() {
  8322. return this._stream._isRangeSupported;
  8323. }
  8324. get isStreamingSupported() {
  8325. return this._stream._isStreamingSupported;
  8326. }
  8327. get contentLength() {
  8328. return this._stream._contentLength;
  8329. }
  8330. async read() {
  8331. if (this._queuedChunks.length > 0) {
  8332. const chunk = this._queuedChunks.shift();
  8333. return {
  8334. value: chunk,
  8335. done: false
  8336. };
  8337. }
  8338. if (this._done) {
  8339. return {
  8340. value: undefined,
  8341. done: true
  8342. };
  8343. }
  8344. const requestCapability = (0, _util.createPromiseCapability)();
  8345. this._requests.push(requestCapability);
  8346. return requestCapability.promise;
  8347. }
  8348. cancel(reason) {
  8349. this._done = true;
  8350. for (const requestCapability of this._requests) {
  8351. requestCapability.resolve({
  8352. value: undefined,
  8353. done: true
  8354. });
  8355. }
  8356. this._requests.length = 0;
  8357. }
  8358. progressiveDone() {
  8359. if (this._done) {
  8360. return;
  8361. }
  8362. this._done = true;
  8363. }
  8364. }
  8365. class PDFDataTransportStreamRangeReader {
  8366. constructor(stream, begin, end) {
  8367. this._stream = stream;
  8368. this._begin = begin;
  8369. this._end = end;
  8370. this._queuedChunk = null;
  8371. this._requests = [];
  8372. this._done = false;
  8373. this.onProgress = null;
  8374. }
  8375. _enqueue(chunk) {
  8376. if (this._done) {
  8377. return;
  8378. }
  8379. if (this._requests.length === 0) {
  8380. this._queuedChunk = chunk;
  8381. } else {
  8382. const requestsCapability = this._requests.shift();
  8383. requestsCapability.resolve({
  8384. value: chunk,
  8385. done: false
  8386. });
  8387. for (const requestCapability of this._requests) {
  8388. requestCapability.resolve({
  8389. value: undefined,
  8390. done: true
  8391. });
  8392. }
  8393. this._requests.length = 0;
  8394. }
  8395. this._done = true;
  8396. this._stream._removeRangeReader(this);
  8397. }
  8398. get isStreamingSupported() {
  8399. return false;
  8400. }
  8401. async read() {
  8402. if (this._queuedChunk) {
  8403. const chunk = this._queuedChunk;
  8404. this._queuedChunk = null;
  8405. return {
  8406. value: chunk,
  8407. done: false
  8408. };
  8409. }
  8410. if (this._done) {
  8411. return {
  8412. value: undefined,
  8413. done: true
  8414. };
  8415. }
  8416. const requestCapability = (0, _util.createPromiseCapability)();
  8417. this._requests.push(requestCapability);
  8418. return requestCapability.promise;
  8419. }
  8420. cancel(reason) {
  8421. this._done = true;
  8422. for (const requestCapability of this._requests) {
  8423. requestCapability.resolve({
  8424. value: undefined,
  8425. done: true
  8426. });
  8427. }
  8428. this._requests.length = 0;
  8429. this._stream._removeRangeReader(this);
  8430. }
  8431. }
  8432. /***/ }),
  8433. /* 19 */
  8434. /***/ ((__unused_webpack_module, exports) => {
  8435. Object.defineProperty(exports, "__esModule", ({
  8436. value: true
  8437. }));
  8438. exports.XfaText = void 0;
  8439. class XfaText {
  8440. static textContent(xfa) {
  8441. const items = [];
  8442. const output = {
  8443. items,
  8444. styles: Object.create(null)
  8445. };
  8446. function walk(node) {
  8447. if (!node) {
  8448. return;
  8449. }
  8450. let str = null;
  8451. const name = node.name;
  8452. if (name === "#text") {
  8453. str = node.value;
  8454. } else if (!XfaText.shouldBuildText(name)) {
  8455. return;
  8456. } else if (node?.attributes?.textContent) {
  8457. str = node.attributes.textContent;
  8458. } else if (node.value) {
  8459. str = node.value;
  8460. }
  8461. if (str !== null) {
  8462. items.push({
  8463. str
  8464. });
  8465. }
  8466. if (!node.children) {
  8467. return;
  8468. }
  8469. for (const child of node.children) {
  8470. walk(child);
  8471. }
  8472. }
  8473. walk(xfa);
  8474. return output;
  8475. }
  8476. static shouldBuildText(name) {
  8477. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  8478. }
  8479. }
  8480. exports.XfaText = XfaText;
  8481. /***/ }),
  8482. /* 20 */
  8483. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8484. Object.defineProperty(exports, "__esModule", ({
  8485. value: true
  8486. }));
  8487. exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
  8488. var _base_factory = __w_pdfjs_require__(7);
  8489. ;
  8490. const fetchData = function (url) {
  8491. return new Promise((resolve, reject) => {
  8492. const fs = require("fs");
  8493. fs.readFile(url, (error, data) => {
  8494. if (error || !data) {
  8495. reject(new Error(error));
  8496. return;
  8497. }
  8498. resolve(new Uint8Array(data));
  8499. });
  8500. });
  8501. };
  8502. class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
  8503. _createCanvas(width, height) {
  8504. const Canvas = require("canvas");
  8505. return Canvas.createCanvas(width, height);
  8506. }
  8507. }
  8508. exports.NodeCanvasFactory = NodeCanvasFactory;
  8509. class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  8510. _fetchData(url, compressionType) {
  8511. return fetchData(url).then(data => {
  8512. return {
  8513. cMapData: data,
  8514. compressionType
  8515. };
  8516. });
  8517. }
  8518. }
  8519. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  8520. class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  8521. _fetchData(url) {
  8522. return fetchData(url);
  8523. }
  8524. }
  8525. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  8526. /***/ }),
  8527. /* 21 */
  8528. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8529. Object.defineProperty(exports, "__esModule", ({
  8530. value: true
  8531. }));
  8532. exports.AnnotationEditorLayer = void 0;
  8533. var _tools = __w_pdfjs_require__(5);
  8534. var _util = __w_pdfjs_require__(1);
  8535. var _freetext = __w_pdfjs_require__(22);
  8536. var _ink = __w_pdfjs_require__(23);
  8537. class AnnotationEditorLayer {
  8538. #accessibilityManager;
  8539. #allowClick = false;
  8540. #boundPointerup = this.pointerup.bind(this);
  8541. #boundPointerdown = this.pointerdown.bind(this);
  8542. #editors = new Map();
  8543. #hadPointerDown = false;
  8544. #isCleaningUp = false;
  8545. #uiManager;
  8546. static _initialized = false;
  8547. constructor(options) {
  8548. if (!AnnotationEditorLayer._initialized) {
  8549. AnnotationEditorLayer._initialized = true;
  8550. _freetext.FreeTextEditor.initialize(options.l10n);
  8551. _ink.InkEditor.initialize(options.l10n);
  8552. }
  8553. options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
  8554. this.#uiManager = options.uiManager;
  8555. this.annotationStorage = options.annotationStorage;
  8556. this.pageIndex = options.pageIndex;
  8557. this.div = options.div;
  8558. this.#accessibilityManager = options.accessibilityManager;
  8559. this.#uiManager.addLayer(this);
  8560. }
  8561. updateToolbar(mode) {
  8562. this.#uiManager.updateToolbar(mode);
  8563. }
  8564. updateMode(mode = this.#uiManager.getMode()) {
  8565. this.#cleanup();
  8566. if (mode === _util.AnnotationEditorType.INK) {
  8567. this.addInkEditorIfNeeded(false);
  8568. this.disableClick();
  8569. } else {
  8570. this.enableClick();
  8571. }
  8572. this.#uiManager.unselectAll();
  8573. this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
  8574. this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
  8575. }
  8576. addInkEditorIfNeeded(isCommitting) {
  8577. if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
  8578. return;
  8579. }
  8580. if (!isCommitting) {
  8581. for (const editor of this.#editors.values()) {
  8582. if (editor.isEmpty()) {
  8583. editor.setInBackground();
  8584. return;
  8585. }
  8586. }
  8587. }
  8588. const editor = this.#createAndAddNewEditor({
  8589. offsetX: 0,
  8590. offsetY: 0
  8591. });
  8592. editor.setInBackground();
  8593. }
  8594. setEditingState(isEditing) {
  8595. this.#uiManager.setEditingState(isEditing);
  8596. }
  8597. addCommands(params) {
  8598. this.#uiManager.addCommands(params);
  8599. }
  8600. enable() {
  8601. this.div.style.pointerEvents = "auto";
  8602. for (const editor of this.#editors.values()) {
  8603. editor.enableEditing();
  8604. }
  8605. }
  8606. disable() {
  8607. this.div.style.pointerEvents = "none";
  8608. for (const editor of this.#editors.values()) {
  8609. editor.disableEditing();
  8610. }
  8611. }
  8612. setActiveEditor(editor) {
  8613. const currentActive = this.#uiManager.getActive();
  8614. if (currentActive === editor) {
  8615. return;
  8616. }
  8617. this.#uiManager.setActiveEditor(editor);
  8618. }
  8619. enableClick() {
  8620. this.div.addEventListener("pointerdown", this.#boundPointerdown);
  8621. this.div.addEventListener("pointerup", this.#boundPointerup);
  8622. }
  8623. disableClick() {
  8624. this.div.removeEventListener("pointerdown", this.#boundPointerdown);
  8625. this.div.removeEventListener("pointerup", this.#boundPointerup);
  8626. }
  8627. attach(editor) {
  8628. this.#editors.set(editor.id, editor);
  8629. }
  8630. detach(editor) {
  8631. this.#editors.delete(editor.id);
  8632. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  8633. }
  8634. remove(editor) {
  8635. this.#uiManager.removeEditor(editor);
  8636. this.detach(editor);
  8637. this.annotationStorage.remove(editor.id);
  8638. editor.div.style.display = "none";
  8639. setTimeout(() => {
  8640. editor.div.style.display = "";
  8641. editor.div.remove();
  8642. editor.isAttachedToDOM = false;
  8643. if (document.activeElement === document.body) {
  8644. this.#uiManager.focusMainContainer();
  8645. }
  8646. }, 0);
  8647. if (!this.#isCleaningUp) {
  8648. this.addInkEditorIfNeeded(false);
  8649. }
  8650. }
  8651. #changeParent(editor) {
  8652. if (editor.parent === this) {
  8653. return;
  8654. }
  8655. this.attach(editor);
  8656. editor.pageIndex = this.pageIndex;
  8657. editor.parent?.detach(editor);
  8658. editor.parent = this;
  8659. if (editor.div && editor.isAttachedToDOM) {
  8660. editor.div.remove();
  8661. this.div.append(editor.div);
  8662. }
  8663. }
  8664. add(editor) {
  8665. this.#changeParent(editor);
  8666. this.#uiManager.addEditor(editor);
  8667. this.attach(editor);
  8668. if (!editor.isAttachedToDOM) {
  8669. const div = editor.render();
  8670. this.div.append(div);
  8671. editor.isAttachedToDOM = true;
  8672. }
  8673. this.moveEditorInDOM(editor);
  8674. editor.onceAdded();
  8675. this.addToAnnotationStorage(editor);
  8676. }
  8677. moveEditorInDOM(editor) {
  8678. this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  8679. }
  8680. addToAnnotationStorage(editor) {
  8681. if (!editor.isEmpty() && !this.annotationStorage.has(editor.id)) {
  8682. this.annotationStorage.setValue(editor.id, editor);
  8683. }
  8684. }
  8685. addOrRebuild(editor) {
  8686. if (editor.needsToBeRebuilt()) {
  8687. editor.rebuild();
  8688. } else {
  8689. this.add(editor);
  8690. }
  8691. }
  8692. addANewEditor(editor) {
  8693. const cmd = () => {
  8694. this.addOrRebuild(editor);
  8695. };
  8696. const undo = () => {
  8697. editor.remove();
  8698. };
  8699. this.addCommands({
  8700. cmd,
  8701. undo,
  8702. mustExec: true
  8703. });
  8704. }
  8705. addUndoableEditor(editor) {
  8706. const cmd = () => {
  8707. this.addOrRebuild(editor);
  8708. };
  8709. const undo = () => {
  8710. editor.remove();
  8711. };
  8712. this.addCommands({
  8713. cmd,
  8714. undo,
  8715. mustExec: false
  8716. });
  8717. }
  8718. getNextId() {
  8719. return this.#uiManager.getId();
  8720. }
  8721. #createNewEditor(params) {
  8722. switch (this.#uiManager.getMode()) {
  8723. case _util.AnnotationEditorType.FREETEXT:
  8724. return new _freetext.FreeTextEditor(params);
  8725. case _util.AnnotationEditorType.INK:
  8726. return new _ink.InkEditor(params);
  8727. }
  8728. return null;
  8729. }
  8730. deserialize(data) {
  8731. switch (data.annotationType) {
  8732. case _util.AnnotationEditorType.FREETEXT:
  8733. return _freetext.FreeTextEditor.deserialize(data, this);
  8734. case _util.AnnotationEditorType.INK:
  8735. return _ink.InkEditor.deserialize(data, this);
  8736. }
  8737. return null;
  8738. }
  8739. #createAndAddNewEditor(event) {
  8740. const id = this.getNextId();
  8741. const editor = this.#createNewEditor({
  8742. parent: this,
  8743. id,
  8744. x: event.offsetX,
  8745. y: event.offsetY
  8746. });
  8747. if (editor) {
  8748. this.add(editor);
  8749. }
  8750. return editor;
  8751. }
  8752. setSelected(editor) {
  8753. this.#uiManager.setSelected(editor);
  8754. }
  8755. toggleSelected(editor) {
  8756. this.#uiManager.toggleSelected(editor);
  8757. }
  8758. isSelected(editor) {
  8759. return this.#uiManager.isSelected(editor);
  8760. }
  8761. unselect(editor) {
  8762. this.#uiManager.unselect(editor);
  8763. }
  8764. pointerup(event) {
  8765. const isMac = _tools.KeyboardManager.platform.isMac;
  8766. if (event.button !== 0 || event.ctrlKey && isMac) {
  8767. return;
  8768. }
  8769. if (event.target !== this.div) {
  8770. return;
  8771. }
  8772. if (!this.#hadPointerDown) {
  8773. return;
  8774. }
  8775. this.#hadPointerDown = false;
  8776. if (!this.#allowClick) {
  8777. this.#allowClick = true;
  8778. return;
  8779. }
  8780. this.#createAndAddNewEditor(event);
  8781. }
  8782. pointerdown(event) {
  8783. const isMac = _tools.KeyboardManager.platform.isMac;
  8784. if (event.button !== 0 || event.ctrlKey && isMac) {
  8785. return;
  8786. }
  8787. if (event.target !== this.div) {
  8788. return;
  8789. }
  8790. this.#hadPointerDown = true;
  8791. const editor = this.#uiManager.getActive();
  8792. this.#allowClick = !editor || editor.isEmpty();
  8793. }
  8794. drop(event) {
  8795. const id = event.dataTransfer.getData("text/plain");
  8796. const editor = this.#uiManager.getEditor(id);
  8797. if (!editor) {
  8798. return;
  8799. }
  8800. event.preventDefault();
  8801. event.dataTransfer.dropEffect = "move";
  8802. this.#changeParent(editor);
  8803. const rect = this.div.getBoundingClientRect();
  8804. const endX = event.clientX - rect.x;
  8805. const endY = event.clientY - rect.y;
  8806. editor.translate(endX - editor.startX, endY - editor.startY);
  8807. this.moveEditorInDOM(editor);
  8808. editor.div.focus();
  8809. }
  8810. dragover(event) {
  8811. event.preventDefault();
  8812. }
  8813. destroy() {
  8814. if (this.#uiManager.getActive()?.parent === this) {
  8815. this.#uiManager.setActiveEditor(null);
  8816. }
  8817. for (const editor of this.#editors.values()) {
  8818. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  8819. editor.isAttachedToDOM = false;
  8820. editor.div.remove();
  8821. editor.parent = null;
  8822. }
  8823. this.div = null;
  8824. this.#editors.clear();
  8825. this.#uiManager.removeLayer(this);
  8826. }
  8827. #cleanup() {
  8828. this.#isCleaningUp = true;
  8829. for (const editor of this.#editors.values()) {
  8830. if (editor.isEmpty()) {
  8831. editor.remove();
  8832. }
  8833. }
  8834. this.#isCleaningUp = false;
  8835. }
  8836. render(parameters) {
  8837. this.viewport = parameters.viewport;
  8838. (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
  8839. this.setDimensions();
  8840. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  8841. this.add(editor);
  8842. }
  8843. this.updateMode();
  8844. }
  8845. update(parameters) {
  8846. this.#uiManager.commitOrRemove();
  8847. this.viewport = parameters.viewport;
  8848. this.setDimensions();
  8849. this.updateMode();
  8850. }
  8851. get scaleFactor() {
  8852. return this.viewport.scale;
  8853. }
  8854. get pageDimensions() {
  8855. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  8856. const width = pageURx - pageLLx;
  8857. const height = pageURy - pageLLy;
  8858. return [width, height];
  8859. }
  8860. get viewportBaseDimensions() {
  8861. const {
  8862. width,
  8863. height,
  8864. rotation
  8865. } = this.viewport;
  8866. return rotation % 180 === 0 ? [width, height] : [height, width];
  8867. }
  8868. setDimensions() {
  8869. const {
  8870. width,
  8871. height,
  8872. rotation
  8873. } = this.viewport;
  8874. const flipOrientation = rotation % 180 !== 0,
  8875. widthStr = Math.floor(width) + "px",
  8876. heightStr = Math.floor(height) + "px";
  8877. this.div.style.width = flipOrientation ? heightStr : widthStr;
  8878. this.div.style.height = flipOrientation ? widthStr : heightStr;
  8879. this.div.setAttribute("data-main-rotation", rotation);
  8880. }
  8881. }
  8882. exports.AnnotationEditorLayer = AnnotationEditorLayer;
  8883. /***/ }),
  8884. /* 22 */
  8885. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8886. Object.defineProperty(exports, "__esModule", ({
  8887. value: true
  8888. }));
  8889. exports.FreeTextEditor = void 0;
  8890. var _util = __w_pdfjs_require__(1);
  8891. var _tools = __w_pdfjs_require__(5);
  8892. var _editor = __w_pdfjs_require__(4);
  8893. class FreeTextEditor extends _editor.AnnotationEditor {
  8894. #boundEditorDivBlur = this.editorDivBlur.bind(this);
  8895. #boundEditorDivFocus = this.editorDivFocus.bind(this);
  8896. #boundEditorDivInput = this.editorDivInput.bind(this);
  8897. #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
  8898. #color;
  8899. #content = "";
  8900. #editorDivId = `${this.id}-editor`;
  8901. #hasAlreadyBeenCommitted = false;
  8902. #fontSize;
  8903. static _freeTextDefaultContent = "";
  8904. static _l10nPromise;
  8905. static _internalPadding = 0;
  8906. static _defaultColor = null;
  8907. static _defaultFontSize = 10;
  8908. static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
  8909. static _type = "freetext";
  8910. constructor(params) {
  8911. super({
  8912. ...params,
  8913. name: "freeTextEditor"
  8914. });
  8915. this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  8916. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  8917. }
  8918. static initialize(l10n) {
  8919. this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
  8920. const style = getComputedStyle(document.documentElement);
  8921. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  8922. }
  8923. static updateDefaultParams(type, value) {
  8924. switch (type) {
  8925. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  8926. FreeTextEditor._defaultFontSize = value;
  8927. break;
  8928. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  8929. FreeTextEditor._defaultColor = value;
  8930. break;
  8931. }
  8932. }
  8933. updateParams(type, value) {
  8934. switch (type) {
  8935. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  8936. this.#updateFontSize(value);
  8937. break;
  8938. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  8939. this.#updateColor(value);
  8940. break;
  8941. }
  8942. }
  8943. static get defaultPropertiesToUpdate() {
  8944. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
  8945. }
  8946. get propertiesToUpdate() {
  8947. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  8948. }
  8949. #updateFontSize(fontSize) {
  8950. const setFontsize = size => {
  8951. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  8952. this.translate(0, -(size - this.#fontSize) * this.parent.scaleFactor);
  8953. this.#fontSize = size;
  8954. this.#setEditorDimensions();
  8955. };
  8956. const savedFontsize = this.#fontSize;
  8957. this.parent.addCommands({
  8958. cmd: () => {
  8959. setFontsize(fontSize);
  8960. },
  8961. undo: () => {
  8962. setFontsize(savedFontsize);
  8963. },
  8964. mustExec: true,
  8965. type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
  8966. overwriteIfSameType: true,
  8967. keepUndo: true
  8968. });
  8969. }
  8970. #updateColor(color) {
  8971. const savedColor = this.#color;
  8972. this.parent.addCommands({
  8973. cmd: () => {
  8974. this.#color = color;
  8975. this.editorDiv.style.color = color;
  8976. },
  8977. undo: () => {
  8978. this.#color = savedColor;
  8979. this.editorDiv.style.color = savedColor;
  8980. },
  8981. mustExec: true,
  8982. type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
  8983. overwriteIfSameType: true,
  8984. keepUndo: true
  8985. });
  8986. }
  8987. getInitialTranslation() {
  8988. return [-FreeTextEditor._internalPadding * this.parent.scaleFactor, -(FreeTextEditor._internalPadding + this.#fontSize) * this.parent.scaleFactor];
  8989. }
  8990. rebuild() {
  8991. super.rebuild();
  8992. if (this.div === null) {
  8993. return;
  8994. }
  8995. if (!this.isAttachedToDOM) {
  8996. this.parent.add(this);
  8997. }
  8998. }
  8999. enableEditMode() {
  9000. if (this.isInEditMode()) {
  9001. return;
  9002. }
  9003. this.parent.setEditingState(false);
  9004. this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
  9005. super.enableEditMode();
  9006. this.overlayDiv.classList.remove("enabled");
  9007. this.editorDiv.contentEditable = true;
  9008. this.div.draggable = false;
  9009. this.div.removeAttribute("aria-activedescendant");
  9010. this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
  9011. this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
  9012. this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
  9013. this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
  9014. }
  9015. disableEditMode() {
  9016. if (!this.isInEditMode()) {
  9017. return;
  9018. }
  9019. this.parent.setEditingState(true);
  9020. super.disableEditMode();
  9021. this.overlayDiv.classList.add("enabled");
  9022. this.editorDiv.contentEditable = false;
  9023. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  9024. this.div.draggable = true;
  9025. this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
  9026. this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
  9027. this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
  9028. this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
  9029. this.div.focus();
  9030. this.isEditing = false;
  9031. this.parent.div.classList.add("freeTextEditing");
  9032. }
  9033. focusin(event) {
  9034. super.focusin(event);
  9035. if (event.target !== this.editorDiv) {
  9036. this.editorDiv.focus();
  9037. }
  9038. }
  9039. onceAdded() {
  9040. if (this.width) {
  9041. return;
  9042. }
  9043. this.enableEditMode();
  9044. this.editorDiv.focus();
  9045. }
  9046. isEmpty() {
  9047. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  9048. }
  9049. remove() {
  9050. this.isEditing = false;
  9051. this.parent.setEditingState(true);
  9052. this.parent.div.classList.add("freeTextEditing");
  9053. super.remove();
  9054. }
  9055. #extractText() {
  9056. const divs = this.editorDiv.getElementsByTagName("div");
  9057. if (divs.length === 0) {
  9058. return this.editorDiv.innerText;
  9059. }
  9060. const buffer = [];
  9061. for (const div of divs) {
  9062. buffer.push(div.innerText.replace(/\r\n?|\n/, ""));
  9063. }
  9064. return buffer.join("\n");
  9065. }
  9066. #setEditorDimensions() {
  9067. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9068. const rect = this.div.getBoundingClientRect();
  9069. this.width = rect.width / parentWidth;
  9070. this.height = rect.height / parentHeight;
  9071. }
  9072. commit() {
  9073. super.commit();
  9074. if (!this.#hasAlreadyBeenCommitted) {
  9075. this.#hasAlreadyBeenCommitted = true;
  9076. this.parent.addUndoableEditor(this);
  9077. }
  9078. this.disableEditMode();
  9079. this.#content = this.#extractText().trimEnd();
  9080. this.#setEditorDimensions();
  9081. }
  9082. shouldGetKeyboardEvents() {
  9083. return this.isInEditMode();
  9084. }
  9085. dblclick(event) {
  9086. this.enableEditMode();
  9087. this.editorDiv.focus();
  9088. }
  9089. keydown(event) {
  9090. if (event.target === this.div && event.key === "Enter") {
  9091. this.enableEditMode();
  9092. this.editorDiv.focus();
  9093. }
  9094. }
  9095. editorDivKeydown(event) {
  9096. FreeTextEditor._keyboardManager.exec(this, event);
  9097. }
  9098. editorDivFocus(event) {
  9099. this.isEditing = true;
  9100. }
  9101. editorDivBlur(event) {
  9102. this.isEditing = false;
  9103. }
  9104. editorDivInput(event) {
  9105. this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
  9106. }
  9107. disableEditing() {
  9108. this.editorDiv.setAttribute("role", "comment");
  9109. this.editorDiv.removeAttribute("aria-multiline");
  9110. }
  9111. enableEditing() {
  9112. this.editorDiv.setAttribute("role", "textbox");
  9113. this.editorDiv.setAttribute("aria-multiline", true);
  9114. }
  9115. render() {
  9116. if (this.div) {
  9117. return this.div;
  9118. }
  9119. let baseX, baseY;
  9120. if (this.width) {
  9121. baseX = this.x;
  9122. baseY = this.y;
  9123. }
  9124. super.render();
  9125. this.editorDiv = document.createElement("div");
  9126. this.editorDiv.className = "internal";
  9127. this.editorDiv.setAttribute("id", this.#editorDivId);
  9128. this.enableEditing();
  9129. FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
  9130. FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
  9131. this.editorDiv.contentEditable = true;
  9132. const {
  9133. style
  9134. } = this.editorDiv;
  9135. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  9136. style.color = this.#color;
  9137. this.div.append(this.editorDiv);
  9138. this.overlayDiv = document.createElement("div");
  9139. this.overlayDiv.classList.add("overlay", "enabled");
  9140. this.div.append(this.overlayDiv);
  9141. (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
  9142. if (this.width) {
  9143. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9144. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  9145. for (const line of this.#content.split("\n")) {
  9146. const div = document.createElement("div");
  9147. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  9148. this.editorDiv.append(div);
  9149. }
  9150. this.div.draggable = true;
  9151. this.editorDiv.contentEditable = false;
  9152. } else {
  9153. this.div.draggable = false;
  9154. this.editorDiv.contentEditable = true;
  9155. }
  9156. return this.div;
  9157. }
  9158. get contentDiv() {
  9159. return this.editorDiv;
  9160. }
  9161. static deserialize(data, parent) {
  9162. const editor = super.deserialize(data, parent);
  9163. editor.#fontSize = data.fontSize;
  9164. editor.#color = _util.Util.makeHexColor(...data.color);
  9165. editor.#content = data.value;
  9166. return editor;
  9167. }
  9168. serialize() {
  9169. if (this.isEmpty()) {
  9170. return null;
  9171. }
  9172. const padding = FreeTextEditor._internalPadding * this.parent.scaleFactor;
  9173. const rect = this.getRect(padding, padding);
  9174. const color = _editor.AnnotationEditor._colorManager.convert(getComputedStyle(this.editorDiv).color);
  9175. return {
  9176. annotationType: _util.AnnotationEditorType.FREETEXT,
  9177. color,
  9178. fontSize: this.#fontSize,
  9179. value: this.#content,
  9180. pageIndex: this.parent.pageIndex,
  9181. rect,
  9182. rotation: this.rotation
  9183. };
  9184. }
  9185. }
  9186. exports.FreeTextEditor = FreeTextEditor;
  9187. /***/ }),
  9188. /* 23 */
  9189. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9190. Object.defineProperty(exports, "__esModule", ({
  9191. value: true
  9192. }));
  9193. exports.InkEditor = void 0;
  9194. Object.defineProperty(exports, "fitCurve", ({
  9195. enumerable: true,
  9196. get: function () {
  9197. return _pdfjsFitCurve.fitCurve;
  9198. }
  9199. }));
  9200. var _util = __w_pdfjs_require__(1);
  9201. var _editor = __w_pdfjs_require__(4);
  9202. var _pdfjsFitCurve = __w_pdfjs_require__(24);
  9203. var _tools = __w_pdfjs_require__(5);
  9204. const RESIZER_SIZE = 16;
  9205. const TIME_TO_WAIT_BEFORE_FIXING_DIMS = 100;
  9206. class InkEditor extends _editor.AnnotationEditor {
  9207. #aspectRatio = 0;
  9208. #baseHeight = 0;
  9209. #baseWidth = 0;
  9210. #boundCanvasPointermove = this.canvasPointermove.bind(this);
  9211. #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
  9212. #boundCanvasPointerup = this.canvasPointerup.bind(this);
  9213. #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
  9214. #disableEditing = false;
  9215. #isCanvasInitialized = false;
  9216. #lastPoint = null;
  9217. #observer = null;
  9218. #realWidth = 0;
  9219. #realHeight = 0;
  9220. #requestFrameCallback = null;
  9221. static _defaultColor = null;
  9222. static _defaultOpacity = 1;
  9223. static _defaultThickness = 1;
  9224. static _l10nPromise;
  9225. static _type = "ink";
  9226. constructor(params) {
  9227. super({
  9228. ...params,
  9229. name: "inkEditor"
  9230. });
  9231. this.color = params.color || null;
  9232. this.thickness = params.thickness || null;
  9233. this.opacity = params.opacity || null;
  9234. this.paths = [];
  9235. this.bezierPath2D = [];
  9236. this.currentPath = [];
  9237. this.scaleFactor = 1;
  9238. this.translationX = this.translationY = 0;
  9239. this.x = 0;
  9240. this.y = 0;
  9241. }
  9242. static initialize(l10n) {
  9243. this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
  9244. }
  9245. static updateDefaultParams(type, value) {
  9246. switch (type) {
  9247. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9248. InkEditor._defaultThickness = value;
  9249. break;
  9250. case _util.AnnotationEditorParamsType.INK_COLOR:
  9251. InkEditor._defaultColor = value;
  9252. break;
  9253. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9254. InkEditor._defaultOpacity = value / 100;
  9255. break;
  9256. }
  9257. }
  9258. updateParams(type, value) {
  9259. switch (type) {
  9260. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9261. this.#updateThickness(value);
  9262. break;
  9263. case _util.AnnotationEditorParamsType.INK_COLOR:
  9264. this.#updateColor(value);
  9265. break;
  9266. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9267. this.#updateOpacity(value);
  9268. break;
  9269. }
  9270. }
  9271. static get defaultPropertiesToUpdate() {
  9272. 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)]];
  9273. }
  9274. get propertiesToUpdate() {
  9275. 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))]];
  9276. }
  9277. #updateThickness(thickness) {
  9278. const savedThickness = this.thickness;
  9279. this.parent.addCommands({
  9280. cmd: () => {
  9281. this.thickness = thickness;
  9282. this.#fitToContent();
  9283. },
  9284. undo: () => {
  9285. this.thickness = savedThickness;
  9286. this.#fitToContent();
  9287. },
  9288. mustExec: true,
  9289. type: _util.AnnotationEditorParamsType.INK_THICKNESS,
  9290. overwriteIfSameType: true,
  9291. keepUndo: true
  9292. });
  9293. }
  9294. #updateColor(color) {
  9295. const savedColor = this.color;
  9296. this.parent.addCommands({
  9297. cmd: () => {
  9298. this.color = color;
  9299. this.#redraw();
  9300. },
  9301. undo: () => {
  9302. this.color = savedColor;
  9303. this.#redraw();
  9304. },
  9305. mustExec: true,
  9306. type: _util.AnnotationEditorParamsType.INK_COLOR,
  9307. overwriteIfSameType: true,
  9308. keepUndo: true
  9309. });
  9310. }
  9311. #updateOpacity(opacity) {
  9312. opacity /= 100;
  9313. const savedOpacity = this.opacity;
  9314. this.parent.addCommands({
  9315. cmd: () => {
  9316. this.opacity = opacity;
  9317. this.#redraw();
  9318. },
  9319. undo: () => {
  9320. this.opacity = savedOpacity;
  9321. this.#redraw();
  9322. },
  9323. mustExec: true,
  9324. type: _util.AnnotationEditorParamsType.INK_OPACITY,
  9325. overwriteIfSameType: true,
  9326. keepUndo: true
  9327. });
  9328. }
  9329. rebuild() {
  9330. super.rebuild();
  9331. if (this.div === null) {
  9332. return;
  9333. }
  9334. if (!this.canvas) {
  9335. this.#createCanvas();
  9336. this.#createObserver();
  9337. }
  9338. if (!this.isAttachedToDOM) {
  9339. this.parent.add(this);
  9340. this.#setCanvasDims();
  9341. }
  9342. this.#fitToContent();
  9343. }
  9344. remove() {
  9345. if (this.canvas === null) {
  9346. return;
  9347. }
  9348. if (!this.isEmpty()) {
  9349. this.commit();
  9350. }
  9351. this.canvas.width = this.canvas.height = 0;
  9352. this.canvas.remove();
  9353. this.canvas = null;
  9354. this.#observer.disconnect();
  9355. this.#observer = null;
  9356. super.remove();
  9357. }
  9358. enableEditMode() {
  9359. if (this.#disableEditing || this.canvas === null) {
  9360. return;
  9361. }
  9362. super.enableEditMode();
  9363. this.div.draggable = false;
  9364. this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
  9365. this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
  9366. }
  9367. disableEditMode() {
  9368. if (!this.isInEditMode() || this.canvas === null) {
  9369. return;
  9370. }
  9371. super.disableEditMode();
  9372. this.div.draggable = !this.isEmpty();
  9373. this.div.classList.remove("editing");
  9374. this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
  9375. this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
  9376. }
  9377. onceAdded() {
  9378. this.div.draggable = !this.isEmpty();
  9379. }
  9380. isEmpty() {
  9381. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  9382. }
  9383. #getInitialBBox() {
  9384. const {
  9385. width,
  9386. height,
  9387. rotation
  9388. } = this.parent.viewport;
  9389. switch (rotation) {
  9390. case 90:
  9391. return [0, width, width, height];
  9392. case 180:
  9393. return [width, height, width, height];
  9394. case 270:
  9395. return [height, 0, width, height];
  9396. default:
  9397. return [0, 0, width, height];
  9398. }
  9399. }
  9400. #setStroke() {
  9401. this.ctx.lineWidth = this.thickness * this.parent.scaleFactor / this.scaleFactor;
  9402. this.ctx.lineCap = "round";
  9403. this.ctx.lineJoin = "round";
  9404. this.ctx.miterLimit = 10;
  9405. this.ctx.strokeStyle = `${this.color}${(0, _tools.opacityToHex)(this.opacity)}`;
  9406. }
  9407. #startDrawing(x, y) {
  9408. this.isEditing = true;
  9409. if (!this.#isCanvasInitialized) {
  9410. this.#isCanvasInitialized = true;
  9411. this.#setCanvasDims();
  9412. this.thickness ||= InkEditor._defaultThickness;
  9413. this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  9414. this.opacity ??= InkEditor._defaultOpacity;
  9415. }
  9416. this.currentPath.push([x, y]);
  9417. this.#lastPoint = null;
  9418. this.#setStroke();
  9419. this.ctx.beginPath();
  9420. this.ctx.moveTo(x, y);
  9421. this.#requestFrameCallback = () => {
  9422. if (!this.#requestFrameCallback) {
  9423. return;
  9424. }
  9425. if (this.#lastPoint) {
  9426. if (this.isEmpty()) {
  9427. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  9428. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  9429. } else {
  9430. this.#redraw();
  9431. }
  9432. this.ctx.lineTo(...this.#lastPoint);
  9433. this.#lastPoint = null;
  9434. this.ctx.stroke();
  9435. }
  9436. window.requestAnimationFrame(this.#requestFrameCallback);
  9437. };
  9438. window.requestAnimationFrame(this.#requestFrameCallback);
  9439. }
  9440. #draw(x, y) {
  9441. const [lastX, lastY] = this.currentPath.at(-1);
  9442. if (x === lastX && y === lastY) {
  9443. return;
  9444. }
  9445. this.currentPath.push([x, y]);
  9446. this.#lastPoint = [x, y];
  9447. }
  9448. #stopDrawing(x, y) {
  9449. this.ctx.closePath();
  9450. this.#requestFrameCallback = null;
  9451. x = Math.min(Math.max(x, 0), this.canvas.width);
  9452. y = Math.min(Math.max(y, 0), this.canvas.height);
  9453. const [lastX, lastY] = this.currentPath.at(-1);
  9454. if (x !== lastX || y !== lastY) {
  9455. this.currentPath.push([x, y]);
  9456. }
  9457. let bezier;
  9458. if (this.currentPath.length !== 1) {
  9459. bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
  9460. } else {
  9461. const xy = [x, y];
  9462. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  9463. }
  9464. const path2D = InkEditor.#buildPath2D(bezier);
  9465. this.currentPath.length = 0;
  9466. const cmd = () => {
  9467. this.paths.push(bezier);
  9468. this.bezierPath2D.push(path2D);
  9469. this.rebuild();
  9470. };
  9471. const undo = () => {
  9472. this.paths.pop();
  9473. this.bezierPath2D.pop();
  9474. if (this.paths.length === 0) {
  9475. this.remove();
  9476. } else {
  9477. if (!this.canvas) {
  9478. this.#createCanvas();
  9479. this.#createObserver();
  9480. }
  9481. this.#fitToContent();
  9482. }
  9483. };
  9484. this.parent.addCommands({
  9485. cmd,
  9486. undo,
  9487. mustExec: true
  9488. });
  9489. }
  9490. #redraw() {
  9491. if (this.isEmpty()) {
  9492. this.#updateTransform();
  9493. return;
  9494. }
  9495. this.#setStroke();
  9496. const {
  9497. canvas,
  9498. ctx
  9499. } = this;
  9500. ctx.setTransform(1, 0, 0, 1, 0, 0);
  9501. ctx.clearRect(0, 0, canvas.width, canvas.height);
  9502. this.#updateTransform();
  9503. for (const path of this.bezierPath2D) {
  9504. ctx.stroke(path);
  9505. }
  9506. }
  9507. commit() {
  9508. if (this.#disableEditing) {
  9509. return;
  9510. }
  9511. super.commit();
  9512. this.isEditing = false;
  9513. this.disableEditMode();
  9514. this.setInForeground();
  9515. this.#disableEditing = true;
  9516. this.div.classList.add("disabled");
  9517. this.#fitToContent(true);
  9518. this.parent.addInkEditorIfNeeded(true);
  9519. this.parent.moveEditorInDOM(this);
  9520. this.div.focus();
  9521. }
  9522. focusin(event) {
  9523. super.focusin(event);
  9524. this.enableEditMode();
  9525. }
  9526. canvasPointerdown(event) {
  9527. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  9528. return;
  9529. }
  9530. this.setInForeground();
  9531. if (event.type !== "mouse") {
  9532. this.div.focus();
  9533. }
  9534. event.stopPropagation();
  9535. this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
  9536. this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
  9537. this.#startDrawing(event.offsetX, event.offsetY);
  9538. }
  9539. canvasPointermove(event) {
  9540. event.stopPropagation();
  9541. this.#draw(event.offsetX, event.offsetY);
  9542. }
  9543. canvasPointerup(event) {
  9544. if (event.button !== 0) {
  9545. return;
  9546. }
  9547. if (this.isInEditMode() && this.currentPath.length !== 0) {
  9548. event.stopPropagation();
  9549. this.#endDrawing(event);
  9550. this.setInBackground();
  9551. }
  9552. }
  9553. canvasPointerleave(event) {
  9554. this.#endDrawing(event);
  9555. this.setInBackground();
  9556. }
  9557. #endDrawing(event) {
  9558. this.#stopDrawing(event.offsetX, event.offsetY);
  9559. this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
  9560. this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
  9561. this.parent.addToAnnotationStorage(this);
  9562. }
  9563. #createCanvas() {
  9564. this.canvas = document.createElement("canvas");
  9565. this.canvas.width = this.canvas.height = 0;
  9566. this.canvas.className = "inkEditorCanvas";
  9567. InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
  9568. this.div.append(this.canvas);
  9569. this.ctx = this.canvas.getContext("2d");
  9570. }
  9571. #createObserver() {
  9572. let timeoutId = null;
  9573. this.#observer = new ResizeObserver(entries => {
  9574. const rect = entries[0].contentRect;
  9575. if (rect.width && rect.height) {
  9576. if (timeoutId !== null) {
  9577. clearTimeout(timeoutId);
  9578. }
  9579. timeoutId = setTimeout(() => {
  9580. this.fixDims();
  9581. timeoutId = null;
  9582. }, TIME_TO_WAIT_BEFORE_FIXING_DIMS);
  9583. this.setDimensions(rect.width, rect.height);
  9584. }
  9585. });
  9586. this.#observer.observe(this.div);
  9587. }
  9588. render() {
  9589. if (this.div) {
  9590. return this.div;
  9591. }
  9592. let baseX, baseY;
  9593. if (this.width) {
  9594. baseX = this.x;
  9595. baseY = this.y;
  9596. }
  9597. super.render();
  9598. InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
  9599. const [x, y, w, h] = this.#getInitialBBox();
  9600. this.setAt(x, y, 0, 0);
  9601. this.setDims(w, h);
  9602. this.#createCanvas();
  9603. if (this.width) {
  9604. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9605. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  9606. this.#isCanvasInitialized = true;
  9607. this.#setCanvasDims();
  9608. this.setDims(this.width * parentWidth, this.height * parentHeight);
  9609. this.#redraw();
  9610. this.#setMinDims();
  9611. this.div.classList.add("disabled");
  9612. } else {
  9613. this.div.classList.add("editing");
  9614. this.enableEditMode();
  9615. }
  9616. this.#createObserver();
  9617. return this.div;
  9618. }
  9619. #setCanvasDims() {
  9620. if (!this.#isCanvasInitialized) {
  9621. return;
  9622. }
  9623. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9624. this.canvas.width = Math.ceil(this.width * parentWidth);
  9625. this.canvas.height = Math.ceil(this.height * parentHeight);
  9626. this.#updateTransform();
  9627. }
  9628. setDimensions(width, height) {
  9629. const roundedWidth = Math.round(width);
  9630. const roundedHeight = Math.round(height);
  9631. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  9632. return;
  9633. }
  9634. this.#realWidth = roundedWidth;
  9635. this.#realHeight = roundedHeight;
  9636. this.canvas.style.visibility = "hidden";
  9637. if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
  9638. height = Math.ceil(width / this.#aspectRatio);
  9639. this.setDims(width, height);
  9640. }
  9641. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9642. this.width = width / parentWidth;
  9643. this.height = height / parentHeight;
  9644. if (this.#disableEditing) {
  9645. this.#setScaleFactor(width, height);
  9646. }
  9647. this.#setCanvasDims();
  9648. this.#redraw();
  9649. this.canvas.style.visibility = "visible";
  9650. }
  9651. #setScaleFactor(width, height) {
  9652. const padding = this.#getPadding();
  9653. const scaleFactorW = (width - padding) / this.#baseWidth;
  9654. const scaleFactorH = (height - padding) / this.#baseHeight;
  9655. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  9656. }
  9657. #updateTransform() {
  9658. const padding = this.#getPadding() / 2;
  9659. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  9660. }
  9661. static #buildPath2D(bezier) {
  9662. const path2D = new Path2D();
  9663. for (let i = 0, ii = bezier.length; i < ii; i++) {
  9664. const [first, control1, control2, second] = bezier[i];
  9665. if (i === 0) {
  9666. path2D.moveTo(...first);
  9667. }
  9668. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  9669. }
  9670. return path2D;
  9671. }
  9672. #serializePaths(s, tx, ty, h) {
  9673. const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
  9674. const paths = [];
  9675. const padding = this.thickness / 2;
  9676. let buffer, points;
  9677. for (const bezier of this.paths) {
  9678. buffer = [];
  9679. points = [];
  9680. for (let i = 0, ii = bezier.length; i < ii; i++) {
  9681. const [first, control1, control2, second] = bezier[i];
  9682. const p10 = s * (first[0] + tx) + padding;
  9683. const p11 = h - s * (first[1] + ty) - padding;
  9684. const p20 = s * (control1[0] + tx) + padding;
  9685. const p21 = h - s * (control1[1] + ty) - padding;
  9686. const p30 = s * (control2[0] + tx) + padding;
  9687. const p31 = h - s * (control2[1] + ty) - padding;
  9688. const p40 = s * (second[0] + tx) + padding;
  9689. const p41 = h - s * (second[1] + ty) - padding;
  9690. if (i === 0) {
  9691. buffer.push(p10, p11);
  9692. points.push(p10, p11);
  9693. }
  9694. buffer.push(p20, p21, p30, p31, p40, p41);
  9695. this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
  9696. }
  9697. paths.push({
  9698. bezier: buffer,
  9699. points
  9700. });
  9701. }
  9702. return paths;
  9703. }
  9704. #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
  9705. if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
  9706. points.push(p40, p41);
  9707. return;
  9708. }
  9709. for (let i = 1; i < n - 1; i++) {
  9710. const t = i / n;
  9711. const mt = 1 - t;
  9712. let q10 = t * p10 + mt * p20;
  9713. let q11 = t * p11 + mt * p21;
  9714. let q20 = t * p20 + mt * p30;
  9715. let q21 = t * p21 + mt * p31;
  9716. const q30 = t * p30 + mt * p40;
  9717. const q31 = t * p31 + mt * p41;
  9718. q10 = t * q10 + mt * q20;
  9719. q11 = t * q11 + mt * q21;
  9720. q20 = t * q20 + mt * q30;
  9721. q21 = t * q21 + mt * q31;
  9722. q10 = t * q10 + mt * q20;
  9723. q11 = t * q11 + mt * q21;
  9724. points.push(q10, q11);
  9725. }
  9726. points.push(p40, p41);
  9727. }
  9728. #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
  9729. const tol = 10;
  9730. const ax = (3 * p20 - 2 * p10 - p40) ** 2;
  9731. const ay = (3 * p21 - 2 * p11 - p41) ** 2;
  9732. const bx = (3 * p30 - p10 - 2 * p40) ** 2;
  9733. const by = (3 * p31 - p11 - 2 * p41) ** 2;
  9734. return Math.max(ax, bx) + Math.max(ay, by) <= tol;
  9735. }
  9736. #getBbox() {
  9737. let xMin = Infinity;
  9738. let xMax = -Infinity;
  9739. let yMin = Infinity;
  9740. let yMax = -Infinity;
  9741. for (const path of this.paths) {
  9742. for (const [first, control1, control2, second] of path) {
  9743. const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  9744. xMin = Math.min(xMin, bbox[0]);
  9745. yMin = Math.min(yMin, bbox[1]);
  9746. xMax = Math.max(xMax, bbox[2]);
  9747. yMax = Math.max(yMax, bbox[3]);
  9748. }
  9749. }
  9750. return [xMin, yMin, xMax, yMax];
  9751. }
  9752. #getPadding() {
  9753. return this.#disableEditing ? Math.ceil(this.thickness * this.parent.scaleFactor) : 0;
  9754. }
  9755. #fitToContent(firstTime = false) {
  9756. if (this.isEmpty()) {
  9757. return;
  9758. }
  9759. if (!this.#disableEditing) {
  9760. this.#redraw();
  9761. return;
  9762. }
  9763. const bbox = this.#getBbox();
  9764. const padding = this.#getPadding();
  9765. this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  9766. this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  9767. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  9768. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  9769. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9770. this.width = width / parentWidth;
  9771. this.height = height / parentHeight;
  9772. this.#aspectRatio = width / height;
  9773. this.#setMinDims();
  9774. const prevTranslationX = this.translationX;
  9775. const prevTranslationY = this.translationY;
  9776. this.translationX = -bbox[0];
  9777. this.translationY = -bbox[1];
  9778. this.#setCanvasDims();
  9779. this.#redraw();
  9780. this.#realWidth = width;
  9781. this.#realHeight = height;
  9782. this.setDims(width, height);
  9783. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  9784. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  9785. }
  9786. #setMinDims() {
  9787. const {
  9788. style
  9789. } = this.div;
  9790. if (this.#aspectRatio >= 1) {
  9791. style.minHeight = `${RESIZER_SIZE}px`;
  9792. style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
  9793. } else {
  9794. style.minWidth = `${RESIZER_SIZE}px`;
  9795. style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
  9796. }
  9797. }
  9798. static deserialize(data, parent) {
  9799. const editor = super.deserialize(data, parent);
  9800. editor.thickness = data.thickness;
  9801. editor.color = _util.Util.makeHexColor(...data.color);
  9802. editor.opacity = data.opacity;
  9803. const [pageWidth, pageHeight] = parent.pageDimensions;
  9804. const width = editor.width * pageWidth;
  9805. const height = editor.height * pageHeight;
  9806. const scaleFactor = parent.scaleFactor;
  9807. const padding = data.thickness / 2;
  9808. editor.#aspectRatio = width / height;
  9809. editor.#disableEditing = true;
  9810. editor.#realWidth = Math.round(width);
  9811. editor.#realHeight = Math.round(height);
  9812. for (const {
  9813. bezier
  9814. } of data.paths) {
  9815. const path = [];
  9816. editor.paths.push(path);
  9817. let p0 = scaleFactor * (bezier[0] - padding);
  9818. let p1 = scaleFactor * (height - bezier[1] - padding);
  9819. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  9820. const p10 = scaleFactor * (bezier[i] - padding);
  9821. const p11 = scaleFactor * (height - bezier[i + 1] - padding);
  9822. const p20 = scaleFactor * (bezier[i + 2] - padding);
  9823. const p21 = scaleFactor * (height - bezier[i + 3] - padding);
  9824. const p30 = scaleFactor * (bezier[i + 4] - padding);
  9825. const p31 = scaleFactor * (height - bezier[i + 5] - padding);
  9826. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  9827. p0 = p30;
  9828. p1 = p31;
  9829. }
  9830. const path2D = this.#buildPath2D(path);
  9831. editor.bezierPath2D.push(path2D);
  9832. }
  9833. const bbox = editor.#getBbox();
  9834. editor.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  9835. editor.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  9836. editor.#setScaleFactor(width, height);
  9837. return editor;
  9838. }
  9839. serialize() {
  9840. if (this.isEmpty()) {
  9841. return null;
  9842. }
  9843. const rect = this.getRect(0, 0);
  9844. const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
  9845. const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  9846. return {
  9847. annotationType: _util.AnnotationEditorType.INK,
  9848. color,
  9849. thickness: this.thickness,
  9850. opacity: this.opacity,
  9851. paths: this.#serializePaths(this.scaleFactor / this.parent.scaleFactor, this.translationX, this.translationY, height),
  9852. pageIndex: this.parent.pageIndex,
  9853. rect,
  9854. rotation: this.rotation
  9855. };
  9856. }
  9857. }
  9858. exports.InkEditor = InkEditor;
  9859. /***/ }),
  9860. /* 24 */
  9861. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9862. Object.defineProperty(exports, "__esModule", ({
  9863. value: true
  9864. }));
  9865. exports.fitCurve = void 0;
  9866. const fitCurve = __w_pdfjs_require__(25);
  9867. exports.fitCurve = fitCurve;
  9868. /***/ }),
  9869. /* 25 */
  9870. /***/ ((module) => {
  9871. function fitCurve(points, maxError, progressCallback) {
  9872. if (!Array.isArray(points)) {
  9873. throw new TypeError("First argument should be an array");
  9874. }
  9875. points.forEach(point => {
  9876. if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
  9877. throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
  9878. }
  9879. });
  9880. points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
  9881. if (points.length < 2) {
  9882. return [];
  9883. }
  9884. const len = points.length;
  9885. const leftTangent = createTangent(points[1], points[0]);
  9886. const rightTangent = createTangent(points[len - 2], points[len - 1]);
  9887. return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
  9888. }
  9889. function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
  9890. const MaxIterations = 20;
  9891. var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
  9892. if (points.length === 2) {
  9893. dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
  9894. bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
  9895. return [bezCurve];
  9896. }
  9897. u = chordLengthParameterize(points);
  9898. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
  9899. if (maxError === 0 || maxError < error) {
  9900. return [bezCurve];
  9901. }
  9902. if (maxError < error * error) {
  9903. uPrime = u;
  9904. prevErr = maxError;
  9905. prevSplit = splitPoint;
  9906. for (i = 0; i < MaxIterations; i++) {
  9907. uPrime = reparameterize(bezCurve, points, uPrime);
  9908. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
  9909. if (maxError < error) {
  9910. return [bezCurve];
  9911. } else if (splitPoint === prevSplit) {
  9912. let errChange = maxError / prevErr;
  9913. if (errChange > .9999 && errChange < 1.0001) {
  9914. break;
  9915. }
  9916. }
  9917. prevErr = maxError;
  9918. prevSplit = splitPoint;
  9919. }
  9920. }
  9921. beziers = [];
  9922. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
  9923. if (centerVector.every(val => val === 0)) {
  9924. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
  9925. [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
  9926. }
  9927. toCenterTangent = maths.normalize(centerVector);
  9928. fromCenterTangent = maths.mulItems(toCenterTangent, -1);
  9929. beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
  9930. beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
  9931. return beziers;
  9932. }
  9933. ;
  9934. function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
  9935. var bezCurve, maxError, splitPoint;
  9936. bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
  9937. [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
  9938. if (progressCallback) {
  9939. progressCallback({
  9940. bez: bezCurve,
  9941. points: points,
  9942. params: paramsOrig,
  9943. maxErr: maxError,
  9944. maxPoint: splitPoint
  9945. });
  9946. }
  9947. return [bezCurve, maxError, splitPoint];
  9948. }
  9949. function generateBezier(points, parameters, leftTangent, rightTangent) {
  9950. var bezCurve,
  9951. A,
  9952. a,
  9953. C,
  9954. X,
  9955. det_C0_C1,
  9956. det_C0_X,
  9957. det_X_C1,
  9958. alpha_l,
  9959. alpha_r,
  9960. epsilon,
  9961. segLength,
  9962. i,
  9963. len,
  9964. tmp,
  9965. u,
  9966. ux,
  9967. firstPoint = points[0],
  9968. lastPoint = points[points.length - 1];
  9969. bezCurve = [firstPoint, null, null, lastPoint];
  9970. A = maths.zeros_Xx2x2(parameters.length);
  9971. for (i = 0, len = parameters.length; i < len; i++) {
  9972. u = parameters[i];
  9973. ux = 1 - u;
  9974. a = A[i];
  9975. a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
  9976. a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
  9977. }
  9978. C = [[0, 0], [0, 0]];
  9979. X = [0, 0];
  9980. for (i = 0, len = points.length; i < len; i++) {
  9981. u = parameters[i];
  9982. a = A[i];
  9983. C[0][0] += maths.dot(a[0], a[0]);
  9984. C[0][1] += maths.dot(a[0], a[1]);
  9985. C[1][0] += maths.dot(a[0], a[1]);
  9986. C[1][1] += maths.dot(a[1], a[1]);
  9987. tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
  9988. X[0] += maths.dot(a[0], tmp);
  9989. X[1] += maths.dot(a[1], tmp);
  9990. }
  9991. det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  9992. det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
  9993. det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
  9994. alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
  9995. alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
  9996. segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
  9997. epsilon = 1.0e-6 * segLength;
  9998. if (alpha_l < epsilon || alpha_r < epsilon) {
  9999. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
  10000. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
  10001. } else {
  10002. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
  10003. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
  10004. }
  10005. return bezCurve;
  10006. }
  10007. ;
  10008. function reparameterize(bezier, points, parameters) {
  10009. return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
  10010. }
  10011. ;
  10012. function newtonRaphsonRootFind(bez, point, u) {
  10013. var d = maths.subtract(bezier.q(bez, u), point),
  10014. qprime = bezier.qprime(bez, u),
  10015. numerator = maths.mulMatrix(d, qprime),
  10016. denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
  10017. if (denominator === 0) {
  10018. return u;
  10019. } else {
  10020. return u - numerator / denominator;
  10021. }
  10022. }
  10023. ;
  10024. function chordLengthParameterize(points) {
  10025. var u = [],
  10026. currU,
  10027. prevU,
  10028. prevP;
  10029. points.forEach((p, i) => {
  10030. currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
  10031. u.push(currU);
  10032. prevU = currU;
  10033. prevP = p;
  10034. });
  10035. u = u.map(x => x / prevU);
  10036. return u;
  10037. }
  10038. ;
  10039. function computeMaxError(points, bez, parameters) {
  10040. var dist, maxDist, splitPoint, v, i, count, point, t;
  10041. maxDist = 0;
  10042. splitPoint = Math.floor(points.length / 2);
  10043. const t_distMap = mapTtoRelativeDistances(bez, 10);
  10044. for (i = 0, count = points.length; i < count; i++) {
  10045. point = points[i];
  10046. t = find_t(bez, parameters[i], t_distMap, 10);
  10047. v = maths.subtract(bezier.q(bez, t), point);
  10048. dist = v[0] * v[0] + v[1] * v[1];
  10049. if (dist > maxDist) {
  10050. maxDist = dist;
  10051. splitPoint = i;
  10052. }
  10053. }
  10054. return [maxDist, splitPoint];
  10055. }
  10056. ;
  10057. var mapTtoRelativeDistances = function (bez, B_parts) {
  10058. var B_t_curr;
  10059. var B_t_dist = [0];
  10060. var B_t_prev = bez[0];
  10061. var sumLen = 0;
  10062. for (var i = 1; i <= B_parts; i++) {
  10063. B_t_curr = bezier.q(bez, i / B_parts);
  10064. sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
  10065. B_t_dist.push(sumLen);
  10066. B_t_prev = B_t_curr;
  10067. }
  10068. B_t_dist = B_t_dist.map(x => x / sumLen);
  10069. return B_t_dist;
  10070. };
  10071. function find_t(bez, param, t_distMap, B_parts) {
  10072. if (param < 0) {
  10073. return 0;
  10074. }
  10075. if (param > 1) {
  10076. return 1;
  10077. }
  10078. var lenMax, lenMin, tMax, tMin, t;
  10079. for (var i = 1; i <= B_parts; i++) {
  10080. if (param <= t_distMap[i]) {
  10081. tMin = (i - 1) / B_parts;
  10082. tMax = i / B_parts;
  10083. lenMin = t_distMap[i - 1];
  10084. lenMax = t_distMap[i];
  10085. t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
  10086. break;
  10087. }
  10088. }
  10089. return t;
  10090. }
  10091. function createTangent(pointA, pointB) {
  10092. return maths.normalize(maths.subtract(pointA, pointB));
  10093. }
  10094. class maths {
  10095. static zeros_Xx2x2(x) {
  10096. var zs = [];
  10097. while (x--) {
  10098. zs.push([0, 0]);
  10099. }
  10100. return zs;
  10101. }
  10102. static mulItems(items, multiplier) {
  10103. return items.map(x => x * multiplier);
  10104. }
  10105. static mulMatrix(m1, m2) {
  10106. return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
  10107. }
  10108. static subtract(arr1, arr2) {
  10109. return arr1.map((x1, i) => x1 - arr2[i]);
  10110. }
  10111. static addArrays(arr1, arr2) {
  10112. return arr1.map((x1, i) => x1 + arr2[i]);
  10113. }
  10114. static addItems(items, addition) {
  10115. return items.map(x => x + addition);
  10116. }
  10117. static sum(items) {
  10118. return items.reduce((sum, x) => sum + x);
  10119. }
  10120. static dot(m1, m2) {
  10121. return maths.mulMatrix(m1, m2);
  10122. }
  10123. static vectorLen(v) {
  10124. return Math.hypot(...v);
  10125. }
  10126. static divItems(items, divisor) {
  10127. return items.map(x => x / divisor);
  10128. }
  10129. static squareItems(items) {
  10130. return items.map(x => x * x);
  10131. }
  10132. static normalize(v) {
  10133. return this.divItems(v, this.vectorLen(v));
  10134. }
  10135. }
  10136. class bezier {
  10137. static q(ctrlPoly, t) {
  10138. var tx = 1.0 - t;
  10139. var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
  10140. pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
  10141. pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
  10142. pD = maths.mulItems(ctrlPoly[3], t * t * t);
  10143. return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
  10144. }
  10145. static qprime(ctrlPoly, t) {
  10146. var tx = 1.0 - t;
  10147. var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
  10148. pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
  10149. pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
  10150. return maths.addArrays(maths.addArrays(pA, pB), pC);
  10151. }
  10152. static qprimeprime(ctrlPoly, t) {
  10153. 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));
  10154. }
  10155. }
  10156. module.exports = fitCurve;
  10157. module.exports.fitCubic = fitCubic;
  10158. module.exports.createTangent = createTangent;
  10159. /***/ }),
  10160. /* 26 */
  10161. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10162. Object.defineProperty(exports, "__esModule", ({
  10163. value: true
  10164. }));
  10165. exports.AnnotationLayer = void 0;
  10166. var _util = __w_pdfjs_require__(1);
  10167. var _display_utils = __w_pdfjs_require__(6);
  10168. var _annotation_storage = __w_pdfjs_require__(3);
  10169. var _scripting_utils = __w_pdfjs_require__(27);
  10170. var _xfa_layer = __w_pdfjs_require__(28);
  10171. const DEFAULT_TAB_INDEX = 1000;
  10172. const DEFAULT_FONT_SIZE = 9;
  10173. const GetElementsByNameSet = new WeakSet();
  10174. function getRectDims(rect) {
  10175. return {
  10176. width: rect[2] - rect[0],
  10177. height: rect[3] - rect[1]
  10178. };
  10179. }
  10180. class AnnotationElementFactory {
  10181. static create(parameters) {
  10182. const subtype = parameters.data.annotationType;
  10183. switch (subtype) {
  10184. case _util.AnnotationType.LINK:
  10185. return new LinkAnnotationElement(parameters);
  10186. case _util.AnnotationType.TEXT:
  10187. return new TextAnnotationElement(parameters);
  10188. case _util.AnnotationType.WIDGET:
  10189. const fieldType = parameters.data.fieldType;
  10190. switch (fieldType) {
  10191. case "Tx":
  10192. return new TextWidgetAnnotationElement(parameters);
  10193. case "Btn":
  10194. if (parameters.data.radioButton) {
  10195. return new RadioButtonWidgetAnnotationElement(parameters);
  10196. } else if (parameters.data.checkBox) {
  10197. return new CheckboxWidgetAnnotationElement(parameters);
  10198. }
  10199. return new PushButtonWidgetAnnotationElement(parameters);
  10200. case "Ch":
  10201. return new ChoiceWidgetAnnotationElement(parameters);
  10202. }
  10203. return new WidgetAnnotationElement(parameters);
  10204. case _util.AnnotationType.POPUP:
  10205. return new PopupAnnotationElement(parameters);
  10206. case _util.AnnotationType.FREETEXT:
  10207. return new FreeTextAnnotationElement(parameters);
  10208. case _util.AnnotationType.LINE:
  10209. return new LineAnnotationElement(parameters);
  10210. case _util.AnnotationType.SQUARE:
  10211. return new SquareAnnotationElement(parameters);
  10212. case _util.AnnotationType.CIRCLE:
  10213. return new CircleAnnotationElement(parameters);
  10214. case _util.AnnotationType.POLYLINE:
  10215. return new PolylineAnnotationElement(parameters);
  10216. case _util.AnnotationType.CARET:
  10217. return new CaretAnnotationElement(parameters);
  10218. case _util.AnnotationType.INK:
  10219. return new InkAnnotationElement(parameters);
  10220. case _util.AnnotationType.POLYGON:
  10221. return new PolygonAnnotationElement(parameters);
  10222. case _util.AnnotationType.HIGHLIGHT:
  10223. return new HighlightAnnotationElement(parameters);
  10224. case _util.AnnotationType.UNDERLINE:
  10225. return new UnderlineAnnotationElement(parameters);
  10226. case _util.AnnotationType.SQUIGGLY:
  10227. return new SquigglyAnnotationElement(parameters);
  10228. case _util.AnnotationType.STRIKEOUT:
  10229. return new StrikeOutAnnotationElement(parameters);
  10230. case _util.AnnotationType.STAMP:
  10231. return new StampAnnotationElement(parameters);
  10232. case _util.AnnotationType.FILEATTACHMENT:
  10233. return new FileAttachmentAnnotationElement(parameters);
  10234. default:
  10235. return new AnnotationElement(parameters);
  10236. }
  10237. }
  10238. }
  10239. class AnnotationElement {
  10240. constructor(parameters, {
  10241. isRenderable = false,
  10242. ignoreBorder = false,
  10243. createQuadrilaterals = false
  10244. } = {}) {
  10245. this.isRenderable = isRenderable;
  10246. this.data = parameters.data;
  10247. this.layer = parameters.layer;
  10248. this.page = parameters.page;
  10249. this.viewport = parameters.viewport;
  10250. this.linkService = parameters.linkService;
  10251. this.downloadManager = parameters.downloadManager;
  10252. this.imageResourcesPath = parameters.imageResourcesPath;
  10253. this.renderForms = parameters.renderForms;
  10254. this.svgFactory = parameters.svgFactory;
  10255. this.annotationStorage = parameters.annotationStorage;
  10256. this.enableScripting = parameters.enableScripting;
  10257. this.hasJSActions = parameters.hasJSActions;
  10258. this._fieldObjects = parameters.fieldObjects;
  10259. this._mouseState = parameters.mouseState;
  10260. if (isRenderable) {
  10261. this.container = this._createContainer(ignoreBorder);
  10262. }
  10263. if (createQuadrilaterals) {
  10264. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  10265. }
  10266. }
  10267. _createContainer(ignoreBorder = false) {
  10268. const data = this.data,
  10269. page = this.page,
  10270. viewport = this.viewport;
  10271. const container = document.createElement("section");
  10272. const {
  10273. width,
  10274. height
  10275. } = getRectDims(data.rect);
  10276. const [pageLLx, pageLLy, pageURx, pageURy] = viewport.viewBox;
  10277. const pageWidth = pageURx - pageLLx;
  10278. const pageHeight = pageURy - pageLLy;
  10279. container.setAttribute("data-annotation-id", data.id);
  10280. 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]]);
  10281. if (!ignoreBorder && data.borderStyle.width > 0) {
  10282. container.style.borderWidth = `${data.borderStyle.width}px`;
  10283. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  10284. const verticalRadius = data.borderStyle.verticalCornerRadius;
  10285. if (horizontalRadius > 0 || verticalRadius > 0) {
  10286. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  10287. container.style.borderRadius = radius;
  10288. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  10289. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  10290. container.style.borderRadius = radius;
  10291. }
  10292. switch (data.borderStyle.style) {
  10293. case _util.AnnotationBorderStyleType.SOLID:
  10294. container.style.borderStyle = "solid";
  10295. break;
  10296. case _util.AnnotationBorderStyleType.DASHED:
  10297. container.style.borderStyle = "dashed";
  10298. break;
  10299. case _util.AnnotationBorderStyleType.BEVELED:
  10300. (0, _util.warn)("Unimplemented border style: beveled");
  10301. break;
  10302. case _util.AnnotationBorderStyleType.INSET:
  10303. (0, _util.warn)("Unimplemented border style: inset");
  10304. break;
  10305. case _util.AnnotationBorderStyleType.UNDERLINE:
  10306. container.style.borderBottomStyle = "solid";
  10307. break;
  10308. default:
  10309. break;
  10310. }
  10311. const borderColor = data.borderColor || null;
  10312. if (borderColor) {
  10313. container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  10314. } else {
  10315. container.style.borderWidth = 0;
  10316. }
  10317. }
  10318. container.style.left = `${100 * (rect[0] - pageLLx) / pageWidth}%`;
  10319. container.style.top = `${100 * (rect[1] - pageLLy) / pageHeight}%`;
  10320. const {
  10321. rotation
  10322. } = data;
  10323. if (data.hasOwnCanvas || rotation === 0) {
  10324. container.style.width = `${100 * width / pageWidth}%`;
  10325. container.style.height = `${100 * height / pageHeight}%`;
  10326. } else {
  10327. this.setRotation(rotation, container);
  10328. }
  10329. return container;
  10330. }
  10331. setRotation(angle, container = this.container) {
  10332. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  10333. const pageWidth = pageURx - pageLLx;
  10334. const pageHeight = pageURy - pageLLy;
  10335. const {
  10336. width,
  10337. height
  10338. } = getRectDims(this.data.rect);
  10339. let elementWidth, elementHeight;
  10340. if (angle % 180 === 0) {
  10341. elementWidth = 100 * width / pageWidth;
  10342. elementHeight = 100 * height / pageHeight;
  10343. } else {
  10344. elementWidth = 100 * height / pageWidth;
  10345. elementHeight = 100 * width / pageHeight;
  10346. }
  10347. container.style.width = `${elementWidth}%`;
  10348. container.style.height = `${elementHeight}%`;
  10349. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  10350. }
  10351. get _commonActions() {
  10352. const setColor = (jsName, styleName, event) => {
  10353. const color = event.detail[jsName];
  10354. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  10355. };
  10356. return (0, _util.shadow)(this, "_commonActions", {
  10357. display: event => {
  10358. const hidden = event.detail.display % 2 === 1;
  10359. this.container.style.visibility = hidden ? "hidden" : "visible";
  10360. this.annotationStorage.setValue(this.data.id, {
  10361. hidden,
  10362. print: event.detail.display === 0 || event.detail.display === 3
  10363. });
  10364. },
  10365. print: event => {
  10366. this.annotationStorage.setValue(this.data.id, {
  10367. print: event.detail.print
  10368. });
  10369. },
  10370. hidden: event => {
  10371. this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
  10372. this.annotationStorage.setValue(this.data.id, {
  10373. hidden: event.detail.hidden
  10374. });
  10375. },
  10376. focus: event => {
  10377. setTimeout(() => event.target.focus({
  10378. preventScroll: false
  10379. }), 0);
  10380. },
  10381. userName: event => {
  10382. event.target.title = event.detail.userName;
  10383. },
  10384. readonly: event => {
  10385. if (event.detail.readonly) {
  10386. event.target.setAttribute("readonly", "");
  10387. } else {
  10388. event.target.removeAttribute("readonly");
  10389. }
  10390. },
  10391. required: event => {
  10392. this._setRequired(event.target, event.detail.required);
  10393. },
  10394. bgColor: event => {
  10395. setColor("bgColor", "backgroundColor", event);
  10396. },
  10397. fillColor: event => {
  10398. setColor("fillColor", "backgroundColor", event);
  10399. },
  10400. fgColor: event => {
  10401. setColor("fgColor", "color", event);
  10402. },
  10403. textColor: event => {
  10404. setColor("textColor", "color", event);
  10405. },
  10406. borderColor: event => {
  10407. setColor("borderColor", "borderColor", event);
  10408. },
  10409. strokeColor: event => {
  10410. setColor("strokeColor", "borderColor", event);
  10411. },
  10412. rotation: event => {
  10413. const angle = event.detail.rotation;
  10414. this.setRotation(angle);
  10415. this.annotationStorage.setValue(this.data.id, {
  10416. rotation: angle
  10417. });
  10418. }
  10419. });
  10420. }
  10421. _dispatchEventFromSandbox(actions, jsEvent) {
  10422. const commonActions = this._commonActions;
  10423. for (const name of Object.keys(jsEvent.detail)) {
  10424. const action = actions[name] || commonActions[name];
  10425. action?.(jsEvent);
  10426. }
  10427. }
  10428. _setDefaultPropertiesFromJS(element) {
  10429. if (!this.enableScripting) {
  10430. return;
  10431. }
  10432. const storedData = this.annotationStorage.getRawValue(this.data.id);
  10433. if (!storedData) {
  10434. return;
  10435. }
  10436. const commonActions = this._commonActions;
  10437. for (const [actionName, detail] of Object.entries(storedData)) {
  10438. const action = commonActions[actionName];
  10439. if (action) {
  10440. const eventProxy = {
  10441. detail: {
  10442. [actionName]: detail
  10443. },
  10444. target: element
  10445. };
  10446. action(eventProxy);
  10447. delete storedData[actionName];
  10448. }
  10449. }
  10450. }
  10451. _createQuadrilaterals(ignoreBorder = false) {
  10452. if (!this.data.quadPoints) {
  10453. return null;
  10454. }
  10455. const quadrilaterals = [];
  10456. const savedRect = this.data.rect;
  10457. for (const quadPoint of this.data.quadPoints) {
  10458. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  10459. quadrilaterals.push(this._createContainer(ignoreBorder));
  10460. }
  10461. this.data.rect = savedRect;
  10462. return quadrilaterals;
  10463. }
  10464. _createPopup(trigger, data) {
  10465. let container = this.container;
  10466. if (this.quadrilaterals) {
  10467. trigger = trigger || this.quadrilaterals;
  10468. container = this.quadrilaterals[0];
  10469. }
  10470. if (!trigger) {
  10471. trigger = document.createElement("div");
  10472. trigger.className = "popupTriggerArea";
  10473. container.append(trigger);
  10474. }
  10475. const popupElement = new PopupElement({
  10476. container,
  10477. trigger,
  10478. color: data.color,
  10479. titleObj: data.titleObj,
  10480. modificationDate: data.modificationDate,
  10481. contentsObj: data.contentsObj,
  10482. richText: data.richText,
  10483. hideWrapper: true
  10484. });
  10485. const popup = popupElement.render();
  10486. popup.style.left = "100%";
  10487. container.append(popup);
  10488. }
  10489. _renderQuadrilaterals(className) {
  10490. for (const quadrilateral of this.quadrilaterals) {
  10491. quadrilateral.className = className;
  10492. }
  10493. return this.quadrilaterals;
  10494. }
  10495. render() {
  10496. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  10497. }
  10498. _getElementsByName(name, skipId = null) {
  10499. const fields = [];
  10500. if (this._fieldObjects) {
  10501. const fieldObj = this._fieldObjects[name];
  10502. if (fieldObj) {
  10503. for (const {
  10504. page,
  10505. id,
  10506. exportValues
  10507. } of fieldObj) {
  10508. if (page === -1) {
  10509. continue;
  10510. }
  10511. if (id === skipId) {
  10512. continue;
  10513. }
  10514. const exportValue = typeof exportValues === "string" ? exportValues : null;
  10515. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  10516. if (domElement && !GetElementsByNameSet.has(domElement)) {
  10517. (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
  10518. continue;
  10519. }
  10520. fields.push({
  10521. id,
  10522. exportValue,
  10523. domElement
  10524. });
  10525. }
  10526. }
  10527. return fields;
  10528. }
  10529. for (const domElement of document.getElementsByName(name)) {
  10530. const {
  10531. exportValue
  10532. } = domElement;
  10533. const id = domElement.getAttribute("data-element-id");
  10534. if (id === skipId) {
  10535. continue;
  10536. }
  10537. if (!GetElementsByNameSet.has(domElement)) {
  10538. continue;
  10539. }
  10540. fields.push({
  10541. id,
  10542. exportValue,
  10543. domElement
  10544. });
  10545. }
  10546. return fields;
  10547. }
  10548. static get platform() {
  10549. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  10550. return (0, _util.shadow)(this, "platform", {
  10551. isWin: platform.includes("Win"),
  10552. isMac: platform.includes("Mac")
  10553. });
  10554. }
  10555. }
  10556. class LinkAnnotationElement extends AnnotationElement {
  10557. constructor(parameters, options = null) {
  10558. super(parameters, {
  10559. isRenderable: true,
  10560. ignoreBorder: !!options?.ignoreBorder,
  10561. createQuadrilaterals: true
  10562. });
  10563. this.isTooltipOnly = parameters.data.isTooltipOnly;
  10564. }
  10565. render() {
  10566. const {
  10567. data,
  10568. linkService
  10569. } = this;
  10570. const link = document.createElement("a");
  10571. link.setAttribute("data-element-id", data.id);
  10572. let isBound = false;
  10573. if (data.url) {
  10574. linkService.addLinkAttributes(link, data.url, data.newWindow);
  10575. isBound = true;
  10576. } else if (data.action) {
  10577. this._bindNamedAction(link, data.action);
  10578. isBound = true;
  10579. } else if (data.attachment) {
  10580. this._bindAttachment(link, data.attachment);
  10581. isBound = true;
  10582. } else if (data.setOCGState) {
  10583. this.#bindSetOCGState(link, data.setOCGState);
  10584. isBound = true;
  10585. } else if (data.dest) {
  10586. this._bindLink(link, data.dest);
  10587. isBound = true;
  10588. } else {
  10589. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  10590. this._bindJSAction(link, data);
  10591. isBound = true;
  10592. }
  10593. if (data.resetForm) {
  10594. this._bindResetFormAction(link, data.resetForm);
  10595. isBound = true;
  10596. } else if (this.isTooltipOnly && !isBound) {
  10597. this._bindLink(link, "");
  10598. isBound = true;
  10599. }
  10600. }
  10601. if (this.quadrilaterals) {
  10602. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  10603. const linkElement = index === 0 ? link : link.cloneNode();
  10604. quadrilateral.append(linkElement);
  10605. return quadrilateral;
  10606. });
  10607. }
  10608. this.container.className = "linkAnnotation";
  10609. if (isBound) {
  10610. this.container.append(link);
  10611. }
  10612. return this.container;
  10613. }
  10614. #setInternalLink() {
  10615. this.container.setAttribute("data-internal-link", "");
  10616. }
  10617. _bindLink(link, destination) {
  10618. link.href = this.linkService.getDestinationHash(destination);
  10619. link.onclick = () => {
  10620. if (destination) {
  10621. this.linkService.goToDestination(destination);
  10622. }
  10623. return false;
  10624. };
  10625. if (destination || destination === "") {
  10626. this.#setInternalLink();
  10627. }
  10628. }
  10629. _bindNamedAction(link, action) {
  10630. link.href = this.linkService.getAnchorUrl("");
  10631. link.onclick = () => {
  10632. this.linkService.executeNamedAction(action);
  10633. return false;
  10634. };
  10635. this.#setInternalLink();
  10636. }
  10637. _bindAttachment(link, attachment) {
  10638. link.href = this.linkService.getAnchorUrl("");
  10639. link.onclick = () => {
  10640. this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
  10641. return false;
  10642. };
  10643. this.#setInternalLink();
  10644. }
  10645. #bindSetOCGState(link, action) {
  10646. link.href = this.linkService.getAnchorUrl("");
  10647. link.onclick = () => {
  10648. this.linkService.executeSetOCGState(action);
  10649. return false;
  10650. };
  10651. this.#setInternalLink();
  10652. }
  10653. _bindJSAction(link, data) {
  10654. link.href = this.linkService.getAnchorUrl("");
  10655. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  10656. for (const name of Object.keys(data.actions)) {
  10657. const jsName = map.get(name);
  10658. if (!jsName) {
  10659. continue;
  10660. }
  10661. link[jsName] = () => {
  10662. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10663. source: this,
  10664. detail: {
  10665. id: data.id,
  10666. name
  10667. }
  10668. });
  10669. return false;
  10670. };
  10671. }
  10672. if (!link.onclick) {
  10673. link.onclick = () => false;
  10674. }
  10675. this.#setInternalLink();
  10676. }
  10677. _bindResetFormAction(link, resetForm) {
  10678. const otherClickAction = link.onclick;
  10679. if (!otherClickAction) {
  10680. link.href = this.linkService.getAnchorUrl("");
  10681. }
  10682. this.#setInternalLink();
  10683. if (!this._fieldObjects) {
  10684. (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  10685. if (!otherClickAction) {
  10686. link.onclick = () => false;
  10687. }
  10688. return;
  10689. }
  10690. link.onclick = () => {
  10691. otherClickAction?.();
  10692. const {
  10693. fields: resetFormFields,
  10694. refs: resetFormRefs,
  10695. include
  10696. } = resetForm;
  10697. const allFields = [];
  10698. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  10699. const fieldIds = new Set(resetFormRefs);
  10700. for (const fieldName of resetFormFields) {
  10701. const fields = this._fieldObjects[fieldName] || [];
  10702. for (const {
  10703. id
  10704. } of fields) {
  10705. fieldIds.add(id);
  10706. }
  10707. }
  10708. for (const fields of Object.values(this._fieldObjects)) {
  10709. for (const field of fields) {
  10710. if (fieldIds.has(field.id) === include) {
  10711. allFields.push(field);
  10712. }
  10713. }
  10714. }
  10715. } else {
  10716. for (const fields of Object.values(this._fieldObjects)) {
  10717. allFields.push(...fields);
  10718. }
  10719. }
  10720. const storage = this.annotationStorage;
  10721. const allIds = [];
  10722. for (const field of allFields) {
  10723. const {
  10724. id
  10725. } = field;
  10726. allIds.push(id);
  10727. switch (field.type) {
  10728. case "text":
  10729. {
  10730. const value = field.defaultValue || "";
  10731. storage.setValue(id, {
  10732. value
  10733. });
  10734. break;
  10735. }
  10736. case "checkbox":
  10737. case "radiobutton":
  10738. {
  10739. const value = field.defaultValue === field.exportValues;
  10740. storage.setValue(id, {
  10741. value
  10742. });
  10743. break;
  10744. }
  10745. case "combobox":
  10746. case "listbox":
  10747. {
  10748. const value = field.defaultValue || "";
  10749. storage.setValue(id, {
  10750. value
  10751. });
  10752. break;
  10753. }
  10754. default:
  10755. continue;
  10756. }
  10757. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  10758. if (!domElement) {
  10759. continue;
  10760. } else if (!GetElementsByNameSet.has(domElement)) {
  10761. (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
  10762. continue;
  10763. }
  10764. domElement.dispatchEvent(new Event("resetform"));
  10765. }
  10766. if (this.enableScripting) {
  10767. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10768. source: this,
  10769. detail: {
  10770. id: "app",
  10771. ids: allIds,
  10772. name: "ResetForm"
  10773. }
  10774. });
  10775. }
  10776. return false;
  10777. };
  10778. }
  10779. }
  10780. class TextAnnotationElement extends AnnotationElement {
  10781. constructor(parameters) {
  10782. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  10783. super(parameters, {
  10784. isRenderable
  10785. });
  10786. }
  10787. render() {
  10788. this.container.className = "textAnnotation";
  10789. const image = document.createElement("img");
  10790. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  10791. image.alt = "[{{type}} Annotation]";
  10792. image.dataset.l10nId = "text_annotation_type";
  10793. image.dataset.l10nArgs = JSON.stringify({
  10794. type: this.data.name
  10795. });
  10796. if (!this.data.hasPopup) {
  10797. this._createPopup(image, this.data);
  10798. }
  10799. this.container.append(image);
  10800. return this.container;
  10801. }
  10802. }
  10803. class WidgetAnnotationElement extends AnnotationElement {
  10804. render() {
  10805. if (this.data.alternativeText) {
  10806. this.container.title = this.data.alternativeText;
  10807. }
  10808. return this.container;
  10809. }
  10810. _getKeyModifier(event) {
  10811. const {
  10812. isWin,
  10813. isMac
  10814. } = AnnotationElement.platform;
  10815. return isWin && event.ctrlKey || isMac && event.metaKey;
  10816. }
  10817. _setEventListener(element, baseName, eventName, valueGetter) {
  10818. if (baseName.includes("mouse")) {
  10819. element.addEventListener(baseName, event => {
  10820. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10821. source: this,
  10822. detail: {
  10823. id: this.data.id,
  10824. name: eventName,
  10825. value: valueGetter(event),
  10826. shift: event.shiftKey,
  10827. modifier: this._getKeyModifier(event)
  10828. }
  10829. });
  10830. });
  10831. } else {
  10832. element.addEventListener(baseName, event => {
  10833. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10834. source: this,
  10835. detail: {
  10836. id: this.data.id,
  10837. name: eventName,
  10838. value: valueGetter(event)
  10839. }
  10840. });
  10841. });
  10842. }
  10843. }
  10844. _setEventListeners(element, names, getter) {
  10845. for (const [baseName, eventName] of names) {
  10846. if (eventName === "Action" || this.data.actions?.[eventName]) {
  10847. this._setEventListener(element, baseName, eventName, getter);
  10848. }
  10849. }
  10850. }
  10851. _setBackgroundColor(element) {
  10852. const color = this.data.backgroundColor || null;
  10853. element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  10854. }
  10855. _setTextStyle(element) {
  10856. const TEXT_ALIGNMENT = ["left", "center", "right"];
  10857. const {
  10858. fontColor
  10859. } = this.data.defaultAppearanceData;
  10860. const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
  10861. const style = element.style;
  10862. let computedFontSize;
  10863. const BORDER_SIZE = 2;
  10864. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  10865. if (this.data.multiLine) {
  10866. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  10867. const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
  10868. const lineHeight = height / numberOfLines;
  10869. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
  10870. } else {
  10871. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  10872. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
  10873. }
  10874. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  10875. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  10876. if (this.data.textAlignment !== null) {
  10877. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  10878. }
  10879. }
  10880. _setRequired(element, isRequired) {
  10881. if (isRequired) {
  10882. element.setAttribute("required", true);
  10883. } else {
  10884. element.removeAttribute("required");
  10885. }
  10886. element.setAttribute("aria-required", isRequired);
  10887. }
  10888. }
  10889. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  10890. constructor(parameters) {
  10891. const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  10892. super(parameters, {
  10893. isRenderable
  10894. });
  10895. }
  10896. setPropertyOnSiblings(base, key, value, keyInStorage) {
  10897. const storage = this.annotationStorage;
  10898. for (const element of this._getElementsByName(base.name, base.id)) {
  10899. if (element.domElement) {
  10900. element.domElement[key] = value;
  10901. }
  10902. storage.setValue(element.id, {
  10903. [keyInStorage]: value
  10904. });
  10905. }
  10906. }
  10907. render() {
  10908. const storage = this.annotationStorage;
  10909. const id = this.data.id;
  10910. this.container.className = "textWidgetAnnotation";
  10911. let element = null;
  10912. if (this.renderForms) {
  10913. const storedData = storage.getValue(id, {
  10914. value: this.data.fieldValue
  10915. });
  10916. let textContent = storedData.formattedValue || storedData.value || "";
  10917. const maxLen = storage.getValue(id, {
  10918. charLimit: this.data.maxLen
  10919. }).charLimit;
  10920. if (maxLen && textContent.length > maxLen) {
  10921. textContent = textContent.slice(0, maxLen);
  10922. }
  10923. const elementData = {
  10924. userValue: textContent,
  10925. formattedValue: null,
  10926. valueOnFocus: ""
  10927. };
  10928. if (this.data.multiLine) {
  10929. element = document.createElement("textarea");
  10930. element.textContent = textContent;
  10931. if (this.data.doNotScroll) {
  10932. element.style.overflowY = "hidden";
  10933. }
  10934. } else {
  10935. element = document.createElement("input");
  10936. element.type = "text";
  10937. element.setAttribute("value", textContent);
  10938. if (this.data.doNotScroll) {
  10939. element.style.overflowX = "hidden";
  10940. }
  10941. }
  10942. GetElementsByNameSet.add(element);
  10943. element.setAttribute("data-element-id", id);
  10944. element.disabled = this.data.readOnly;
  10945. element.name = this.data.fieldName;
  10946. element.tabIndex = DEFAULT_TAB_INDEX;
  10947. this._setRequired(element, this.data.required);
  10948. if (maxLen) {
  10949. element.maxLength = maxLen;
  10950. }
  10951. element.addEventListener("input", event => {
  10952. storage.setValue(id, {
  10953. value: event.target.value
  10954. });
  10955. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  10956. });
  10957. element.addEventListener("resetform", event => {
  10958. const defaultValue = this.data.defaultFieldValue ?? "";
  10959. element.value = elementData.userValue = defaultValue;
  10960. elementData.formattedValue = null;
  10961. });
  10962. let blurListener = event => {
  10963. const {
  10964. formattedValue
  10965. } = elementData;
  10966. if (formattedValue !== null && formattedValue !== undefined) {
  10967. event.target.value = formattedValue;
  10968. }
  10969. event.target.scrollLeft = 0;
  10970. };
  10971. if (this.enableScripting && this.hasJSActions) {
  10972. element.addEventListener("focus", event => {
  10973. if (elementData.userValue) {
  10974. event.target.value = elementData.userValue;
  10975. }
  10976. elementData.valueOnFocus = event.target.value;
  10977. });
  10978. element.addEventListener("updatefromsandbox", jsEvent => {
  10979. const actions = {
  10980. value(event) {
  10981. elementData.userValue = event.detail.value ?? "";
  10982. storage.setValue(id, {
  10983. value: elementData.userValue.toString()
  10984. });
  10985. event.target.value = elementData.userValue;
  10986. },
  10987. formattedValue(event) {
  10988. const {
  10989. formattedValue
  10990. } = event.detail;
  10991. elementData.formattedValue = formattedValue;
  10992. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  10993. event.target.value = formattedValue;
  10994. }
  10995. storage.setValue(id, {
  10996. formattedValue
  10997. });
  10998. },
  10999. selRange(event) {
  11000. event.target.setSelectionRange(...event.detail.selRange);
  11001. },
  11002. charLimit: event => {
  11003. const {
  11004. charLimit
  11005. } = event.detail;
  11006. const {
  11007. target
  11008. } = event;
  11009. if (charLimit === 0) {
  11010. target.removeAttribute("maxLength");
  11011. return;
  11012. }
  11013. target.setAttribute("maxLength", charLimit);
  11014. let value = elementData.userValue;
  11015. if (!value || value.length <= charLimit) {
  11016. return;
  11017. }
  11018. value = value.slice(0, charLimit);
  11019. target.value = elementData.userValue = value;
  11020. storage.setValue(id, {
  11021. value
  11022. });
  11023. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11024. source: this,
  11025. detail: {
  11026. id,
  11027. name: "Keystroke",
  11028. value,
  11029. willCommit: true,
  11030. commitKey: 1,
  11031. selStart: target.selectionStart,
  11032. selEnd: target.selectionEnd
  11033. }
  11034. });
  11035. }
  11036. };
  11037. this._dispatchEventFromSandbox(actions, jsEvent);
  11038. });
  11039. element.addEventListener("keydown", event => {
  11040. let commitKey = -1;
  11041. if (event.key === "Escape") {
  11042. commitKey = 0;
  11043. } else if (event.key === "Enter" && !this.data.multiLine) {
  11044. commitKey = 2;
  11045. } else if (event.key === "Tab") {
  11046. commitKey = 3;
  11047. }
  11048. if (commitKey === -1) {
  11049. return;
  11050. }
  11051. const {
  11052. value
  11053. } = event.target;
  11054. if (elementData.valueOnFocus === value) {
  11055. return;
  11056. }
  11057. elementData.userValue = value;
  11058. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11059. source: this,
  11060. detail: {
  11061. id,
  11062. name: "Keystroke",
  11063. value,
  11064. willCommit: true,
  11065. commitKey,
  11066. selStart: event.target.selectionStart,
  11067. selEnd: event.target.selectionEnd
  11068. }
  11069. });
  11070. });
  11071. const _blurListener = blurListener;
  11072. blurListener = null;
  11073. element.addEventListener("blur", event => {
  11074. const {
  11075. value
  11076. } = event.target;
  11077. elementData.userValue = value;
  11078. if (this._mouseState.isDown && elementData.valueOnFocus !== value) {
  11079. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11080. source: this,
  11081. detail: {
  11082. id,
  11083. name: "Keystroke",
  11084. value,
  11085. willCommit: true,
  11086. commitKey: 1,
  11087. selStart: event.target.selectionStart,
  11088. selEnd: event.target.selectionEnd
  11089. }
  11090. });
  11091. }
  11092. _blurListener(event);
  11093. });
  11094. if (this.data.actions?.Keystroke) {
  11095. element.addEventListener("beforeinput", event => {
  11096. const {
  11097. data,
  11098. target
  11099. } = event;
  11100. const {
  11101. value,
  11102. selectionStart,
  11103. selectionEnd
  11104. } = target;
  11105. let selStart = selectionStart,
  11106. selEnd = selectionEnd;
  11107. switch (event.inputType) {
  11108. case "deleteWordBackward":
  11109. {
  11110. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  11111. if (match) {
  11112. selStart -= match[0].length;
  11113. }
  11114. break;
  11115. }
  11116. case "deleteWordForward":
  11117. {
  11118. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  11119. if (match) {
  11120. selEnd += match[0].length;
  11121. }
  11122. break;
  11123. }
  11124. case "deleteContentBackward":
  11125. if (selectionStart === selectionEnd) {
  11126. selStart -= 1;
  11127. }
  11128. break;
  11129. case "deleteContentForward":
  11130. if (selectionStart === selectionEnd) {
  11131. selEnd += 1;
  11132. }
  11133. break;
  11134. }
  11135. event.preventDefault();
  11136. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11137. source: this,
  11138. detail: {
  11139. id,
  11140. name: "Keystroke",
  11141. value,
  11142. change: data || "",
  11143. willCommit: false,
  11144. selStart,
  11145. selEnd
  11146. }
  11147. });
  11148. });
  11149. }
  11150. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  11151. }
  11152. if (blurListener) {
  11153. element.addEventListener("blur", blurListener);
  11154. }
  11155. if (this.data.comb) {
  11156. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  11157. const combWidth = fieldWidth / maxLen;
  11158. element.classList.add("comb");
  11159. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  11160. }
  11161. } else {
  11162. element = document.createElement("div");
  11163. element.textContent = this.data.fieldValue;
  11164. element.style.verticalAlign = "middle";
  11165. element.style.display = "table-cell";
  11166. }
  11167. this._setTextStyle(element);
  11168. this._setBackgroundColor(element);
  11169. this._setDefaultPropertiesFromJS(element);
  11170. this.container.append(element);
  11171. return this.container;
  11172. }
  11173. }
  11174. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  11175. constructor(parameters) {
  11176. super(parameters, {
  11177. isRenderable: parameters.renderForms
  11178. });
  11179. }
  11180. render() {
  11181. const storage = this.annotationStorage;
  11182. const data = this.data;
  11183. const id = data.id;
  11184. let value = storage.getValue(id, {
  11185. value: data.exportValue === data.fieldValue
  11186. }).value;
  11187. if (typeof value === "string") {
  11188. value = value !== "Off";
  11189. storage.setValue(id, {
  11190. value
  11191. });
  11192. }
  11193. this.container.className = "buttonWidgetAnnotation checkBox";
  11194. const element = document.createElement("input");
  11195. GetElementsByNameSet.add(element);
  11196. element.setAttribute("data-element-id", id);
  11197. element.disabled = data.readOnly;
  11198. this._setRequired(element, this.data.required);
  11199. element.type = "checkbox";
  11200. element.name = data.fieldName;
  11201. if (value) {
  11202. element.setAttribute("checked", true);
  11203. }
  11204. element.setAttribute("exportValue", data.exportValue);
  11205. element.tabIndex = DEFAULT_TAB_INDEX;
  11206. element.addEventListener("change", event => {
  11207. const {
  11208. name,
  11209. checked
  11210. } = event.target;
  11211. for (const checkbox of this._getElementsByName(name, id)) {
  11212. const curChecked = checked && checkbox.exportValue === data.exportValue;
  11213. if (checkbox.domElement) {
  11214. checkbox.domElement.checked = curChecked;
  11215. }
  11216. storage.setValue(checkbox.id, {
  11217. value: curChecked
  11218. });
  11219. }
  11220. storage.setValue(id, {
  11221. value: checked
  11222. });
  11223. });
  11224. element.addEventListener("resetform", event => {
  11225. const defaultValue = data.defaultFieldValue || "Off";
  11226. event.target.checked = defaultValue === data.exportValue;
  11227. });
  11228. if (this.enableScripting && this.hasJSActions) {
  11229. element.addEventListener("updatefromsandbox", jsEvent => {
  11230. const actions = {
  11231. value(event) {
  11232. event.target.checked = event.detail.value !== "Off";
  11233. storage.setValue(id, {
  11234. value: event.target.checked
  11235. });
  11236. }
  11237. };
  11238. this._dispatchEventFromSandbox(actions, jsEvent);
  11239. });
  11240. 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);
  11241. }
  11242. this._setBackgroundColor(element);
  11243. this._setDefaultPropertiesFromJS(element);
  11244. this.container.append(element);
  11245. return this.container;
  11246. }
  11247. }
  11248. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  11249. constructor(parameters) {
  11250. super(parameters, {
  11251. isRenderable: parameters.renderForms
  11252. });
  11253. }
  11254. render() {
  11255. this.container.className = "buttonWidgetAnnotation radioButton";
  11256. const storage = this.annotationStorage;
  11257. const data = this.data;
  11258. const id = data.id;
  11259. let value = storage.getValue(id, {
  11260. value: data.fieldValue === data.buttonValue
  11261. }).value;
  11262. if (typeof value === "string") {
  11263. value = value !== data.buttonValue;
  11264. storage.setValue(id, {
  11265. value
  11266. });
  11267. }
  11268. const element = document.createElement("input");
  11269. GetElementsByNameSet.add(element);
  11270. element.setAttribute("data-element-id", id);
  11271. element.disabled = data.readOnly;
  11272. this._setRequired(element, this.data.required);
  11273. element.type = "radio";
  11274. element.name = data.fieldName;
  11275. if (value) {
  11276. element.setAttribute("checked", true);
  11277. }
  11278. element.tabIndex = DEFAULT_TAB_INDEX;
  11279. element.addEventListener("change", event => {
  11280. const {
  11281. name,
  11282. checked
  11283. } = event.target;
  11284. for (const radio of this._getElementsByName(name, id)) {
  11285. storage.setValue(radio.id, {
  11286. value: false
  11287. });
  11288. }
  11289. storage.setValue(id, {
  11290. value: checked
  11291. });
  11292. });
  11293. element.addEventListener("resetform", event => {
  11294. const defaultValue = data.defaultFieldValue;
  11295. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  11296. });
  11297. if (this.enableScripting && this.hasJSActions) {
  11298. const pdfButtonValue = data.buttonValue;
  11299. element.addEventListener("updatefromsandbox", jsEvent => {
  11300. const actions = {
  11301. value: event => {
  11302. const checked = pdfButtonValue === event.detail.value;
  11303. for (const radio of this._getElementsByName(event.target.name)) {
  11304. const curChecked = checked && radio.id === id;
  11305. if (radio.domElement) {
  11306. radio.domElement.checked = curChecked;
  11307. }
  11308. storage.setValue(radio.id, {
  11309. value: curChecked
  11310. });
  11311. }
  11312. }
  11313. };
  11314. this._dispatchEventFromSandbox(actions, jsEvent);
  11315. });
  11316. 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);
  11317. }
  11318. this._setBackgroundColor(element);
  11319. this._setDefaultPropertiesFromJS(element);
  11320. this.container.append(element);
  11321. return this.container;
  11322. }
  11323. }
  11324. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  11325. constructor(parameters) {
  11326. super(parameters, {
  11327. ignoreBorder: parameters.data.hasAppearance
  11328. });
  11329. }
  11330. render() {
  11331. const container = super.render();
  11332. container.className = "buttonWidgetAnnotation pushButton";
  11333. if (this.data.alternativeText) {
  11334. container.title = this.data.alternativeText;
  11335. }
  11336. const linkElement = container.lastChild;
  11337. if (this.enableScripting && this.hasJSActions && linkElement) {
  11338. this._setDefaultPropertiesFromJS(linkElement);
  11339. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  11340. this._dispatchEventFromSandbox({}, jsEvent);
  11341. });
  11342. }
  11343. return container;
  11344. }
  11345. }
  11346. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  11347. constructor(parameters) {
  11348. super(parameters, {
  11349. isRenderable: parameters.renderForms
  11350. });
  11351. }
  11352. render() {
  11353. this.container.className = "choiceWidgetAnnotation";
  11354. const storage = this.annotationStorage;
  11355. const id = this.data.id;
  11356. const storedData = storage.getValue(id, {
  11357. value: this.data.fieldValue
  11358. });
  11359. const selectElement = document.createElement("select");
  11360. GetElementsByNameSet.add(selectElement);
  11361. selectElement.setAttribute("data-element-id", id);
  11362. selectElement.disabled = this.data.readOnly;
  11363. this._setRequired(selectElement, this.data.required);
  11364. selectElement.name = this.data.fieldName;
  11365. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  11366. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  11367. if (!this.data.combo) {
  11368. selectElement.size = this.data.options.length;
  11369. if (this.data.multiSelect) {
  11370. selectElement.multiple = true;
  11371. }
  11372. }
  11373. selectElement.addEventListener("resetform", event => {
  11374. const defaultValue = this.data.defaultFieldValue;
  11375. for (const option of selectElement.options) {
  11376. option.selected = option.value === defaultValue;
  11377. }
  11378. });
  11379. for (const option of this.data.options) {
  11380. const optionElement = document.createElement("option");
  11381. optionElement.textContent = option.displayValue;
  11382. optionElement.value = option.exportValue;
  11383. if (storedData.value.includes(option.exportValue)) {
  11384. optionElement.setAttribute("selected", true);
  11385. addAnEmptyEntry = false;
  11386. }
  11387. selectElement.append(optionElement);
  11388. }
  11389. let removeEmptyEntry = null;
  11390. if (addAnEmptyEntry) {
  11391. const noneOptionElement = document.createElement("option");
  11392. noneOptionElement.value = " ";
  11393. noneOptionElement.setAttribute("hidden", true);
  11394. noneOptionElement.setAttribute("selected", true);
  11395. selectElement.prepend(noneOptionElement);
  11396. removeEmptyEntry = () => {
  11397. noneOptionElement.remove();
  11398. selectElement.removeEventListener("input", removeEmptyEntry);
  11399. removeEmptyEntry = null;
  11400. };
  11401. selectElement.addEventListener("input", removeEmptyEntry);
  11402. }
  11403. const getValue = (event, isExport) => {
  11404. const name = isExport ? "value" : "textContent";
  11405. const options = event.target.options;
  11406. if (!event.target.multiple) {
  11407. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  11408. }
  11409. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  11410. };
  11411. const getItems = event => {
  11412. const options = event.target.options;
  11413. return Array.prototype.map.call(options, option => {
  11414. return {
  11415. displayValue: option.textContent,
  11416. exportValue: option.value
  11417. };
  11418. });
  11419. };
  11420. if (this.enableScripting && this.hasJSActions) {
  11421. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  11422. const actions = {
  11423. value(event) {
  11424. removeEmptyEntry?.();
  11425. const value = event.detail.value;
  11426. const values = new Set(Array.isArray(value) ? value : [value]);
  11427. for (const option of selectElement.options) {
  11428. option.selected = values.has(option.value);
  11429. }
  11430. storage.setValue(id, {
  11431. value: getValue(event, true)
  11432. });
  11433. },
  11434. multipleSelection(event) {
  11435. selectElement.multiple = true;
  11436. },
  11437. remove(event) {
  11438. const options = selectElement.options;
  11439. const index = event.detail.remove;
  11440. options[index].selected = false;
  11441. selectElement.remove(index);
  11442. if (options.length > 0) {
  11443. const i = Array.prototype.findIndex.call(options, option => option.selected);
  11444. if (i === -1) {
  11445. options[0].selected = true;
  11446. }
  11447. }
  11448. storage.setValue(id, {
  11449. value: getValue(event, true),
  11450. items: getItems(event)
  11451. });
  11452. },
  11453. clear(event) {
  11454. while (selectElement.length !== 0) {
  11455. selectElement.remove(0);
  11456. }
  11457. storage.setValue(id, {
  11458. value: null,
  11459. items: []
  11460. });
  11461. },
  11462. insert(event) {
  11463. const {
  11464. index,
  11465. displayValue,
  11466. exportValue
  11467. } = event.detail.insert;
  11468. const selectChild = selectElement.children[index];
  11469. const optionElement = document.createElement("option");
  11470. optionElement.textContent = displayValue;
  11471. optionElement.value = exportValue;
  11472. if (selectChild) {
  11473. selectChild.before(optionElement);
  11474. } else {
  11475. selectElement.append(optionElement);
  11476. }
  11477. storage.setValue(id, {
  11478. value: getValue(event, true),
  11479. items: getItems(event)
  11480. });
  11481. },
  11482. items(event) {
  11483. const {
  11484. items
  11485. } = event.detail;
  11486. while (selectElement.length !== 0) {
  11487. selectElement.remove(0);
  11488. }
  11489. for (const item of items) {
  11490. const {
  11491. displayValue,
  11492. exportValue
  11493. } = item;
  11494. const optionElement = document.createElement("option");
  11495. optionElement.textContent = displayValue;
  11496. optionElement.value = exportValue;
  11497. selectElement.append(optionElement);
  11498. }
  11499. if (selectElement.options.length > 0) {
  11500. selectElement.options[0].selected = true;
  11501. }
  11502. storage.setValue(id, {
  11503. value: getValue(event, true),
  11504. items: getItems(event)
  11505. });
  11506. },
  11507. indices(event) {
  11508. const indices = new Set(event.detail.indices);
  11509. for (const option of event.target.options) {
  11510. option.selected = indices.has(option.index);
  11511. }
  11512. storage.setValue(id, {
  11513. value: getValue(event, true)
  11514. });
  11515. },
  11516. editable(event) {
  11517. event.target.disabled = !event.detail.editable;
  11518. }
  11519. };
  11520. this._dispatchEventFromSandbox(actions, jsEvent);
  11521. });
  11522. selectElement.addEventListener("input", event => {
  11523. const exportValue = getValue(event, true);
  11524. const value = getValue(event, false);
  11525. storage.setValue(id, {
  11526. value: exportValue
  11527. });
  11528. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11529. source: this,
  11530. detail: {
  11531. id,
  11532. name: "Keystroke",
  11533. value,
  11534. changeEx: exportValue,
  11535. willCommit: true,
  11536. commitKey: 1,
  11537. keyDown: false
  11538. }
  11539. });
  11540. });
  11541. this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"]], event => event.target.checked);
  11542. } else {
  11543. selectElement.addEventListener("input", function (event) {
  11544. storage.setValue(id, {
  11545. value: getValue(event, true)
  11546. });
  11547. });
  11548. }
  11549. if (this.data.combo) {
  11550. this._setTextStyle(selectElement);
  11551. } else {}
  11552. this._setBackgroundColor(selectElement);
  11553. this._setDefaultPropertiesFromJS(selectElement);
  11554. this.container.append(selectElement);
  11555. return this.container;
  11556. }
  11557. }
  11558. class PopupAnnotationElement extends AnnotationElement {
  11559. static IGNORE_TYPES = new Set(["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]);
  11560. constructor(parameters) {
  11561. const {
  11562. data
  11563. } = parameters;
  11564. const isRenderable = !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) && !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
  11565. super(parameters, {
  11566. isRenderable
  11567. });
  11568. }
  11569. render() {
  11570. this.container.className = "popupAnnotation";
  11571. const parentElements = this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);
  11572. if (parentElements.length === 0) {
  11573. return this.container;
  11574. }
  11575. const popup = new PopupElement({
  11576. container: this.container,
  11577. trigger: Array.from(parentElements),
  11578. color: this.data.color,
  11579. titleObj: this.data.titleObj,
  11580. modificationDate: this.data.modificationDate,
  11581. contentsObj: this.data.contentsObj,
  11582. richText: this.data.richText
  11583. });
  11584. const page = this.page;
  11585. 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]]);
  11586. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  11587. const popupTop = rect[1];
  11588. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  11589. const pageWidth = pageURx - pageLLx;
  11590. const pageHeight = pageURy - pageLLy;
  11591. this.container.style.left = `${100 * (popupLeft - pageLLx) / pageWidth}%`;
  11592. this.container.style.top = `${100 * (popupTop - pageLLy) / pageHeight}%`;
  11593. this.container.append(popup.render());
  11594. return this.container;
  11595. }
  11596. }
  11597. class PopupElement {
  11598. constructor(parameters) {
  11599. this.container = parameters.container;
  11600. this.trigger = parameters.trigger;
  11601. this.color = parameters.color;
  11602. this.titleObj = parameters.titleObj;
  11603. this.modificationDate = parameters.modificationDate;
  11604. this.contentsObj = parameters.contentsObj;
  11605. this.richText = parameters.richText;
  11606. this.hideWrapper = parameters.hideWrapper || false;
  11607. this.pinned = false;
  11608. }
  11609. render() {
  11610. const BACKGROUND_ENLIGHT = 0.7;
  11611. const wrapper = document.createElement("div");
  11612. wrapper.className = "popupWrapper";
  11613. this.hideElement = this.hideWrapper ? wrapper : this.container;
  11614. this.hideElement.hidden = true;
  11615. const popup = document.createElement("div");
  11616. popup.className = "popup";
  11617. const color = this.color;
  11618. if (color) {
  11619. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  11620. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  11621. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  11622. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  11623. }
  11624. const title = document.createElement("h1");
  11625. title.dir = this.titleObj.dir;
  11626. title.textContent = this.titleObj.str;
  11627. popup.append(title);
  11628. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  11629. if (dateObject) {
  11630. const modificationDate = document.createElement("span");
  11631. modificationDate.className = "popupDate";
  11632. modificationDate.textContent = "{{date}}, {{time}}";
  11633. modificationDate.dataset.l10nId = "annotation_date_string";
  11634. modificationDate.dataset.l10nArgs = JSON.stringify({
  11635. date: dateObject.toLocaleDateString(),
  11636. time: dateObject.toLocaleTimeString()
  11637. });
  11638. popup.append(modificationDate);
  11639. }
  11640. if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
  11641. _xfa_layer.XfaLayer.render({
  11642. xfaHtml: this.richText.html,
  11643. intent: "richText",
  11644. div: popup
  11645. });
  11646. popup.lastChild.className = "richText popupContent";
  11647. } else {
  11648. const contents = this._formatContents(this.contentsObj);
  11649. popup.append(contents);
  11650. }
  11651. if (!Array.isArray(this.trigger)) {
  11652. this.trigger = [this.trigger];
  11653. }
  11654. for (const element of this.trigger) {
  11655. element.addEventListener("click", this._toggle.bind(this));
  11656. element.addEventListener("mouseover", this._show.bind(this, false));
  11657. element.addEventListener("mouseout", this._hide.bind(this, false));
  11658. }
  11659. popup.addEventListener("click", this._hide.bind(this, true));
  11660. wrapper.append(popup);
  11661. return wrapper;
  11662. }
  11663. _formatContents({
  11664. str,
  11665. dir
  11666. }) {
  11667. const p = document.createElement("p");
  11668. p.className = "popupContent";
  11669. p.dir = dir;
  11670. const lines = str.split(/(?:\r\n?|\n)/);
  11671. for (let i = 0, ii = lines.length; i < ii; ++i) {
  11672. const line = lines[i];
  11673. p.append(document.createTextNode(line));
  11674. if (i < ii - 1) {
  11675. p.append(document.createElement("br"));
  11676. }
  11677. }
  11678. return p;
  11679. }
  11680. _toggle() {
  11681. if (this.pinned) {
  11682. this._hide(true);
  11683. } else {
  11684. this._show(true);
  11685. }
  11686. }
  11687. _show(pin = false) {
  11688. if (pin) {
  11689. this.pinned = true;
  11690. }
  11691. if (this.hideElement.hidden) {
  11692. this.hideElement.hidden = false;
  11693. this.container.style.zIndex = parseInt(this.container.style.zIndex) + 1000;
  11694. }
  11695. }
  11696. _hide(unpin = true) {
  11697. if (unpin) {
  11698. this.pinned = false;
  11699. }
  11700. if (!this.hideElement.hidden && !this.pinned) {
  11701. this.hideElement.hidden = true;
  11702. this.container.style.zIndex = parseInt(this.container.style.zIndex) - 1000;
  11703. }
  11704. }
  11705. }
  11706. class FreeTextAnnotationElement extends AnnotationElement {
  11707. constructor(parameters) {
  11708. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11709. super(parameters, {
  11710. isRenderable,
  11711. ignoreBorder: true
  11712. });
  11713. this.textContent = parameters.data.textContent;
  11714. }
  11715. render() {
  11716. this.container.className = "freeTextAnnotation";
  11717. if (this.textContent) {
  11718. const content = document.createElement("div");
  11719. content.className = "annotationTextContent";
  11720. content.setAttribute("role", "comment");
  11721. for (const line of this.textContent) {
  11722. const lineSpan = document.createElement("span");
  11723. lineSpan.textContent = line;
  11724. content.append(lineSpan);
  11725. }
  11726. this.container.append(content);
  11727. }
  11728. if (!this.data.hasPopup) {
  11729. this._createPopup(null, this.data);
  11730. }
  11731. return this.container;
  11732. }
  11733. }
  11734. class LineAnnotationElement extends AnnotationElement {
  11735. constructor(parameters) {
  11736. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11737. super(parameters, {
  11738. isRenderable,
  11739. ignoreBorder: true
  11740. });
  11741. }
  11742. render() {
  11743. this.container.className = "lineAnnotation";
  11744. const data = this.data;
  11745. const {
  11746. width,
  11747. height
  11748. } = getRectDims(data.rect);
  11749. const svg = this.svgFactory.create(width, height, true);
  11750. const line = this.svgFactory.createElement("svg:line");
  11751. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  11752. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  11753. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  11754. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  11755. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  11756. line.setAttribute("stroke", "transparent");
  11757. line.setAttribute("fill", "transparent");
  11758. svg.append(line);
  11759. this.container.append(svg);
  11760. this._createPopup(line, data);
  11761. return this.container;
  11762. }
  11763. }
  11764. class SquareAnnotationElement extends AnnotationElement {
  11765. constructor(parameters) {
  11766. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11767. super(parameters, {
  11768. isRenderable,
  11769. ignoreBorder: true
  11770. });
  11771. }
  11772. render() {
  11773. this.container.className = "squareAnnotation";
  11774. const data = this.data;
  11775. const {
  11776. width,
  11777. height
  11778. } = getRectDims(data.rect);
  11779. const svg = this.svgFactory.create(width, height, true);
  11780. const borderWidth = data.borderStyle.width;
  11781. const square = this.svgFactory.createElement("svg:rect");
  11782. square.setAttribute("x", borderWidth / 2);
  11783. square.setAttribute("y", borderWidth / 2);
  11784. square.setAttribute("width", width - borderWidth);
  11785. square.setAttribute("height", height - borderWidth);
  11786. square.setAttribute("stroke-width", borderWidth || 1);
  11787. square.setAttribute("stroke", "transparent");
  11788. square.setAttribute("fill", "transparent");
  11789. svg.append(square);
  11790. this.container.append(svg);
  11791. this._createPopup(square, data);
  11792. return this.container;
  11793. }
  11794. }
  11795. class CircleAnnotationElement extends AnnotationElement {
  11796. constructor(parameters) {
  11797. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11798. super(parameters, {
  11799. isRenderable,
  11800. ignoreBorder: true
  11801. });
  11802. }
  11803. render() {
  11804. this.container.className = "circleAnnotation";
  11805. const data = this.data;
  11806. const {
  11807. width,
  11808. height
  11809. } = getRectDims(data.rect);
  11810. const svg = this.svgFactory.create(width, height, true);
  11811. const borderWidth = data.borderStyle.width;
  11812. const circle = this.svgFactory.createElement("svg:ellipse");
  11813. circle.setAttribute("cx", width / 2);
  11814. circle.setAttribute("cy", height / 2);
  11815. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  11816. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  11817. circle.setAttribute("stroke-width", borderWidth || 1);
  11818. circle.setAttribute("stroke", "transparent");
  11819. circle.setAttribute("fill", "transparent");
  11820. svg.append(circle);
  11821. this.container.append(svg);
  11822. this._createPopup(circle, data);
  11823. return this.container;
  11824. }
  11825. }
  11826. class PolylineAnnotationElement extends AnnotationElement {
  11827. constructor(parameters) {
  11828. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11829. super(parameters, {
  11830. isRenderable,
  11831. ignoreBorder: true
  11832. });
  11833. this.containerClassName = "polylineAnnotation";
  11834. this.svgElementName = "svg:polyline";
  11835. }
  11836. render() {
  11837. this.container.className = this.containerClassName;
  11838. const data = this.data;
  11839. const {
  11840. width,
  11841. height
  11842. } = getRectDims(data.rect);
  11843. const svg = this.svgFactory.create(width, height, true);
  11844. let points = [];
  11845. for (const coordinate of data.vertices) {
  11846. const x = coordinate.x - data.rect[0];
  11847. const y = data.rect[3] - coordinate.y;
  11848. points.push(x + "," + y);
  11849. }
  11850. points = points.join(" ");
  11851. const polyline = this.svgFactory.createElement(this.svgElementName);
  11852. polyline.setAttribute("points", points);
  11853. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  11854. polyline.setAttribute("stroke", "transparent");
  11855. polyline.setAttribute("fill", "transparent");
  11856. svg.append(polyline);
  11857. this.container.append(svg);
  11858. this._createPopup(polyline, data);
  11859. return this.container;
  11860. }
  11861. }
  11862. class PolygonAnnotationElement extends PolylineAnnotationElement {
  11863. constructor(parameters) {
  11864. super(parameters);
  11865. this.containerClassName = "polygonAnnotation";
  11866. this.svgElementName = "svg:polygon";
  11867. }
  11868. }
  11869. class CaretAnnotationElement extends AnnotationElement {
  11870. constructor(parameters) {
  11871. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11872. super(parameters, {
  11873. isRenderable,
  11874. ignoreBorder: true
  11875. });
  11876. }
  11877. render() {
  11878. this.container.className = "caretAnnotation";
  11879. if (!this.data.hasPopup) {
  11880. this._createPopup(null, this.data);
  11881. }
  11882. return this.container;
  11883. }
  11884. }
  11885. class InkAnnotationElement extends AnnotationElement {
  11886. constructor(parameters) {
  11887. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11888. super(parameters, {
  11889. isRenderable,
  11890. ignoreBorder: true
  11891. });
  11892. this.containerClassName = "inkAnnotation";
  11893. this.svgElementName = "svg:polyline";
  11894. }
  11895. render() {
  11896. this.container.className = this.containerClassName;
  11897. const data = this.data;
  11898. const {
  11899. width,
  11900. height
  11901. } = getRectDims(data.rect);
  11902. const svg = this.svgFactory.create(width, height, true);
  11903. for (const inkList of data.inkLists) {
  11904. let points = [];
  11905. for (const coordinate of inkList) {
  11906. const x = coordinate.x - data.rect[0];
  11907. const y = data.rect[3] - coordinate.y;
  11908. points.push(`${x},${y}`);
  11909. }
  11910. points = points.join(" ");
  11911. const polyline = this.svgFactory.createElement(this.svgElementName);
  11912. polyline.setAttribute("points", points);
  11913. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  11914. polyline.setAttribute("stroke", "transparent");
  11915. polyline.setAttribute("fill", "transparent");
  11916. this._createPopup(polyline, data);
  11917. svg.append(polyline);
  11918. }
  11919. this.container.append(svg);
  11920. return this.container;
  11921. }
  11922. }
  11923. class HighlightAnnotationElement extends AnnotationElement {
  11924. constructor(parameters) {
  11925. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11926. super(parameters, {
  11927. isRenderable,
  11928. ignoreBorder: true,
  11929. createQuadrilaterals: true
  11930. });
  11931. }
  11932. render() {
  11933. if (!this.data.hasPopup) {
  11934. this._createPopup(null, this.data);
  11935. }
  11936. if (this.quadrilaterals) {
  11937. return this._renderQuadrilaterals("highlightAnnotation");
  11938. }
  11939. this.container.className = "highlightAnnotation";
  11940. return this.container;
  11941. }
  11942. }
  11943. class UnderlineAnnotationElement extends AnnotationElement {
  11944. constructor(parameters) {
  11945. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11946. super(parameters, {
  11947. isRenderable,
  11948. ignoreBorder: true,
  11949. createQuadrilaterals: true
  11950. });
  11951. }
  11952. render() {
  11953. if (!this.data.hasPopup) {
  11954. this._createPopup(null, this.data);
  11955. }
  11956. if (this.quadrilaterals) {
  11957. return this._renderQuadrilaterals("underlineAnnotation");
  11958. }
  11959. this.container.className = "underlineAnnotation";
  11960. return this.container;
  11961. }
  11962. }
  11963. class SquigglyAnnotationElement extends AnnotationElement {
  11964. constructor(parameters) {
  11965. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11966. super(parameters, {
  11967. isRenderable,
  11968. ignoreBorder: true,
  11969. createQuadrilaterals: true
  11970. });
  11971. }
  11972. render() {
  11973. if (!this.data.hasPopup) {
  11974. this._createPopup(null, this.data);
  11975. }
  11976. if (this.quadrilaterals) {
  11977. return this._renderQuadrilaterals("squigglyAnnotation");
  11978. }
  11979. this.container.className = "squigglyAnnotation";
  11980. return this.container;
  11981. }
  11982. }
  11983. class StrikeOutAnnotationElement extends AnnotationElement {
  11984. constructor(parameters) {
  11985. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11986. super(parameters, {
  11987. isRenderable,
  11988. ignoreBorder: true,
  11989. createQuadrilaterals: true
  11990. });
  11991. }
  11992. render() {
  11993. if (!this.data.hasPopup) {
  11994. this._createPopup(null, this.data);
  11995. }
  11996. if (this.quadrilaterals) {
  11997. return this._renderQuadrilaterals("strikeoutAnnotation");
  11998. }
  11999. this.container.className = "strikeoutAnnotation";
  12000. return this.container;
  12001. }
  12002. }
  12003. class StampAnnotationElement extends AnnotationElement {
  12004. constructor(parameters) {
  12005. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12006. super(parameters, {
  12007. isRenderable,
  12008. ignoreBorder: true
  12009. });
  12010. }
  12011. render() {
  12012. this.container.className = "stampAnnotation";
  12013. if (!this.data.hasPopup) {
  12014. this._createPopup(null, this.data);
  12015. }
  12016. return this.container;
  12017. }
  12018. }
  12019. class FileAttachmentAnnotationElement extends AnnotationElement {
  12020. constructor(parameters) {
  12021. super(parameters, {
  12022. isRenderable: true
  12023. });
  12024. const {
  12025. filename,
  12026. content
  12027. } = this.data.file;
  12028. this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true);
  12029. this.content = content;
  12030. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  12031. source: this,
  12032. filename,
  12033. content
  12034. });
  12035. }
  12036. render() {
  12037. this.container.className = "fileAttachmentAnnotation";
  12038. const trigger = document.createElement("div");
  12039. trigger.className = "popupTriggerArea";
  12040. trigger.addEventListener("dblclick", this._download.bind(this));
  12041. if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
  12042. this._createPopup(trigger, this.data);
  12043. }
  12044. this.container.append(trigger);
  12045. return this.container;
  12046. }
  12047. _download() {
  12048. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  12049. }
  12050. }
  12051. class AnnotationLayer {
  12052. static #appendElement(element, id, div, accessibilityManager) {
  12053. const contentElement = element.firstChild || element;
  12054. contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
  12055. div.append(element);
  12056. accessibilityManager?.moveElementInDOM(div, element, contentElement, false);
  12057. }
  12058. static render(parameters) {
  12059. const {
  12060. annotations,
  12061. div,
  12062. viewport,
  12063. accessibilityManager
  12064. } = parameters;
  12065. this.#setDimensions(div, viewport);
  12066. let zIndex = 0;
  12067. for (const data of annotations) {
  12068. if (data.annotationType !== _util.AnnotationType.POPUP) {
  12069. const {
  12070. width,
  12071. height
  12072. } = getRectDims(data.rect);
  12073. if (width <= 0 || height <= 0) {
  12074. continue;
  12075. }
  12076. }
  12077. const element = AnnotationElementFactory.create({
  12078. data,
  12079. layer: div,
  12080. page: parameters.page,
  12081. viewport,
  12082. linkService: parameters.linkService,
  12083. downloadManager: parameters.downloadManager,
  12084. imageResourcesPath: parameters.imageResourcesPath || "",
  12085. renderForms: parameters.renderForms !== false,
  12086. svgFactory: new _display_utils.DOMSVGFactory(),
  12087. annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
  12088. enableScripting: parameters.enableScripting,
  12089. hasJSActions: parameters.hasJSActions,
  12090. fieldObjects: parameters.fieldObjects,
  12091. mouseState: parameters.mouseState || {
  12092. isDown: false
  12093. }
  12094. });
  12095. if (element.isRenderable) {
  12096. const rendered = element.render();
  12097. if (data.hidden) {
  12098. rendered.style.visibility = "hidden";
  12099. }
  12100. if (Array.isArray(rendered)) {
  12101. for (const renderedElement of rendered) {
  12102. renderedElement.style.zIndex = zIndex++;
  12103. AnnotationLayer.#appendElement(renderedElement, data.id, div, accessibilityManager);
  12104. }
  12105. } else {
  12106. rendered.style.zIndex = zIndex++;
  12107. if (element instanceof PopupAnnotationElement) {
  12108. div.prepend(rendered);
  12109. } else {
  12110. AnnotationLayer.#appendElement(rendered, data.id, div, accessibilityManager);
  12111. }
  12112. }
  12113. }
  12114. }
  12115. this.#setAnnotationCanvasMap(div, parameters.annotationCanvasMap);
  12116. }
  12117. static update(parameters) {
  12118. const {
  12119. annotationCanvasMap,
  12120. div,
  12121. viewport
  12122. } = parameters;
  12123. this.#setDimensions(div, viewport);
  12124. this.#setAnnotationCanvasMap(div, annotationCanvasMap);
  12125. div.hidden = false;
  12126. }
  12127. static #setDimensions(div, {
  12128. width,
  12129. height,
  12130. rotation
  12131. }) {
  12132. const {
  12133. style
  12134. } = div;
  12135. const flipOrientation = rotation % 180 !== 0,
  12136. widthStr = Math.floor(width) + "px",
  12137. heightStr = Math.floor(height) + "px";
  12138. style.width = flipOrientation ? heightStr : widthStr;
  12139. style.height = flipOrientation ? widthStr : heightStr;
  12140. div.setAttribute("data-main-rotation", rotation);
  12141. }
  12142. static #setAnnotationCanvasMap(div, annotationCanvasMap) {
  12143. if (!annotationCanvasMap) {
  12144. return;
  12145. }
  12146. for (const [id, canvas] of annotationCanvasMap) {
  12147. const element = div.querySelector(`[data-annotation-id="${id}"]`);
  12148. if (!element) {
  12149. continue;
  12150. }
  12151. const {
  12152. firstChild
  12153. } = element;
  12154. if (!firstChild) {
  12155. element.append(canvas);
  12156. } else if (firstChild.nodeName === "CANVAS") {
  12157. firstChild.replaceWith(canvas);
  12158. } else {
  12159. firstChild.before(canvas);
  12160. }
  12161. }
  12162. annotationCanvasMap.clear();
  12163. }
  12164. }
  12165. exports.AnnotationLayer = AnnotationLayer;
  12166. /***/ }),
  12167. /* 27 */
  12168. /***/ ((__unused_webpack_module, exports) => {
  12169. Object.defineProperty(exports, "__esModule", ({
  12170. value: true
  12171. }));
  12172. exports.ColorConverters = void 0;
  12173. function makeColorComp(n) {
  12174. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  12175. }
  12176. class ColorConverters {
  12177. static CMYK_G([c, y, m, k]) {
  12178. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  12179. }
  12180. static G_CMYK([g]) {
  12181. return ["CMYK", 0, 0, 0, 1 - g];
  12182. }
  12183. static G_RGB([g]) {
  12184. return ["RGB", g, g, g];
  12185. }
  12186. static G_HTML([g]) {
  12187. const G = makeColorComp(g);
  12188. return `#${G}${G}${G}`;
  12189. }
  12190. static RGB_G([r, g, b]) {
  12191. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  12192. }
  12193. static RGB_HTML([r, g, b]) {
  12194. const R = makeColorComp(r);
  12195. const G = makeColorComp(g);
  12196. const B = makeColorComp(b);
  12197. return `#${R}${G}${B}`;
  12198. }
  12199. static T_HTML() {
  12200. return "#00000000";
  12201. }
  12202. static CMYK_RGB([c, y, m, k]) {
  12203. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  12204. }
  12205. static CMYK_HTML(components) {
  12206. const rgb = this.CMYK_RGB(components).slice(1);
  12207. return this.RGB_HTML(rgb);
  12208. }
  12209. static RGB_CMYK([r, g, b]) {
  12210. const c = 1 - r;
  12211. const m = 1 - g;
  12212. const y = 1 - b;
  12213. const k = Math.min(c, m, y);
  12214. return ["CMYK", c, m, y, k];
  12215. }
  12216. }
  12217. exports.ColorConverters = ColorConverters;
  12218. /***/ }),
  12219. /* 28 */
  12220. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12221. Object.defineProperty(exports, "__esModule", ({
  12222. value: true
  12223. }));
  12224. exports.XfaLayer = void 0;
  12225. var _xfa_text = __w_pdfjs_require__(19);
  12226. class XfaLayer {
  12227. static setupStorage(html, id, element, storage, intent) {
  12228. const storedData = storage.getValue(id, {
  12229. value: null
  12230. });
  12231. switch (element.name) {
  12232. case "textarea":
  12233. if (storedData.value !== null) {
  12234. html.textContent = storedData.value;
  12235. }
  12236. if (intent === "print") {
  12237. break;
  12238. }
  12239. html.addEventListener("input", event => {
  12240. storage.setValue(id, {
  12241. value: event.target.value
  12242. });
  12243. });
  12244. break;
  12245. case "input":
  12246. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  12247. if (storedData.value === element.attributes.xfaOn) {
  12248. html.setAttribute("checked", true);
  12249. } else if (storedData.value === element.attributes.xfaOff) {
  12250. html.removeAttribute("checked");
  12251. }
  12252. if (intent === "print") {
  12253. break;
  12254. }
  12255. html.addEventListener("change", event => {
  12256. storage.setValue(id, {
  12257. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  12258. });
  12259. });
  12260. } else {
  12261. if (storedData.value !== null) {
  12262. html.setAttribute("value", storedData.value);
  12263. }
  12264. if (intent === "print") {
  12265. break;
  12266. }
  12267. html.addEventListener("input", event => {
  12268. storage.setValue(id, {
  12269. value: event.target.value
  12270. });
  12271. });
  12272. }
  12273. break;
  12274. case "select":
  12275. if (storedData.value !== null) {
  12276. for (const option of element.children) {
  12277. if (option.attributes.value === storedData.value) {
  12278. option.attributes.selected = true;
  12279. }
  12280. }
  12281. }
  12282. html.addEventListener("input", event => {
  12283. const options = event.target.options;
  12284. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  12285. storage.setValue(id, {
  12286. value
  12287. });
  12288. });
  12289. break;
  12290. }
  12291. }
  12292. static setAttributes({
  12293. html,
  12294. element,
  12295. storage = null,
  12296. intent,
  12297. linkService
  12298. }) {
  12299. const {
  12300. attributes
  12301. } = element;
  12302. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  12303. if (attributes.type === "radio") {
  12304. attributes.name = `${attributes.name}-${intent}`;
  12305. }
  12306. for (const [key, value] of Object.entries(attributes)) {
  12307. if (value === null || value === undefined) {
  12308. continue;
  12309. }
  12310. switch (key) {
  12311. case "class":
  12312. if (value.length) {
  12313. html.setAttribute(key, value.join(" "));
  12314. }
  12315. break;
  12316. case "dataId":
  12317. break;
  12318. case "id":
  12319. html.setAttribute("data-element-id", value);
  12320. break;
  12321. case "style":
  12322. Object.assign(html.style, value);
  12323. break;
  12324. case "textContent":
  12325. html.textContent = value;
  12326. break;
  12327. default:
  12328. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  12329. html.setAttribute(key, value);
  12330. }
  12331. }
  12332. }
  12333. if (isHTMLAnchorElement) {
  12334. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  12335. }
  12336. if (storage && attributes.dataId) {
  12337. this.setupStorage(html, attributes.dataId, element, storage);
  12338. }
  12339. }
  12340. static render(parameters) {
  12341. const storage = parameters.annotationStorage;
  12342. const linkService = parameters.linkService;
  12343. const root = parameters.xfaHtml;
  12344. const intent = parameters.intent || "display";
  12345. const rootHtml = document.createElement(root.name);
  12346. if (root.attributes) {
  12347. this.setAttributes({
  12348. html: rootHtml,
  12349. element: root,
  12350. intent,
  12351. linkService
  12352. });
  12353. }
  12354. const stack = [[root, -1, rootHtml]];
  12355. const rootDiv = parameters.div;
  12356. rootDiv.append(rootHtml);
  12357. if (parameters.viewport) {
  12358. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12359. rootDiv.style.transform = transform;
  12360. }
  12361. if (intent !== "richText") {
  12362. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  12363. }
  12364. const textDivs = [];
  12365. while (stack.length > 0) {
  12366. const [parent, i, html] = stack.at(-1);
  12367. if (i + 1 === parent.children.length) {
  12368. stack.pop();
  12369. continue;
  12370. }
  12371. const child = parent.children[++stack.at(-1)[1]];
  12372. if (child === null) {
  12373. continue;
  12374. }
  12375. const {
  12376. name
  12377. } = child;
  12378. if (name === "#text") {
  12379. const node = document.createTextNode(child.value);
  12380. textDivs.push(node);
  12381. html.append(node);
  12382. continue;
  12383. }
  12384. let childHtml;
  12385. if (child?.attributes?.xmlns) {
  12386. childHtml = document.createElementNS(child.attributes.xmlns, name);
  12387. } else {
  12388. childHtml = document.createElement(name);
  12389. }
  12390. html.append(childHtml);
  12391. if (child.attributes) {
  12392. this.setAttributes({
  12393. html: childHtml,
  12394. element: child,
  12395. storage,
  12396. intent,
  12397. linkService
  12398. });
  12399. }
  12400. if (child.children && child.children.length > 0) {
  12401. stack.push([child, -1, childHtml]);
  12402. } else if (child.value) {
  12403. const node = document.createTextNode(child.value);
  12404. if (_xfa_text.XfaText.shouldBuildText(name)) {
  12405. textDivs.push(node);
  12406. }
  12407. childHtml.append(node);
  12408. }
  12409. }
  12410. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  12411. el.setAttribute("readOnly", true);
  12412. }
  12413. return {
  12414. textDivs
  12415. };
  12416. }
  12417. static update(parameters) {
  12418. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12419. parameters.div.style.transform = transform;
  12420. parameters.div.hidden = false;
  12421. }
  12422. }
  12423. exports.XfaLayer = XfaLayer;
  12424. /***/ }),
  12425. /* 29 */
  12426. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12427. Object.defineProperty(exports, "__esModule", ({
  12428. value: true
  12429. }));
  12430. exports.TextLayerRenderTask = void 0;
  12431. exports.renderTextLayer = renderTextLayer;
  12432. var _util = __w_pdfjs_require__(1);
  12433. var _display_utils = __w_pdfjs_require__(6);
  12434. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  12435. const DEFAULT_FONT_SIZE = 30;
  12436. const DEFAULT_FONT_ASCENT = 0.8;
  12437. const ascentCache = new Map();
  12438. function getAscent(fontFamily, ctx) {
  12439. const cachedAscent = ascentCache.get(fontFamily);
  12440. if (cachedAscent) {
  12441. return cachedAscent;
  12442. }
  12443. ctx.save();
  12444. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  12445. const metrics = ctx.measureText("");
  12446. let ascent = metrics.fontBoundingBoxAscent;
  12447. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  12448. if (ascent) {
  12449. ctx.restore();
  12450. const ratio = ascent / (ascent + descent);
  12451. ascentCache.set(fontFamily, ratio);
  12452. return ratio;
  12453. }
  12454. ctx.strokeStyle = "red";
  12455. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12456. ctx.strokeText("g", 0, 0);
  12457. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12458. descent = 0;
  12459. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  12460. if (pixels[i] > 0) {
  12461. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  12462. break;
  12463. }
  12464. }
  12465. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12466. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  12467. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12468. ascent = 0;
  12469. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  12470. if (pixels[i] > 0) {
  12471. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  12472. break;
  12473. }
  12474. }
  12475. ctx.restore();
  12476. if (ascent) {
  12477. const ratio = ascent / (ascent + descent);
  12478. ascentCache.set(fontFamily, ratio);
  12479. return ratio;
  12480. }
  12481. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  12482. return DEFAULT_FONT_ASCENT;
  12483. }
  12484. function appendText(task, geom, styles, ctx) {
  12485. const textDiv = document.createElement("span");
  12486. const textDivProperties = {
  12487. angle: 0,
  12488. canvasWidth: 0,
  12489. hasText: geom.str !== "",
  12490. hasEOL: geom.hasEOL,
  12491. fontSize: 0
  12492. };
  12493. task._textDivs.push(textDiv);
  12494. const tx = _util.Util.transform(task._viewport.transform, geom.transform);
  12495. let angle = Math.atan2(tx[1], tx[0]);
  12496. const style = styles[geom.fontName];
  12497. if (style.vertical) {
  12498. angle += Math.PI / 2;
  12499. }
  12500. const fontHeight = Math.hypot(tx[2], tx[3]);
  12501. const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
  12502. let left, top;
  12503. if (angle === 0) {
  12504. left = tx[4];
  12505. top = tx[5] - fontAscent;
  12506. } else {
  12507. left = tx[4] + fontAscent * Math.sin(angle);
  12508. top = tx[5] - fontAscent * Math.cos(angle);
  12509. }
  12510. textDiv.style.left = `${left}px`;
  12511. textDiv.style.top = `${top}px`;
  12512. textDiv.style.fontSize = `${fontHeight}px`;
  12513. textDiv.style.fontFamily = style.fontFamily;
  12514. textDivProperties.fontSize = fontHeight;
  12515. textDiv.setAttribute("role", "presentation");
  12516. textDiv.textContent = geom.str;
  12517. textDiv.dir = geom.dir;
  12518. if (task._fontInspectorEnabled) {
  12519. textDiv.dataset.fontName = geom.fontName;
  12520. }
  12521. if (angle !== 0) {
  12522. textDivProperties.angle = angle * (180 / Math.PI);
  12523. }
  12524. let shouldScaleText = false;
  12525. if (geom.str.length > 1) {
  12526. shouldScaleText = true;
  12527. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  12528. const absScaleX = Math.abs(geom.transform[0]),
  12529. absScaleY = Math.abs(geom.transform[3]);
  12530. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  12531. shouldScaleText = true;
  12532. }
  12533. }
  12534. if (shouldScaleText) {
  12535. if (style.vertical) {
  12536. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  12537. } else {
  12538. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  12539. }
  12540. }
  12541. task._textDivProperties.set(textDiv, textDivProperties);
  12542. if (task._textContentStream) {
  12543. task._layoutText(textDiv);
  12544. }
  12545. }
  12546. function render(task) {
  12547. if (task._canceled) {
  12548. return;
  12549. }
  12550. const textDivs = task._textDivs;
  12551. const capability = task._capability;
  12552. const textDivsLength = textDivs.length;
  12553. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  12554. task._renderingDone = true;
  12555. capability.resolve();
  12556. return;
  12557. }
  12558. if (!task._textContentStream) {
  12559. for (const textDiv of textDivs) {
  12560. task._layoutText(textDiv);
  12561. }
  12562. }
  12563. task._renderingDone = true;
  12564. capability.resolve();
  12565. }
  12566. class TextLayerRenderTask {
  12567. constructor({
  12568. textContent,
  12569. textContentStream,
  12570. container,
  12571. viewport,
  12572. textDivs,
  12573. textContentItemsStr
  12574. }) {
  12575. this._textContent = textContent;
  12576. this._textContentStream = textContentStream;
  12577. this._container = container;
  12578. this._document = container.ownerDocument;
  12579. this._viewport = viewport;
  12580. this._textDivs = textDivs || [];
  12581. this._textContentItemsStr = textContentItemsStr || [];
  12582. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  12583. this._reader = null;
  12584. this._layoutTextLastFontSize = null;
  12585. this._layoutTextLastFontFamily = null;
  12586. this._layoutTextCtx = null;
  12587. this._textDivProperties = new WeakMap();
  12588. this._renderingDone = false;
  12589. this._canceled = false;
  12590. this._capability = (0, _util.createPromiseCapability)();
  12591. this._renderTimer = null;
  12592. this._devicePixelRatio = globalThis.devicePixelRatio || 1;
  12593. this._capability.promise.finally(() => {
  12594. this._textDivProperties = null;
  12595. if (this._layoutTextCtx) {
  12596. this._layoutTextCtx.canvas.width = 0;
  12597. this._layoutTextCtx.canvas.height = 0;
  12598. this._layoutTextCtx = null;
  12599. }
  12600. }).catch(() => {});
  12601. }
  12602. get promise() {
  12603. return this._capability.promise;
  12604. }
  12605. cancel() {
  12606. this._canceled = true;
  12607. if (this._reader) {
  12608. this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
  12609. this._reader = null;
  12610. }
  12611. if (this._renderTimer !== null) {
  12612. clearTimeout(this._renderTimer);
  12613. this._renderTimer = null;
  12614. }
  12615. this._capability.reject(new Error("TextLayer task cancelled."));
  12616. }
  12617. _processItems(items, styleCache) {
  12618. for (const item of items) {
  12619. if (item.str === undefined) {
  12620. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  12621. const parent = this._container;
  12622. this._container = document.createElement("span");
  12623. this._container.classList.add("markedContent");
  12624. if (item.id !== null) {
  12625. this._container.setAttribute("id", `${item.id}`);
  12626. }
  12627. parent.append(this._container);
  12628. } else if (item.type === "endMarkedContent") {
  12629. this._container = this._container.parentNode;
  12630. }
  12631. continue;
  12632. }
  12633. this._textContentItemsStr.push(item.str);
  12634. appendText(this, item, styleCache, this._layoutTextCtx);
  12635. }
  12636. }
  12637. _layoutText(textDiv) {
  12638. const textDivProperties = this._textDivProperties.get(textDiv);
  12639. let transform = "";
  12640. if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
  12641. const {
  12642. fontFamily
  12643. } = textDiv.style;
  12644. const {
  12645. fontSize
  12646. } = textDivProperties;
  12647. if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
  12648. this._layoutTextCtx.font = `${fontSize * this._devicePixelRatio}px ${fontFamily}`;
  12649. this._layoutTextLastFontSize = fontSize;
  12650. this._layoutTextLastFontFamily = fontFamily;
  12651. }
  12652. const {
  12653. width
  12654. } = this._layoutTextCtx.measureText(textDiv.textContent);
  12655. if (width > 0) {
  12656. transform = `scaleX(${this._devicePixelRatio * textDivProperties.canvasWidth / width})`;
  12657. }
  12658. }
  12659. if (textDivProperties.angle !== 0) {
  12660. transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
  12661. }
  12662. if (transform.length > 0) {
  12663. textDiv.style.transform = transform;
  12664. }
  12665. if (textDivProperties.hasText) {
  12666. this._container.append(textDiv);
  12667. }
  12668. if (textDivProperties.hasEOL) {
  12669. const br = document.createElement("br");
  12670. br.setAttribute("role", "presentation");
  12671. this._container.append(br);
  12672. }
  12673. }
  12674. _render(timeout = 0) {
  12675. const capability = (0, _util.createPromiseCapability)();
  12676. let styleCache = Object.create(null);
  12677. const canvas = this._document.createElement("canvas");
  12678. canvas.height = canvas.width = DEFAULT_FONT_SIZE;
  12679. this._layoutTextCtx = canvas.getContext("2d", {
  12680. alpha: false
  12681. });
  12682. if (this._textContent) {
  12683. const textItems = this._textContent.items;
  12684. const textStyles = this._textContent.styles;
  12685. this._processItems(textItems, textStyles);
  12686. capability.resolve();
  12687. } else if (this._textContentStream) {
  12688. const pump = () => {
  12689. this._reader.read().then(({
  12690. value,
  12691. done
  12692. }) => {
  12693. if (done) {
  12694. capability.resolve();
  12695. return;
  12696. }
  12697. Object.assign(styleCache, value.styles);
  12698. this._processItems(value.items, styleCache);
  12699. pump();
  12700. }, capability.reject);
  12701. };
  12702. this._reader = this._textContentStream.getReader();
  12703. pump();
  12704. } else {
  12705. throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');
  12706. }
  12707. capability.promise.then(() => {
  12708. styleCache = null;
  12709. if (!timeout) {
  12710. render(this);
  12711. } else {
  12712. (0, _display_utils.deprecated)("The TextLayerRender `timeout` parameter will be removed in the " + "future, since streaming of textContent has made it obsolete.");
  12713. this._renderTimer = setTimeout(() => {
  12714. render(this);
  12715. this._renderTimer = null;
  12716. }, timeout);
  12717. }
  12718. }, this._capability.reject);
  12719. }
  12720. }
  12721. exports.TextLayerRenderTask = TextLayerRenderTask;
  12722. function renderTextLayer(renderParameters) {
  12723. const task = new TextLayerRenderTask({
  12724. textContent: renderParameters.textContent,
  12725. textContentStream: renderParameters.textContentStream,
  12726. container: renderParameters.container,
  12727. viewport: renderParameters.viewport,
  12728. textDivs: renderParameters.textDivs,
  12729. textContentItemsStr: renderParameters.textContentItemsStr
  12730. });
  12731. task._render(renderParameters.timeout);
  12732. return task;
  12733. }
  12734. /***/ }),
  12735. /* 30 */
  12736. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12737. Object.defineProperty(exports, "__esModule", ({
  12738. value: true
  12739. }));
  12740. exports.SVGGraphics = void 0;
  12741. var _display_utils = __w_pdfjs_require__(6);
  12742. var _util = __w_pdfjs_require__(1);
  12743. var _is_node = __w_pdfjs_require__(12);
  12744. let SVGGraphics = class {
  12745. constructor() {
  12746. (0, _util.unreachable)("Not implemented: SVGGraphics");
  12747. }
  12748. };
  12749. exports.SVGGraphics = SVGGraphics;
  12750. {
  12751. const SVG_DEFAULTS = {
  12752. fontStyle: "normal",
  12753. fontWeight: "normal",
  12754. fillColor: "#000000"
  12755. };
  12756. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  12757. const XLINK_NS = "http://www.w3.org/1999/xlink";
  12758. const LINE_CAP_STYLES = ["butt", "round", "square"];
  12759. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  12760. const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
  12761. if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
  12762. return URL.createObjectURL(new Blob([data], {
  12763. type: contentType
  12764. }));
  12765. }
  12766. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  12767. let buffer = `data:${contentType};base64,`;
  12768. for (let i = 0, ii = data.length; i < ii; i += 3) {
  12769. const b1 = data[i] & 0xff;
  12770. const b2 = data[i + 1] & 0xff;
  12771. const b3 = data[i + 2] & 0xff;
  12772. const d1 = b1 >> 2,
  12773. d2 = (b1 & 3) << 4 | b2 >> 4;
  12774. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  12775. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  12776. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  12777. }
  12778. return buffer;
  12779. };
  12780. const convertImgDataToPng = function () {
  12781. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  12782. const CHUNK_WRAPPER_SIZE = 12;
  12783. const crcTable = new Int32Array(256);
  12784. for (let i = 0; i < 256; i++) {
  12785. let c = i;
  12786. for (let h = 0; h < 8; h++) {
  12787. if (c & 1) {
  12788. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  12789. } else {
  12790. c = c >> 1 & 0x7fffffff;
  12791. }
  12792. }
  12793. crcTable[i] = c;
  12794. }
  12795. function crc32(data, start, end) {
  12796. let crc = -1;
  12797. for (let i = start; i < end; i++) {
  12798. const a = (crc ^ data[i]) & 0xff;
  12799. const b = crcTable[a];
  12800. crc = crc >>> 8 ^ b;
  12801. }
  12802. return crc ^ -1;
  12803. }
  12804. function writePngChunk(type, body, data, offset) {
  12805. let p = offset;
  12806. const len = body.length;
  12807. data[p] = len >> 24 & 0xff;
  12808. data[p + 1] = len >> 16 & 0xff;
  12809. data[p + 2] = len >> 8 & 0xff;
  12810. data[p + 3] = len & 0xff;
  12811. p += 4;
  12812. data[p] = type.charCodeAt(0) & 0xff;
  12813. data[p + 1] = type.charCodeAt(1) & 0xff;
  12814. data[p + 2] = type.charCodeAt(2) & 0xff;
  12815. data[p + 3] = type.charCodeAt(3) & 0xff;
  12816. p += 4;
  12817. data.set(body, p);
  12818. p += body.length;
  12819. const crc = crc32(data, offset + 4, p);
  12820. data[p] = crc >> 24 & 0xff;
  12821. data[p + 1] = crc >> 16 & 0xff;
  12822. data[p + 2] = crc >> 8 & 0xff;
  12823. data[p + 3] = crc & 0xff;
  12824. }
  12825. function adler32(data, start, end) {
  12826. let a = 1;
  12827. let b = 0;
  12828. for (let i = start; i < end; ++i) {
  12829. a = (a + (data[i] & 0xff)) % 65521;
  12830. b = (b + a) % 65521;
  12831. }
  12832. return b << 16 | a;
  12833. }
  12834. function deflateSync(literals) {
  12835. if (!_is_node.isNodeJS) {
  12836. return deflateSyncUncompressed(literals);
  12837. }
  12838. try {
  12839. let input;
  12840. if (parseInt(process.versions.node) >= 8) {
  12841. input = literals;
  12842. } else {
  12843. input = Buffer.from(literals);
  12844. }
  12845. const output = require("zlib").deflateSync(input, {
  12846. level: 9
  12847. });
  12848. return output instanceof Uint8Array ? output : new Uint8Array(output);
  12849. } catch (e) {
  12850. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  12851. }
  12852. return deflateSyncUncompressed(literals);
  12853. }
  12854. function deflateSyncUncompressed(literals) {
  12855. let len = literals.length;
  12856. const maxBlockLength = 0xffff;
  12857. const deflateBlocks = Math.ceil(len / maxBlockLength);
  12858. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  12859. let pi = 0;
  12860. idat[pi++] = 0x78;
  12861. idat[pi++] = 0x9c;
  12862. let pos = 0;
  12863. while (len > maxBlockLength) {
  12864. idat[pi++] = 0x00;
  12865. idat[pi++] = 0xff;
  12866. idat[pi++] = 0xff;
  12867. idat[pi++] = 0x00;
  12868. idat[pi++] = 0x00;
  12869. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  12870. pi += maxBlockLength;
  12871. pos += maxBlockLength;
  12872. len -= maxBlockLength;
  12873. }
  12874. idat[pi++] = 0x01;
  12875. idat[pi++] = len & 0xff;
  12876. idat[pi++] = len >> 8 & 0xff;
  12877. idat[pi++] = ~len & 0xffff & 0xff;
  12878. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  12879. idat.set(literals.subarray(pos), pi);
  12880. pi += literals.length - pos;
  12881. const adler = adler32(literals, 0, literals.length);
  12882. idat[pi++] = adler >> 24 & 0xff;
  12883. idat[pi++] = adler >> 16 & 0xff;
  12884. idat[pi++] = adler >> 8 & 0xff;
  12885. idat[pi++] = adler & 0xff;
  12886. return idat;
  12887. }
  12888. function encode(imgData, kind, forceDataSchema, isMask) {
  12889. const width = imgData.width;
  12890. const height = imgData.height;
  12891. let bitDepth, colorType, lineSize;
  12892. const bytes = imgData.data;
  12893. switch (kind) {
  12894. case _util.ImageKind.GRAYSCALE_1BPP:
  12895. colorType = 0;
  12896. bitDepth = 1;
  12897. lineSize = width + 7 >> 3;
  12898. break;
  12899. case _util.ImageKind.RGB_24BPP:
  12900. colorType = 2;
  12901. bitDepth = 8;
  12902. lineSize = width * 3;
  12903. break;
  12904. case _util.ImageKind.RGBA_32BPP:
  12905. colorType = 6;
  12906. bitDepth = 8;
  12907. lineSize = width * 4;
  12908. break;
  12909. default:
  12910. throw new Error("invalid format");
  12911. }
  12912. const literals = new Uint8Array((1 + lineSize) * height);
  12913. let offsetLiterals = 0,
  12914. offsetBytes = 0;
  12915. for (let y = 0; y < height; ++y) {
  12916. literals[offsetLiterals++] = 0;
  12917. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  12918. offsetBytes += lineSize;
  12919. offsetLiterals += lineSize;
  12920. }
  12921. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  12922. offsetLiterals = 0;
  12923. for (let y = 0; y < height; y++) {
  12924. offsetLiterals++;
  12925. for (let i = 0; i < lineSize; i++) {
  12926. literals[offsetLiterals++] ^= 0xff;
  12927. }
  12928. }
  12929. }
  12930. 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]);
  12931. const idat = deflateSync(literals);
  12932. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  12933. const data = new Uint8Array(pngLength);
  12934. let offset = 0;
  12935. data.set(PNG_HEADER, offset);
  12936. offset += PNG_HEADER.length;
  12937. writePngChunk("IHDR", ihdr, data, offset);
  12938. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  12939. writePngChunk("IDATA", idat, data, offset);
  12940. offset += CHUNK_WRAPPER_SIZE + idat.length;
  12941. writePngChunk("IEND", new Uint8Array(0), data, offset);
  12942. return createObjectURL(data, "image/png", forceDataSchema);
  12943. }
  12944. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  12945. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  12946. return encode(imgData, kind, forceDataSchema, isMask);
  12947. };
  12948. }();
  12949. class SVGExtraState {
  12950. constructor() {
  12951. this.fontSizeScale = 1;
  12952. this.fontWeight = SVG_DEFAULTS.fontWeight;
  12953. this.fontSize = 0;
  12954. this.textMatrix = _util.IDENTITY_MATRIX;
  12955. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  12956. this.leading = 0;
  12957. this.textRenderingMode = _util.TextRenderingMode.FILL;
  12958. this.textMatrixScale = 1;
  12959. this.x = 0;
  12960. this.y = 0;
  12961. this.lineX = 0;
  12962. this.lineY = 0;
  12963. this.charSpacing = 0;
  12964. this.wordSpacing = 0;
  12965. this.textHScale = 1;
  12966. this.textRise = 0;
  12967. this.fillColor = SVG_DEFAULTS.fillColor;
  12968. this.strokeColor = "#000000";
  12969. this.fillAlpha = 1;
  12970. this.strokeAlpha = 1;
  12971. this.lineWidth = 1;
  12972. this.lineJoin = "";
  12973. this.lineCap = "";
  12974. this.miterLimit = 0;
  12975. this.dashArray = [];
  12976. this.dashPhase = 0;
  12977. this.dependencies = [];
  12978. this.activeClipUrl = null;
  12979. this.clipGroup = null;
  12980. this.maskId = "";
  12981. }
  12982. clone() {
  12983. return Object.create(this);
  12984. }
  12985. setCurrentPoint(x, y) {
  12986. this.x = x;
  12987. this.y = y;
  12988. }
  12989. }
  12990. function opListToTree(opList) {
  12991. let opTree = [];
  12992. const tmp = [];
  12993. for (const opListElement of opList) {
  12994. if (opListElement.fn === "save") {
  12995. opTree.push({
  12996. fnId: 92,
  12997. fn: "group",
  12998. items: []
  12999. });
  13000. tmp.push(opTree);
  13001. opTree = opTree.at(-1).items;
  13002. continue;
  13003. }
  13004. if (opListElement.fn === "restore") {
  13005. opTree = tmp.pop();
  13006. } else {
  13007. opTree.push(opListElement);
  13008. }
  13009. }
  13010. return opTree;
  13011. }
  13012. function pf(value) {
  13013. if (Number.isInteger(value)) {
  13014. return value.toString();
  13015. }
  13016. const s = value.toFixed(10);
  13017. let i = s.length - 1;
  13018. if (s[i] !== "0") {
  13019. return s;
  13020. }
  13021. do {
  13022. i--;
  13023. } while (s[i] === "0");
  13024. return s.substring(0, s[i] === "." ? i : i + 1);
  13025. }
  13026. function pm(m) {
  13027. if (m[4] === 0 && m[5] === 0) {
  13028. if (m[1] === 0 && m[2] === 0) {
  13029. if (m[0] === 1 && m[3] === 1) {
  13030. return "";
  13031. }
  13032. return `scale(${pf(m[0])} ${pf(m[3])})`;
  13033. }
  13034. if (m[0] === m[3] && m[1] === -m[2]) {
  13035. const a = Math.acos(m[0]) * 180 / Math.PI;
  13036. return `rotate(${pf(a)})`;
  13037. }
  13038. } else {
  13039. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  13040. return `translate(${pf(m[4])} ${pf(m[5])})`;
  13041. }
  13042. }
  13043. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  13044. }
  13045. let clipCount = 0;
  13046. let maskCount = 0;
  13047. let shadingCount = 0;
  13048. exports.SVGGraphics = SVGGraphics = class {
  13049. constructor(commonObjs, objs, forceDataSchema = false) {
  13050. (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
  13051. this.svgFactory = new _display_utils.DOMSVGFactory();
  13052. this.current = new SVGExtraState();
  13053. this.transformMatrix = _util.IDENTITY_MATRIX;
  13054. this.transformStack = [];
  13055. this.extraStack = [];
  13056. this.commonObjs = commonObjs;
  13057. this.objs = objs;
  13058. this.pendingClip = null;
  13059. this.pendingEOFill = false;
  13060. this.embedFonts = false;
  13061. this.embeddedFonts = Object.create(null);
  13062. this.cssStyle = null;
  13063. this.forceDataSchema = !!forceDataSchema;
  13064. this._operatorIdMapping = [];
  13065. for (const op in _util.OPS) {
  13066. this._operatorIdMapping[_util.OPS[op]] = op;
  13067. }
  13068. }
  13069. getObject(data, fallback = null) {
  13070. if (typeof data === "string") {
  13071. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  13072. }
  13073. return fallback;
  13074. }
  13075. save() {
  13076. this.transformStack.push(this.transformMatrix);
  13077. const old = this.current;
  13078. this.extraStack.push(old);
  13079. this.current = old.clone();
  13080. }
  13081. restore() {
  13082. this.transformMatrix = this.transformStack.pop();
  13083. this.current = this.extraStack.pop();
  13084. this.pendingClip = null;
  13085. this.tgrp = null;
  13086. }
  13087. group(items) {
  13088. this.save();
  13089. this.executeOpTree(items);
  13090. this.restore();
  13091. }
  13092. loadDependencies(operatorList) {
  13093. const fnArray = operatorList.fnArray;
  13094. const argsArray = operatorList.argsArray;
  13095. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13096. if (fnArray[i] !== _util.OPS.dependency) {
  13097. continue;
  13098. }
  13099. for (const obj of argsArray[i]) {
  13100. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  13101. const promise = new Promise(resolve => {
  13102. objsPool.get(obj, resolve);
  13103. });
  13104. this.current.dependencies.push(promise);
  13105. }
  13106. }
  13107. return Promise.all(this.current.dependencies);
  13108. }
  13109. transform(a, b, c, d, e, f) {
  13110. const transformMatrix = [a, b, c, d, e, f];
  13111. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  13112. this.tgrp = null;
  13113. }
  13114. getSVG(operatorList, viewport) {
  13115. this.viewport = viewport;
  13116. const svgElement = this._initialize(viewport);
  13117. return this.loadDependencies(operatorList).then(() => {
  13118. this.transformMatrix = _util.IDENTITY_MATRIX;
  13119. this.executeOpTree(this.convertOpList(operatorList));
  13120. return svgElement;
  13121. });
  13122. }
  13123. convertOpList(operatorList) {
  13124. const operatorIdMapping = this._operatorIdMapping;
  13125. const argsArray = operatorList.argsArray;
  13126. const fnArray = operatorList.fnArray;
  13127. const opList = [];
  13128. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13129. const fnId = fnArray[i];
  13130. opList.push({
  13131. fnId,
  13132. fn: operatorIdMapping[fnId],
  13133. args: argsArray[i]
  13134. });
  13135. }
  13136. return opListToTree(opList);
  13137. }
  13138. executeOpTree(opTree) {
  13139. for (const opTreeElement of opTree) {
  13140. const fn = opTreeElement.fn;
  13141. const fnId = opTreeElement.fnId;
  13142. const args = opTreeElement.args;
  13143. switch (fnId | 0) {
  13144. case _util.OPS.beginText:
  13145. this.beginText();
  13146. break;
  13147. case _util.OPS.dependency:
  13148. break;
  13149. case _util.OPS.setLeading:
  13150. this.setLeading(args);
  13151. break;
  13152. case _util.OPS.setLeadingMoveText:
  13153. this.setLeadingMoveText(args[0], args[1]);
  13154. break;
  13155. case _util.OPS.setFont:
  13156. this.setFont(args);
  13157. break;
  13158. case _util.OPS.showText:
  13159. this.showText(args[0]);
  13160. break;
  13161. case _util.OPS.showSpacedText:
  13162. this.showText(args[0]);
  13163. break;
  13164. case _util.OPS.endText:
  13165. this.endText();
  13166. break;
  13167. case _util.OPS.moveText:
  13168. this.moveText(args[0], args[1]);
  13169. break;
  13170. case _util.OPS.setCharSpacing:
  13171. this.setCharSpacing(args[0]);
  13172. break;
  13173. case _util.OPS.setWordSpacing:
  13174. this.setWordSpacing(args[0]);
  13175. break;
  13176. case _util.OPS.setHScale:
  13177. this.setHScale(args[0]);
  13178. break;
  13179. case _util.OPS.setTextMatrix:
  13180. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  13181. break;
  13182. case _util.OPS.setTextRise:
  13183. this.setTextRise(args[0]);
  13184. break;
  13185. case _util.OPS.setTextRenderingMode:
  13186. this.setTextRenderingMode(args[0]);
  13187. break;
  13188. case _util.OPS.setLineWidth:
  13189. this.setLineWidth(args[0]);
  13190. break;
  13191. case _util.OPS.setLineJoin:
  13192. this.setLineJoin(args[0]);
  13193. break;
  13194. case _util.OPS.setLineCap:
  13195. this.setLineCap(args[0]);
  13196. break;
  13197. case _util.OPS.setMiterLimit:
  13198. this.setMiterLimit(args[0]);
  13199. break;
  13200. case _util.OPS.setFillRGBColor:
  13201. this.setFillRGBColor(args[0], args[1], args[2]);
  13202. break;
  13203. case _util.OPS.setStrokeRGBColor:
  13204. this.setStrokeRGBColor(args[0], args[1], args[2]);
  13205. break;
  13206. case _util.OPS.setStrokeColorN:
  13207. this.setStrokeColorN(args);
  13208. break;
  13209. case _util.OPS.setFillColorN:
  13210. this.setFillColorN(args);
  13211. break;
  13212. case _util.OPS.shadingFill:
  13213. this.shadingFill(args[0]);
  13214. break;
  13215. case _util.OPS.setDash:
  13216. this.setDash(args[0], args[1]);
  13217. break;
  13218. case _util.OPS.setRenderingIntent:
  13219. this.setRenderingIntent(args[0]);
  13220. break;
  13221. case _util.OPS.setFlatness:
  13222. this.setFlatness(args[0]);
  13223. break;
  13224. case _util.OPS.setGState:
  13225. this.setGState(args[0]);
  13226. break;
  13227. case _util.OPS.fill:
  13228. this.fill();
  13229. break;
  13230. case _util.OPS.eoFill:
  13231. this.eoFill();
  13232. break;
  13233. case _util.OPS.stroke:
  13234. this.stroke();
  13235. break;
  13236. case _util.OPS.fillStroke:
  13237. this.fillStroke();
  13238. break;
  13239. case _util.OPS.eoFillStroke:
  13240. this.eoFillStroke();
  13241. break;
  13242. case _util.OPS.clip:
  13243. this.clip("nonzero");
  13244. break;
  13245. case _util.OPS.eoClip:
  13246. this.clip("evenodd");
  13247. break;
  13248. case _util.OPS.paintSolidColorImageMask:
  13249. this.paintSolidColorImageMask();
  13250. break;
  13251. case _util.OPS.paintImageXObject:
  13252. this.paintImageXObject(args[0]);
  13253. break;
  13254. case _util.OPS.paintInlineImageXObject:
  13255. this.paintInlineImageXObject(args[0]);
  13256. break;
  13257. case _util.OPS.paintImageMaskXObject:
  13258. this.paintImageMaskXObject(args[0]);
  13259. break;
  13260. case _util.OPS.paintFormXObjectBegin:
  13261. this.paintFormXObjectBegin(args[0], args[1]);
  13262. break;
  13263. case _util.OPS.paintFormXObjectEnd:
  13264. this.paintFormXObjectEnd();
  13265. break;
  13266. case _util.OPS.closePath:
  13267. this.closePath();
  13268. break;
  13269. case _util.OPS.closeStroke:
  13270. this.closeStroke();
  13271. break;
  13272. case _util.OPS.closeFillStroke:
  13273. this.closeFillStroke();
  13274. break;
  13275. case _util.OPS.closeEOFillStroke:
  13276. this.closeEOFillStroke();
  13277. break;
  13278. case _util.OPS.nextLine:
  13279. this.nextLine();
  13280. break;
  13281. case _util.OPS.transform:
  13282. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  13283. break;
  13284. case _util.OPS.constructPath:
  13285. this.constructPath(args[0], args[1]);
  13286. break;
  13287. case _util.OPS.endPath:
  13288. this.endPath();
  13289. break;
  13290. case 92:
  13291. this.group(opTreeElement.items);
  13292. break;
  13293. default:
  13294. (0, _util.warn)(`Unimplemented operator ${fn}`);
  13295. break;
  13296. }
  13297. }
  13298. }
  13299. setWordSpacing(wordSpacing) {
  13300. this.current.wordSpacing = wordSpacing;
  13301. }
  13302. setCharSpacing(charSpacing) {
  13303. this.current.charSpacing = charSpacing;
  13304. }
  13305. nextLine() {
  13306. this.moveText(0, this.current.leading);
  13307. }
  13308. setTextMatrix(a, b, c, d, e, f) {
  13309. const current = this.current;
  13310. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  13311. current.textMatrixScale = Math.hypot(a, b);
  13312. current.x = current.lineX = 0;
  13313. current.y = current.lineY = 0;
  13314. current.xcoords = [];
  13315. current.ycoords = [];
  13316. current.tspan = this.svgFactory.createElement("svg:tspan");
  13317. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13318. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13319. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13320. current.txtElement = this.svgFactory.createElement("svg:text");
  13321. current.txtElement.append(current.tspan);
  13322. }
  13323. beginText() {
  13324. const current = this.current;
  13325. current.x = current.lineX = 0;
  13326. current.y = current.lineY = 0;
  13327. current.textMatrix = _util.IDENTITY_MATRIX;
  13328. current.lineMatrix = _util.IDENTITY_MATRIX;
  13329. current.textMatrixScale = 1;
  13330. current.tspan = this.svgFactory.createElement("svg:tspan");
  13331. current.txtElement = this.svgFactory.createElement("svg:text");
  13332. current.txtgrp = this.svgFactory.createElement("svg:g");
  13333. current.xcoords = [];
  13334. current.ycoords = [];
  13335. }
  13336. moveText(x, y) {
  13337. const current = this.current;
  13338. current.x = current.lineX += x;
  13339. current.y = current.lineY += y;
  13340. current.xcoords = [];
  13341. current.ycoords = [];
  13342. current.tspan = this.svgFactory.createElement("svg:tspan");
  13343. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13344. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13345. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13346. }
  13347. showText(glyphs) {
  13348. const current = this.current;
  13349. const font = current.font;
  13350. const fontSize = current.fontSize;
  13351. if (fontSize === 0) {
  13352. return;
  13353. }
  13354. const fontSizeScale = current.fontSizeScale;
  13355. const charSpacing = current.charSpacing;
  13356. const wordSpacing = current.wordSpacing;
  13357. const fontDirection = current.fontDirection;
  13358. const textHScale = current.textHScale * fontDirection;
  13359. const vertical = font.vertical;
  13360. const spacingDir = vertical ? 1 : -1;
  13361. const defaultVMetrics = font.defaultVMetrics;
  13362. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  13363. let x = 0;
  13364. for (const glyph of glyphs) {
  13365. if (glyph === null) {
  13366. x += fontDirection * wordSpacing;
  13367. continue;
  13368. } else if (typeof glyph === "number") {
  13369. x += spacingDir * glyph * fontSize / 1000;
  13370. continue;
  13371. }
  13372. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  13373. const character = glyph.fontChar;
  13374. let scaledX, scaledY;
  13375. let width = glyph.width;
  13376. if (vertical) {
  13377. let vx;
  13378. const vmetric = glyph.vmetric || defaultVMetrics;
  13379. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  13380. vx = -vx * widthAdvanceScale;
  13381. const vy = vmetric[2] * widthAdvanceScale;
  13382. width = vmetric ? -vmetric[0] : width;
  13383. scaledX = vx / fontSizeScale;
  13384. scaledY = (x + vy) / fontSizeScale;
  13385. } else {
  13386. scaledX = x / fontSizeScale;
  13387. scaledY = 0;
  13388. }
  13389. if (glyph.isInFont || font.missingFile) {
  13390. current.xcoords.push(current.x + scaledX);
  13391. if (vertical) {
  13392. current.ycoords.push(-current.y + scaledY);
  13393. }
  13394. current.tspan.textContent += character;
  13395. } else {}
  13396. let charWidth;
  13397. if (vertical) {
  13398. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  13399. } else {
  13400. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  13401. }
  13402. x += charWidth;
  13403. }
  13404. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  13405. if (vertical) {
  13406. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  13407. } else {
  13408. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13409. }
  13410. if (vertical) {
  13411. current.y -= x;
  13412. } else {
  13413. current.x += x * textHScale;
  13414. }
  13415. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13416. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13417. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  13418. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  13419. }
  13420. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  13421. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  13422. }
  13423. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  13424. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  13425. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  13426. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  13427. }
  13428. if (current.fillAlpha < 1) {
  13429. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  13430. }
  13431. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  13432. current.tspan.setAttributeNS(null, "fill", "transparent");
  13433. } else {
  13434. current.tspan.setAttributeNS(null, "fill", "none");
  13435. }
  13436. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  13437. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  13438. this._setStrokeAttributes(current.tspan, lineWidthScale);
  13439. }
  13440. let textMatrix = current.textMatrix;
  13441. if (current.textRise !== 0) {
  13442. textMatrix = textMatrix.slice();
  13443. textMatrix[5] += current.textRise;
  13444. }
  13445. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  13446. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  13447. current.txtElement.append(current.tspan);
  13448. current.txtgrp.append(current.txtElement);
  13449. this._ensureTransformGroup().append(current.txtElement);
  13450. }
  13451. setLeadingMoveText(x, y) {
  13452. this.setLeading(-y);
  13453. this.moveText(x, y);
  13454. }
  13455. addFontStyle(fontObj) {
  13456. if (!fontObj.data) {
  13457. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  13458. }
  13459. if (!this.cssStyle) {
  13460. this.cssStyle = this.svgFactory.createElement("svg:style");
  13461. this.cssStyle.setAttributeNS(null, "type", "text/css");
  13462. this.defs.append(this.cssStyle);
  13463. }
  13464. const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  13465. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  13466. }
  13467. setFont(details) {
  13468. const current = this.current;
  13469. const fontObj = this.commonObjs.get(details[0]);
  13470. let size = details[1];
  13471. current.font = fontObj;
  13472. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  13473. this.addFontStyle(fontObj);
  13474. this.embeddedFonts[fontObj.loadedName] = fontObj;
  13475. }
  13476. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  13477. let bold = "normal";
  13478. if (fontObj.black) {
  13479. bold = "900";
  13480. } else if (fontObj.bold) {
  13481. bold = "bold";
  13482. }
  13483. const italic = fontObj.italic ? "italic" : "normal";
  13484. if (size < 0) {
  13485. size = -size;
  13486. current.fontDirection = -1;
  13487. } else {
  13488. current.fontDirection = 1;
  13489. }
  13490. current.fontSize = size;
  13491. current.fontFamily = fontObj.loadedName;
  13492. current.fontWeight = bold;
  13493. current.fontStyle = italic;
  13494. current.tspan = this.svgFactory.createElement("svg:tspan");
  13495. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13496. current.xcoords = [];
  13497. current.ycoords = [];
  13498. }
  13499. endText() {
  13500. const current = this.current;
  13501. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  13502. current.element = current.txtElement;
  13503. this.clip("nonzero");
  13504. this.endPath();
  13505. }
  13506. }
  13507. setLineWidth(width) {
  13508. if (width > 0) {
  13509. this.current.lineWidth = width;
  13510. }
  13511. }
  13512. setLineCap(style) {
  13513. this.current.lineCap = LINE_CAP_STYLES[style];
  13514. }
  13515. setLineJoin(style) {
  13516. this.current.lineJoin = LINE_JOIN_STYLES[style];
  13517. }
  13518. setMiterLimit(limit) {
  13519. this.current.miterLimit = limit;
  13520. }
  13521. setStrokeAlpha(strokeAlpha) {
  13522. this.current.strokeAlpha = strokeAlpha;
  13523. }
  13524. setStrokeRGBColor(r, g, b) {
  13525. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  13526. }
  13527. setFillAlpha(fillAlpha) {
  13528. this.current.fillAlpha = fillAlpha;
  13529. }
  13530. setFillRGBColor(r, g, b) {
  13531. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  13532. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  13533. this.current.xcoords = [];
  13534. this.current.ycoords = [];
  13535. }
  13536. setStrokeColorN(args) {
  13537. this.current.strokeColor = this._makeColorN_Pattern(args);
  13538. }
  13539. setFillColorN(args) {
  13540. this.current.fillColor = this._makeColorN_Pattern(args);
  13541. }
  13542. shadingFill(args) {
  13543. const width = this.viewport.width;
  13544. const height = this.viewport.height;
  13545. const inv = _util.Util.inverseTransform(this.transformMatrix);
  13546. const bl = _util.Util.applyTransform([0, 0], inv);
  13547. const br = _util.Util.applyTransform([0, height], inv);
  13548. const ul = _util.Util.applyTransform([width, 0], inv);
  13549. const ur = _util.Util.applyTransform([width, height], inv);
  13550. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  13551. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  13552. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  13553. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  13554. const rect = this.svgFactory.createElement("svg:rect");
  13555. rect.setAttributeNS(null, "x", x0);
  13556. rect.setAttributeNS(null, "y", y0);
  13557. rect.setAttributeNS(null, "width", x1 - x0);
  13558. rect.setAttributeNS(null, "height", y1 - y0);
  13559. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  13560. if (this.current.fillAlpha < 1) {
  13561. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  13562. }
  13563. this._ensureTransformGroup().append(rect);
  13564. }
  13565. _makeColorN_Pattern(args) {
  13566. if (args[0] === "TilingPattern") {
  13567. return this._makeTilingPattern(args);
  13568. }
  13569. return this._makeShadingPattern(args);
  13570. }
  13571. _makeTilingPattern(args) {
  13572. const color = args[1];
  13573. const operatorList = args[2];
  13574. const matrix = args[3] || _util.IDENTITY_MATRIX;
  13575. const [x0, y0, x1, y1] = args[4];
  13576. const xstep = args[5];
  13577. const ystep = args[6];
  13578. const paintType = args[7];
  13579. const tilingId = `shading${shadingCount++}`;
  13580. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  13581. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  13582. const txstep = xstep * xscale;
  13583. const tystep = ystep * yscale;
  13584. const tiling = this.svgFactory.createElement("svg:pattern");
  13585. tiling.setAttributeNS(null, "id", tilingId);
  13586. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  13587. tiling.setAttributeNS(null, "width", txstep);
  13588. tiling.setAttributeNS(null, "height", tystep);
  13589. tiling.setAttributeNS(null, "x", `${tx0}`);
  13590. tiling.setAttributeNS(null, "y", `${ty0}`);
  13591. const svg = this.svg;
  13592. const transformMatrix = this.transformMatrix;
  13593. const fillColor = this.current.fillColor;
  13594. const strokeColor = this.current.strokeColor;
  13595. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  13596. this.svg = bbox;
  13597. this.transformMatrix = matrix;
  13598. if (paintType === 2) {
  13599. const cssColor = _util.Util.makeHexColor(...color);
  13600. this.current.fillColor = cssColor;
  13601. this.current.strokeColor = cssColor;
  13602. }
  13603. this.executeOpTree(this.convertOpList(operatorList));
  13604. this.svg = svg;
  13605. this.transformMatrix = transformMatrix;
  13606. this.current.fillColor = fillColor;
  13607. this.current.strokeColor = strokeColor;
  13608. tiling.append(bbox.childNodes[0]);
  13609. this.defs.append(tiling);
  13610. return `url(#${tilingId})`;
  13611. }
  13612. _makeShadingPattern(args) {
  13613. if (typeof args === "string") {
  13614. args = this.objs.get(args);
  13615. }
  13616. switch (args[0]) {
  13617. case "RadialAxial":
  13618. const shadingId = `shading${shadingCount++}`;
  13619. const colorStops = args[3];
  13620. let gradient;
  13621. switch (args[1]) {
  13622. case "axial":
  13623. const point0 = args[4];
  13624. const point1 = args[5];
  13625. gradient = this.svgFactory.createElement("svg:linearGradient");
  13626. gradient.setAttributeNS(null, "id", shadingId);
  13627. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  13628. gradient.setAttributeNS(null, "x1", point0[0]);
  13629. gradient.setAttributeNS(null, "y1", point0[1]);
  13630. gradient.setAttributeNS(null, "x2", point1[0]);
  13631. gradient.setAttributeNS(null, "y2", point1[1]);
  13632. break;
  13633. case "radial":
  13634. const focalPoint = args[4];
  13635. const circlePoint = args[5];
  13636. const focalRadius = args[6];
  13637. const circleRadius = args[7];
  13638. gradient = this.svgFactory.createElement("svg:radialGradient");
  13639. gradient.setAttributeNS(null, "id", shadingId);
  13640. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  13641. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  13642. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  13643. gradient.setAttributeNS(null, "r", circleRadius);
  13644. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  13645. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  13646. gradient.setAttributeNS(null, "fr", focalRadius);
  13647. break;
  13648. default:
  13649. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  13650. }
  13651. for (const colorStop of colorStops) {
  13652. const stop = this.svgFactory.createElement("svg:stop");
  13653. stop.setAttributeNS(null, "offset", colorStop[0]);
  13654. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  13655. gradient.append(stop);
  13656. }
  13657. this.defs.append(gradient);
  13658. return `url(#${shadingId})`;
  13659. case "Mesh":
  13660. (0, _util.warn)("Unimplemented pattern Mesh");
  13661. return null;
  13662. case "Dummy":
  13663. return "hotpink";
  13664. default:
  13665. throw new Error(`Unknown IR type: ${args[0]}`);
  13666. }
  13667. }
  13668. setDash(dashArray, dashPhase) {
  13669. this.current.dashArray = dashArray;
  13670. this.current.dashPhase = dashPhase;
  13671. }
  13672. constructPath(ops, args) {
  13673. const current = this.current;
  13674. let x = current.x,
  13675. y = current.y;
  13676. let d = [];
  13677. let j = 0;
  13678. for (const op of ops) {
  13679. switch (op | 0) {
  13680. case _util.OPS.rectangle:
  13681. x = args[j++];
  13682. y = args[j++];
  13683. const width = args[j++];
  13684. const height = args[j++];
  13685. const xw = x + width;
  13686. const yh = y + height;
  13687. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  13688. break;
  13689. case _util.OPS.moveTo:
  13690. x = args[j++];
  13691. y = args[j++];
  13692. d.push("M", pf(x), pf(y));
  13693. break;
  13694. case _util.OPS.lineTo:
  13695. x = args[j++];
  13696. y = args[j++];
  13697. d.push("L", pf(x), pf(y));
  13698. break;
  13699. case _util.OPS.curveTo:
  13700. x = args[j + 4];
  13701. y = args[j + 5];
  13702. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  13703. j += 6;
  13704. break;
  13705. case _util.OPS.curveTo2:
  13706. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  13707. x = args[j + 2];
  13708. y = args[j + 3];
  13709. j += 4;
  13710. break;
  13711. case _util.OPS.curveTo3:
  13712. x = args[j + 2];
  13713. y = args[j + 3];
  13714. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  13715. j += 4;
  13716. break;
  13717. case _util.OPS.closePath:
  13718. d.push("Z");
  13719. break;
  13720. }
  13721. }
  13722. d = d.join(" ");
  13723. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  13724. d = current.path.getAttributeNS(null, "d") + d;
  13725. } else {
  13726. current.path = this.svgFactory.createElement("svg:path");
  13727. this._ensureTransformGroup().append(current.path);
  13728. }
  13729. current.path.setAttributeNS(null, "d", d);
  13730. current.path.setAttributeNS(null, "fill", "none");
  13731. current.element = current.path;
  13732. current.setCurrentPoint(x, y);
  13733. }
  13734. endPath() {
  13735. const current = this.current;
  13736. current.path = null;
  13737. if (!this.pendingClip) {
  13738. return;
  13739. }
  13740. if (!current.element) {
  13741. this.pendingClip = null;
  13742. return;
  13743. }
  13744. const clipId = `clippath${clipCount++}`;
  13745. const clipPath = this.svgFactory.createElement("svg:clipPath");
  13746. clipPath.setAttributeNS(null, "id", clipId);
  13747. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  13748. const clipElement = current.element.cloneNode(true);
  13749. if (this.pendingClip === "evenodd") {
  13750. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  13751. } else {
  13752. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  13753. }
  13754. this.pendingClip = null;
  13755. clipPath.append(clipElement);
  13756. this.defs.append(clipPath);
  13757. if (current.activeClipUrl) {
  13758. current.clipGroup = null;
  13759. for (const prev of this.extraStack) {
  13760. prev.clipGroup = null;
  13761. }
  13762. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  13763. }
  13764. current.activeClipUrl = `url(#${clipId})`;
  13765. this.tgrp = null;
  13766. }
  13767. clip(type) {
  13768. this.pendingClip = type;
  13769. }
  13770. closePath() {
  13771. const current = this.current;
  13772. if (current.path) {
  13773. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  13774. current.path.setAttributeNS(null, "d", d);
  13775. }
  13776. }
  13777. setLeading(leading) {
  13778. this.current.leading = -leading;
  13779. }
  13780. setTextRise(textRise) {
  13781. this.current.textRise = textRise;
  13782. }
  13783. setTextRenderingMode(textRenderingMode) {
  13784. this.current.textRenderingMode = textRenderingMode;
  13785. }
  13786. setHScale(scale) {
  13787. this.current.textHScale = scale / 100;
  13788. }
  13789. setRenderingIntent(intent) {}
  13790. setFlatness(flatness) {}
  13791. setGState(states) {
  13792. for (const [key, value] of states) {
  13793. switch (key) {
  13794. case "LW":
  13795. this.setLineWidth(value);
  13796. break;
  13797. case "LC":
  13798. this.setLineCap(value);
  13799. break;
  13800. case "LJ":
  13801. this.setLineJoin(value);
  13802. break;
  13803. case "ML":
  13804. this.setMiterLimit(value);
  13805. break;
  13806. case "D":
  13807. this.setDash(value[0], value[1]);
  13808. break;
  13809. case "RI":
  13810. this.setRenderingIntent(value);
  13811. break;
  13812. case "FL":
  13813. this.setFlatness(value);
  13814. break;
  13815. case "Font":
  13816. this.setFont(value);
  13817. break;
  13818. case "CA":
  13819. this.setStrokeAlpha(value);
  13820. break;
  13821. case "ca":
  13822. this.setFillAlpha(value);
  13823. break;
  13824. default:
  13825. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  13826. break;
  13827. }
  13828. }
  13829. }
  13830. fill() {
  13831. const current = this.current;
  13832. if (current.element) {
  13833. current.element.setAttributeNS(null, "fill", current.fillColor);
  13834. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  13835. this.endPath();
  13836. }
  13837. }
  13838. stroke() {
  13839. const current = this.current;
  13840. if (current.element) {
  13841. this._setStrokeAttributes(current.element);
  13842. current.element.setAttributeNS(null, "fill", "none");
  13843. this.endPath();
  13844. }
  13845. }
  13846. _setStrokeAttributes(element, lineWidthScale = 1) {
  13847. const current = this.current;
  13848. let dashArray = current.dashArray;
  13849. if (lineWidthScale !== 1 && dashArray.length > 0) {
  13850. dashArray = dashArray.map(function (value) {
  13851. return lineWidthScale * value;
  13852. });
  13853. }
  13854. element.setAttributeNS(null, "stroke", current.strokeColor);
  13855. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  13856. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  13857. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  13858. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  13859. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  13860. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  13861. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  13862. }
  13863. eoFill() {
  13864. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  13865. this.fill();
  13866. }
  13867. fillStroke() {
  13868. this.stroke();
  13869. this.fill();
  13870. }
  13871. eoFillStroke() {
  13872. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  13873. this.fillStroke();
  13874. }
  13875. closeStroke() {
  13876. this.closePath();
  13877. this.stroke();
  13878. }
  13879. closeFillStroke() {
  13880. this.closePath();
  13881. this.fillStroke();
  13882. }
  13883. closeEOFillStroke() {
  13884. this.closePath();
  13885. this.eoFillStroke();
  13886. }
  13887. paintSolidColorImageMask() {
  13888. const rect = this.svgFactory.createElement("svg:rect");
  13889. rect.setAttributeNS(null, "x", "0");
  13890. rect.setAttributeNS(null, "y", "0");
  13891. rect.setAttributeNS(null, "width", "1px");
  13892. rect.setAttributeNS(null, "height", "1px");
  13893. rect.setAttributeNS(null, "fill", this.current.fillColor);
  13894. this._ensureTransformGroup().append(rect);
  13895. }
  13896. paintImageXObject(objId) {
  13897. const imgData = this.getObject(objId);
  13898. if (!imgData) {
  13899. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  13900. return;
  13901. }
  13902. this.paintInlineImageXObject(imgData);
  13903. }
  13904. paintInlineImageXObject(imgData, mask) {
  13905. const width = imgData.width;
  13906. const height = imgData.height;
  13907. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  13908. const cliprect = this.svgFactory.createElement("svg:rect");
  13909. cliprect.setAttributeNS(null, "x", "0");
  13910. cliprect.setAttributeNS(null, "y", "0");
  13911. cliprect.setAttributeNS(null, "width", pf(width));
  13912. cliprect.setAttributeNS(null, "height", pf(height));
  13913. this.current.element = cliprect;
  13914. this.clip("nonzero");
  13915. const imgEl = this.svgFactory.createElement("svg:image");
  13916. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  13917. imgEl.setAttributeNS(null, "x", "0");
  13918. imgEl.setAttributeNS(null, "y", pf(-height));
  13919. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  13920. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  13921. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  13922. if (mask) {
  13923. mask.append(imgEl);
  13924. } else {
  13925. this._ensureTransformGroup().append(imgEl);
  13926. }
  13927. }
  13928. paintImageMaskXObject(img) {
  13929. const imgData = this.getObject(img.data, img);
  13930. if (imgData.bitmap) {
  13931. (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
  13932. return;
  13933. }
  13934. const current = this.current;
  13935. const width = imgData.width;
  13936. const height = imgData.height;
  13937. const fillColor = current.fillColor;
  13938. current.maskId = `mask${maskCount++}`;
  13939. const mask = this.svgFactory.createElement("svg:mask");
  13940. mask.setAttributeNS(null, "id", current.maskId);
  13941. const rect = this.svgFactory.createElement("svg:rect");
  13942. rect.setAttributeNS(null, "x", "0");
  13943. rect.setAttributeNS(null, "y", "0");
  13944. rect.setAttributeNS(null, "width", pf(width));
  13945. rect.setAttributeNS(null, "height", pf(height));
  13946. rect.setAttributeNS(null, "fill", fillColor);
  13947. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  13948. this.defs.append(mask);
  13949. this._ensureTransformGroup().append(rect);
  13950. this.paintInlineImageXObject(imgData, mask);
  13951. }
  13952. paintFormXObjectBegin(matrix, bbox) {
  13953. if (Array.isArray(matrix) && matrix.length === 6) {
  13954. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  13955. }
  13956. if (bbox) {
  13957. const width = bbox[2] - bbox[0];
  13958. const height = bbox[3] - bbox[1];
  13959. const cliprect = this.svgFactory.createElement("svg:rect");
  13960. cliprect.setAttributeNS(null, "x", bbox[0]);
  13961. cliprect.setAttributeNS(null, "y", bbox[1]);
  13962. cliprect.setAttributeNS(null, "width", pf(width));
  13963. cliprect.setAttributeNS(null, "height", pf(height));
  13964. this.current.element = cliprect;
  13965. this.clip("nonzero");
  13966. this.endPath();
  13967. }
  13968. }
  13969. paintFormXObjectEnd() {}
  13970. _initialize(viewport) {
  13971. const svg = this.svgFactory.create(viewport.width, viewport.height);
  13972. const definitions = this.svgFactory.createElement("svg:defs");
  13973. svg.append(definitions);
  13974. this.defs = definitions;
  13975. const rootGroup = this.svgFactory.createElement("svg:g");
  13976. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  13977. svg.append(rootGroup);
  13978. this.svg = rootGroup;
  13979. return svg;
  13980. }
  13981. _ensureClipGroup() {
  13982. if (!this.current.clipGroup) {
  13983. const clipGroup = this.svgFactory.createElement("svg:g");
  13984. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  13985. this.svg.append(clipGroup);
  13986. this.current.clipGroup = clipGroup;
  13987. }
  13988. return this.current.clipGroup;
  13989. }
  13990. _ensureTransformGroup() {
  13991. if (!this.tgrp) {
  13992. this.tgrp = this.svgFactory.createElement("svg:g");
  13993. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  13994. if (this.current.activeClipUrl) {
  13995. this._ensureClipGroup().append(this.tgrp);
  13996. } else {
  13997. this.svg.append(this.tgrp);
  13998. }
  13999. }
  14000. return this.tgrp;
  14001. }
  14002. };
  14003. }
  14004. /***/ }),
  14005. /* 31 */
  14006. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14007. Object.defineProperty(exports, "__esModule", ({
  14008. value: true
  14009. }));
  14010. exports.PDFNodeStream = void 0;
  14011. var _util = __w_pdfjs_require__(1);
  14012. var _network_utils = __w_pdfjs_require__(32);
  14013. ;
  14014. const fs = require("fs");
  14015. const http = require("http");
  14016. const https = require("https");
  14017. const url = require("url");
  14018. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  14019. function parseUrl(sourceUrl) {
  14020. const parsedUrl = url.parse(sourceUrl);
  14021. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  14022. return parsedUrl;
  14023. }
  14024. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  14025. return url.parse(`file:///${sourceUrl}`);
  14026. }
  14027. if (!parsedUrl.host) {
  14028. parsedUrl.protocol = "file:";
  14029. }
  14030. return parsedUrl;
  14031. }
  14032. class PDFNodeStream {
  14033. constructor(source) {
  14034. this.source = source;
  14035. this.url = parseUrl(source.url);
  14036. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  14037. this.isFsUrl = this.url.protocol === "file:";
  14038. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  14039. this._fullRequestReader = null;
  14040. this._rangeRequestReaders = [];
  14041. }
  14042. get _progressiveDataLength() {
  14043. return this._fullRequestReader?._loaded ?? 0;
  14044. }
  14045. getFullReader() {
  14046. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  14047. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  14048. return this._fullRequestReader;
  14049. }
  14050. getRangeReader(start, end) {
  14051. if (end <= this._progressiveDataLength) {
  14052. return null;
  14053. }
  14054. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  14055. this._rangeRequestReaders.push(rangeReader);
  14056. return rangeReader;
  14057. }
  14058. cancelAllRequests(reason) {
  14059. this._fullRequestReader?.cancel(reason);
  14060. for (const reader of this._rangeRequestReaders.slice(0)) {
  14061. reader.cancel(reason);
  14062. }
  14063. }
  14064. }
  14065. exports.PDFNodeStream = PDFNodeStream;
  14066. class BaseFullReader {
  14067. constructor(stream) {
  14068. this._url = stream.url;
  14069. this._done = false;
  14070. this._storedError = null;
  14071. this.onProgress = null;
  14072. const source = stream.source;
  14073. this._contentLength = source.length;
  14074. this._loaded = 0;
  14075. this._filename = null;
  14076. this._disableRange = source.disableRange || false;
  14077. this._rangeChunkSize = source.rangeChunkSize;
  14078. if (!this._rangeChunkSize && !this._disableRange) {
  14079. this._disableRange = true;
  14080. }
  14081. this._isStreamingSupported = !source.disableStream;
  14082. this._isRangeSupported = !source.disableRange;
  14083. this._readableStream = null;
  14084. this._readCapability = (0, _util.createPromiseCapability)();
  14085. this._headersCapability = (0, _util.createPromiseCapability)();
  14086. }
  14087. get headersReady() {
  14088. return this._headersCapability.promise;
  14089. }
  14090. get filename() {
  14091. return this._filename;
  14092. }
  14093. get contentLength() {
  14094. return this._contentLength;
  14095. }
  14096. get isRangeSupported() {
  14097. return this._isRangeSupported;
  14098. }
  14099. get isStreamingSupported() {
  14100. return this._isStreamingSupported;
  14101. }
  14102. async read() {
  14103. await this._readCapability.promise;
  14104. if (this._done) {
  14105. return {
  14106. value: undefined,
  14107. done: true
  14108. };
  14109. }
  14110. if (this._storedError) {
  14111. throw this._storedError;
  14112. }
  14113. const chunk = this._readableStream.read();
  14114. if (chunk === null) {
  14115. this._readCapability = (0, _util.createPromiseCapability)();
  14116. return this.read();
  14117. }
  14118. this._loaded += chunk.length;
  14119. this.onProgress?.({
  14120. loaded: this._loaded,
  14121. total: this._contentLength
  14122. });
  14123. const buffer = new Uint8Array(chunk).buffer;
  14124. return {
  14125. value: buffer,
  14126. done: false
  14127. };
  14128. }
  14129. cancel(reason) {
  14130. if (!this._readableStream) {
  14131. this._error(reason);
  14132. return;
  14133. }
  14134. this._readableStream.destroy(reason);
  14135. }
  14136. _error(reason) {
  14137. this._storedError = reason;
  14138. this._readCapability.resolve();
  14139. }
  14140. _setReadableStream(readableStream) {
  14141. this._readableStream = readableStream;
  14142. readableStream.on("readable", () => {
  14143. this._readCapability.resolve();
  14144. });
  14145. readableStream.on("end", () => {
  14146. readableStream.destroy();
  14147. this._done = true;
  14148. this._readCapability.resolve();
  14149. });
  14150. readableStream.on("error", reason => {
  14151. this._error(reason);
  14152. });
  14153. if (!this._isStreamingSupported && this._isRangeSupported) {
  14154. this._error(new _util.AbortException("streaming is disabled"));
  14155. }
  14156. if (this._storedError) {
  14157. this._readableStream.destroy(this._storedError);
  14158. }
  14159. }
  14160. }
  14161. class BaseRangeReader {
  14162. constructor(stream) {
  14163. this._url = stream.url;
  14164. this._done = false;
  14165. this._storedError = null;
  14166. this.onProgress = null;
  14167. this._loaded = 0;
  14168. this._readableStream = null;
  14169. this._readCapability = (0, _util.createPromiseCapability)();
  14170. const source = stream.source;
  14171. this._isStreamingSupported = !source.disableStream;
  14172. }
  14173. get isStreamingSupported() {
  14174. return this._isStreamingSupported;
  14175. }
  14176. async read() {
  14177. await this._readCapability.promise;
  14178. if (this._done) {
  14179. return {
  14180. value: undefined,
  14181. done: true
  14182. };
  14183. }
  14184. if (this._storedError) {
  14185. throw this._storedError;
  14186. }
  14187. const chunk = this._readableStream.read();
  14188. if (chunk === null) {
  14189. this._readCapability = (0, _util.createPromiseCapability)();
  14190. return this.read();
  14191. }
  14192. this._loaded += chunk.length;
  14193. this.onProgress?.({
  14194. loaded: this._loaded
  14195. });
  14196. const buffer = new Uint8Array(chunk).buffer;
  14197. return {
  14198. value: buffer,
  14199. done: false
  14200. };
  14201. }
  14202. cancel(reason) {
  14203. if (!this._readableStream) {
  14204. this._error(reason);
  14205. return;
  14206. }
  14207. this._readableStream.destroy(reason);
  14208. }
  14209. _error(reason) {
  14210. this._storedError = reason;
  14211. this._readCapability.resolve();
  14212. }
  14213. _setReadableStream(readableStream) {
  14214. this._readableStream = readableStream;
  14215. readableStream.on("readable", () => {
  14216. this._readCapability.resolve();
  14217. });
  14218. readableStream.on("end", () => {
  14219. readableStream.destroy();
  14220. this._done = true;
  14221. this._readCapability.resolve();
  14222. });
  14223. readableStream.on("error", reason => {
  14224. this._error(reason);
  14225. });
  14226. if (this._storedError) {
  14227. this._readableStream.destroy(this._storedError);
  14228. }
  14229. }
  14230. }
  14231. function createRequestOptions(parsedUrl, headers) {
  14232. return {
  14233. protocol: parsedUrl.protocol,
  14234. auth: parsedUrl.auth,
  14235. host: parsedUrl.hostname,
  14236. port: parsedUrl.port,
  14237. path: parsedUrl.path,
  14238. method: "GET",
  14239. headers
  14240. };
  14241. }
  14242. class PDFNodeStreamFullReader extends BaseFullReader {
  14243. constructor(stream) {
  14244. super(stream);
  14245. const handleResponse = response => {
  14246. if (response.statusCode === 404) {
  14247. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14248. this._storedError = error;
  14249. this._headersCapability.reject(error);
  14250. return;
  14251. }
  14252. this._headersCapability.resolve();
  14253. this._setReadableStream(response);
  14254. const getResponseHeader = name => {
  14255. return this._readableStream.headers[name.toLowerCase()];
  14256. };
  14257. const {
  14258. allowRangeRequests,
  14259. suggestedLength
  14260. } = (0, _network_utils.validateRangeRequestCapabilities)({
  14261. getResponseHeader,
  14262. isHttp: stream.isHttp,
  14263. rangeChunkSize: this._rangeChunkSize,
  14264. disableRange: this._disableRange
  14265. });
  14266. this._isRangeSupported = allowRangeRequests;
  14267. this._contentLength = suggestedLength || this._contentLength;
  14268. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  14269. };
  14270. this._request = null;
  14271. if (this._url.protocol === "http:") {
  14272. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14273. } else {
  14274. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14275. }
  14276. this._request.on("error", reason => {
  14277. this._storedError = reason;
  14278. this._headersCapability.reject(reason);
  14279. });
  14280. this._request.end();
  14281. }
  14282. }
  14283. class PDFNodeStreamRangeReader extends BaseRangeReader {
  14284. constructor(stream, start, end) {
  14285. super(stream);
  14286. this._httpHeaders = {};
  14287. for (const property in stream.httpHeaders) {
  14288. const value = stream.httpHeaders[property];
  14289. if (typeof value === "undefined") {
  14290. continue;
  14291. }
  14292. this._httpHeaders[property] = value;
  14293. }
  14294. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  14295. const handleResponse = response => {
  14296. if (response.statusCode === 404) {
  14297. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14298. this._storedError = error;
  14299. return;
  14300. }
  14301. this._setReadableStream(response);
  14302. };
  14303. this._request = null;
  14304. if (this._url.protocol === "http:") {
  14305. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14306. } else {
  14307. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14308. }
  14309. this._request.on("error", reason => {
  14310. this._storedError = reason;
  14311. });
  14312. this._request.end();
  14313. }
  14314. }
  14315. class PDFNodeStreamFsFullReader extends BaseFullReader {
  14316. constructor(stream) {
  14317. super(stream);
  14318. let path = decodeURIComponent(this._url.path);
  14319. if (fileUriRegex.test(this._url.href)) {
  14320. path = path.replace(/^\//, "");
  14321. }
  14322. fs.lstat(path, (error, stat) => {
  14323. if (error) {
  14324. if (error.code === "ENOENT") {
  14325. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  14326. }
  14327. this._storedError = error;
  14328. this._headersCapability.reject(error);
  14329. return;
  14330. }
  14331. this._contentLength = stat.size;
  14332. this._setReadableStream(fs.createReadStream(path));
  14333. this._headersCapability.resolve();
  14334. });
  14335. }
  14336. }
  14337. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  14338. constructor(stream, start, end) {
  14339. super(stream);
  14340. let path = decodeURIComponent(this._url.path);
  14341. if (fileUriRegex.test(this._url.href)) {
  14342. path = path.replace(/^\//, "");
  14343. }
  14344. this._setReadableStream(fs.createReadStream(path, {
  14345. start,
  14346. end: end - 1
  14347. }));
  14348. }
  14349. }
  14350. /***/ }),
  14351. /* 32 */
  14352. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14353. Object.defineProperty(exports, "__esModule", ({
  14354. value: true
  14355. }));
  14356. exports.createResponseStatusError = createResponseStatusError;
  14357. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  14358. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  14359. exports.validateResponseStatus = validateResponseStatus;
  14360. var _util = __w_pdfjs_require__(1);
  14361. var _content_disposition = __w_pdfjs_require__(33);
  14362. var _display_utils = __w_pdfjs_require__(6);
  14363. function validateRangeRequestCapabilities({
  14364. getResponseHeader,
  14365. isHttp,
  14366. rangeChunkSize,
  14367. disableRange
  14368. }) {
  14369. const returnValues = {
  14370. allowRangeRequests: false,
  14371. suggestedLength: undefined
  14372. };
  14373. const length = parseInt(getResponseHeader("Content-Length"), 10);
  14374. if (!Number.isInteger(length)) {
  14375. return returnValues;
  14376. }
  14377. returnValues.suggestedLength = length;
  14378. if (length <= 2 * rangeChunkSize) {
  14379. return returnValues;
  14380. }
  14381. if (disableRange || !isHttp) {
  14382. return returnValues;
  14383. }
  14384. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  14385. return returnValues;
  14386. }
  14387. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  14388. if (contentEncoding !== "identity") {
  14389. return returnValues;
  14390. }
  14391. returnValues.allowRangeRequests = true;
  14392. return returnValues;
  14393. }
  14394. function extractFilenameFromHeader(getResponseHeader) {
  14395. const contentDisposition = getResponseHeader("Content-Disposition");
  14396. if (contentDisposition) {
  14397. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  14398. if (filename.includes("%")) {
  14399. try {
  14400. filename = decodeURIComponent(filename);
  14401. } catch (ex) {}
  14402. }
  14403. if ((0, _display_utils.isPdfFile)(filename)) {
  14404. return filename;
  14405. }
  14406. }
  14407. return null;
  14408. }
  14409. function createResponseStatusError(status, url) {
  14410. if (status === 404 || status === 0 && url.startsWith("file:")) {
  14411. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  14412. }
  14413. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  14414. }
  14415. function validateResponseStatus(status) {
  14416. return status === 200 || status === 206;
  14417. }
  14418. /***/ }),
  14419. /* 33 */
  14420. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14421. Object.defineProperty(exports, "__esModule", ({
  14422. value: true
  14423. }));
  14424. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  14425. var _util = __w_pdfjs_require__(1);
  14426. function getFilenameFromContentDispositionHeader(contentDisposition) {
  14427. let needsEncodingFixup = true;
  14428. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  14429. if (tmp) {
  14430. tmp = tmp[1];
  14431. let filename = rfc2616unquote(tmp);
  14432. filename = unescape(filename);
  14433. filename = rfc5987decode(filename);
  14434. filename = rfc2047decode(filename);
  14435. return fixupEncoding(filename);
  14436. }
  14437. tmp = rfc2231getparam(contentDisposition);
  14438. if (tmp) {
  14439. const filename = rfc2047decode(tmp);
  14440. return fixupEncoding(filename);
  14441. }
  14442. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  14443. if (tmp) {
  14444. tmp = tmp[1];
  14445. let filename = rfc2616unquote(tmp);
  14446. filename = rfc2047decode(filename);
  14447. return fixupEncoding(filename);
  14448. }
  14449. function toParamRegExp(attributePattern, flags) {
  14450. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  14451. }
  14452. function textdecode(encoding, value) {
  14453. if (encoding) {
  14454. if (!/^[\x00-\xFF]+$/.test(value)) {
  14455. return value;
  14456. }
  14457. try {
  14458. const decoder = new TextDecoder(encoding, {
  14459. fatal: true
  14460. });
  14461. const buffer = (0, _util.stringToBytes)(value);
  14462. value = decoder.decode(buffer);
  14463. needsEncodingFixup = false;
  14464. } catch (e) {}
  14465. }
  14466. return value;
  14467. }
  14468. function fixupEncoding(value) {
  14469. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  14470. value = textdecode("utf-8", value);
  14471. if (needsEncodingFixup) {
  14472. value = textdecode("iso-8859-1", value);
  14473. }
  14474. }
  14475. return value;
  14476. }
  14477. function rfc2231getparam(contentDispositionStr) {
  14478. const matches = [];
  14479. let match;
  14480. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  14481. while ((match = iter.exec(contentDispositionStr)) !== null) {
  14482. let [, n, quot, part] = match;
  14483. n = parseInt(n, 10);
  14484. if (n in matches) {
  14485. if (n === 0) {
  14486. break;
  14487. }
  14488. continue;
  14489. }
  14490. matches[n] = [quot, part];
  14491. }
  14492. const parts = [];
  14493. for (let n = 0; n < matches.length; ++n) {
  14494. if (!(n in matches)) {
  14495. break;
  14496. }
  14497. let [quot, part] = matches[n];
  14498. part = rfc2616unquote(part);
  14499. if (quot) {
  14500. part = unescape(part);
  14501. if (n === 0) {
  14502. part = rfc5987decode(part);
  14503. }
  14504. }
  14505. parts.push(part);
  14506. }
  14507. return parts.join("");
  14508. }
  14509. function rfc2616unquote(value) {
  14510. if (value.startsWith('"')) {
  14511. const parts = value.slice(1).split('\\"');
  14512. for (let i = 0; i < parts.length; ++i) {
  14513. const quotindex = parts[i].indexOf('"');
  14514. if (quotindex !== -1) {
  14515. parts[i] = parts[i].slice(0, quotindex);
  14516. parts.length = i + 1;
  14517. }
  14518. parts[i] = parts[i].replace(/\\(.)/g, "$1");
  14519. }
  14520. value = parts.join('"');
  14521. }
  14522. return value;
  14523. }
  14524. function rfc5987decode(extvalue) {
  14525. const encodingend = extvalue.indexOf("'");
  14526. if (encodingend === -1) {
  14527. return extvalue;
  14528. }
  14529. const encoding = extvalue.slice(0, encodingend);
  14530. const langvalue = extvalue.slice(encodingend + 1);
  14531. const value = langvalue.replace(/^[^']*'/, "");
  14532. return textdecode(encoding, value);
  14533. }
  14534. function rfc2047decode(value) {
  14535. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  14536. return value;
  14537. }
  14538. return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  14539. if (encoding === "q" || encoding === "Q") {
  14540. text = text.replace(/_/g, " ");
  14541. text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  14542. return String.fromCharCode(parseInt(hex, 16));
  14543. });
  14544. return textdecode(charset, text);
  14545. }
  14546. try {
  14547. text = atob(text);
  14548. } catch (e) {}
  14549. return textdecode(charset, text);
  14550. });
  14551. }
  14552. return "";
  14553. }
  14554. /***/ }),
  14555. /* 34 */
  14556. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14557. Object.defineProperty(exports, "__esModule", ({
  14558. value: true
  14559. }));
  14560. exports.PDFNetworkStream = void 0;
  14561. var _util = __w_pdfjs_require__(1);
  14562. var _network_utils = __w_pdfjs_require__(32);
  14563. ;
  14564. const OK_RESPONSE = 200;
  14565. const PARTIAL_CONTENT_RESPONSE = 206;
  14566. function getArrayBuffer(xhr) {
  14567. const data = xhr.response;
  14568. if (typeof data !== "string") {
  14569. return data;
  14570. }
  14571. const array = (0, _util.stringToBytes)(data);
  14572. return array.buffer;
  14573. }
  14574. class NetworkManager {
  14575. constructor(url, args = {}) {
  14576. this.url = url;
  14577. this.isHttp = /^https?:/i.test(url);
  14578. this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
  14579. this.withCredentials = args.withCredentials || false;
  14580. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  14581. return new XMLHttpRequest();
  14582. };
  14583. this.currXhrId = 0;
  14584. this.pendingRequests = Object.create(null);
  14585. }
  14586. requestRange(begin, end, listeners) {
  14587. const args = {
  14588. begin,
  14589. end
  14590. };
  14591. for (const prop in listeners) {
  14592. args[prop] = listeners[prop];
  14593. }
  14594. return this.request(args);
  14595. }
  14596. requestFull(listeners) {
  14597. return this.request(listeners);
  14598. }
  14599. request(args) {
  14600. const xhr = this.getXhr();
  14601. const xhrId = this.currXhrId++;
  14602. const pendingRequest = this.pendingRequests[xhrId] = {
  14603. xhr
  14604. };
  14605. xhr.open("GET", this.url);
  14606. xhr.withCredentials = this.withCredentials;
  14607. for (const property in this.httpHeaders) {
  14608. const value = this.httpHeaders[property];
  14609. if (typeof value === "undefined") {
  14610. continue;
  14611. }
  14612. xhr.setRequestHeader(property, value);
  14613. }
  14614. if (this.isHttp && "begin" in args && "end" in args) {
  14615. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  14616. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  14617. } else {
  14618. pendingRequest.expectedStatus = OK_RESPONSE;
  14619. }
  14620. xhr.responseType = "arraybuffer";
  14621. if (args.onError) {
  14622. xhr.onerror = function (evt) {
  14623. args.onError(xhr.status);
  14624. };
  14625. }
  14626. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  14627. xhr.onprogress = this.onProgress.bind(this, xhrId);
  14628. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  14629. pendingRequest.onDone = args.onDone;
  14630. pendingRequest.onError = args.onError;
  14631. pendingRequest.onProgress = args.onProgress;
  14632. xhr.send(null);
  14633. return xhrId;
  14634. }
  14635. onProgress(xhrId, evt) {
  14636. const pendingRequest = this.pendingRequests[xhrId];
  14637. if (!pendingRequest) {
  14638. return;
  14639. }
  14640. pendingRequest.onProgress?.(evt);
  14641. }
  14642. onStateChange(xhrId, evt) {
  14643. const pendingRequest = this.pendingRequests[xhrId];
  14644. if (!pendingRequest) {
  14645. return;
  14646. }
  14647. const xhr = pendingRequest.xhr;
  14648. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  14649. pendingRequest.onHeadersReceived();
  14650. delete pendingRequest.onHeadersReceived;
  14651. }
  14652. if (xhr.readyState !== 4) {
  14653. return;
  14654. }
  14655. if (!(xhrId in this.pendingRequests)) {
  14656. return;
  14657. }
  14658. delete this.pendingRequests[xhrId];
  14659. if (xhr.status === 0 && this.isHttp) {
  14660. pendingRequest.onError?.(xhr.status);
  14661. return;
  14662. }
  14663. const xhrStatus = xhr.status || OK_RESPONSE;
  14664. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  14665. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  14666. pendingRequest.onError?.(xhr.status);
  14667. return;
  14668. }
  14669. const chunk = getArrayBuffer(xhr);
  14670. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  14671. const rangeHeader = xhr.getResponseHeader("Content-Range");
  14672. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  14673. pendingRequest.onDone({
  14674. begin: parseInt(matches[1], 10),
  14675. chunk
  14676. });
  14677. } else if (chunk) {
  14678. pendingRequest.onDone({
  14679. begin: 0,
  14680. chunk
  14681. });
  14682. } else {
  14683. pendingRequest.onError?.(xhr.status);
  14684. }
  14685. }
  14686. getRequestXhr(xhrId) {
  14687. return this.pendingRequests[xhrId].xhr;
  14688. }
  14689. isPendingRequest(xhrId) {
  14690. return xhrId in this.pendingRequests;
  14691. }
  14692. abortRequest(xhrId) {
  14693. const xhr = this.pendingRequests[xhrId].xhr;
  14694. delete this.pendingRequests[xhrId];
  14695. xhr.abort();
  14696. }
  14697. }
  14698. class PDFNetworkStream {
  14699. constructor(source) {
  14700. this._source = source;
  14701. this._manager = new NetworkManager(source.url, {
  14702. httpHeaders: source.httpHeaders,
  14703. withCredentials: source.withCredentials
  14704. });
  14705. this._rangeChunkSize = source.rangeChunkSize;
  14706. this._fullRequestReader = null;
  14707. this._rangeRequestReaders = [];
  14708. }
  14709. _onRangeRequestReaderClosed(reader) {
  14710. const i = this._rangeRequestReaders.indexOf(reader);
  14711. if (i >= 0) {
  14712. this._rangeRequestReaders.splice(i, 1);
  14713. }
  14714. }
  14715. getFullReader() {
  14716. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  14717. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  14718. return this._fullRequestReader;
  14719. }
  14720. getRangeReader(begin, end) {
  14721. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  14722. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  14723. this._rangeRequestReaders.push(reader);
  14724. return reader;
  14725. }
  14726. cancelAllRequests(reason) {
  14727. this._fullRequestReader?.cancel(reason);
  14728. for (const reader of this._rangeRequestReaders.slice(0)) {
  14729. reader.cancel(reason);
  14730. }
  14731. }
  14732. }
  14733. exports.PDFNetworkStream = PDFNetworkStream;
  14734. class PDFNetworkStreamFullRequestReader {
  14735. constructor(manager, source) {
  14736. this._manager = manager;
  14737. const args = {
  14738. onHeadersReceived: this._onHeadersReceived.bind(this),
  14739. onDone: this._onDone.bind(this),
  14740. onError: this._onError.bind(this),
  14741. onProgress: this._onProgress.bind(this)
  14742. };
  14743. this._url = source.url;
  14744. this._fullRequestId = manager.requestFull(args);
  14745. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  14746. this._disableRange = source.disableRange || false;
  14747. this._contentLength = source.length;
  14748. this._rangeChunkSize = source.rangeChunkSize;
  14749. if (!this._rangeChunkSize && !this._disableRange) {
  14750. this._disableRange = true;
  14751. }
  14752. this._isStreamingSupported = false;
  14753. this._isRangeSupported = false;
  14754. this._cachedChunks = [];
  14755. this._requests = [];
  14756. this._done = false;
  14757. this._storedError = undefined;
  14758. this._filename = null;
  14759. this.onProgress = null;
  14760. }
  14761. _onHeadersReceived() {
  14762. const fullRequestXhrId = this._fullRequestId;
  14763. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  14764. const getResponseHeader = name => {
  14765. return fullRequestXhr.getResponseHeader(name);
  14766. };
  14767. const {
  14768. allowRangeRequests,
  14769. suggestedLength
  14770. } = (0, _network_utils.validateRangeRequestCapabilities)({
  14771. getResponseHeader,
  14772. isHttp: this._manager.isHttp,
  14773. rangeChunkSize: this._rangeChunkSize,
  14774. disableRange: this._disableRange
  14775. });
  14776. if (allowRangeRequests) {
  14777. this._isRangeSupported = true;
  14778. }
  14779. this._contentLength = suggestedLength || this._contentLength;
  14780. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  14781. if (this._isRangeSupported) {
  14782. this._manager.abortRequest(fullRequestXhrId);
  14783. }
  14784. this._headersReceivedCapability.resolve();
  14785. }
  14786. _onDone(data) {
  14787. if (data) {
  14788. if (this._requests.length > 0) {
  14789. const requestCapability = this._requests.shift();
  14790. requestCapability.resolve({
  14791. value: data.chunk,
  14792. done: false
  14793. });
  14794. } else {
  14795. this._cachedChunks.push(data.chunk);
  14796. }
  14797. }
  14798. this._done = true;
  14799. if (this._cachedChunks.length > 0) {
  14800. return;
  14801. }
  14802. for (const requestCapability of this._requests) {
  14803. requestCapability.resolve({
  14804. value: undefined,
  14805. done: true
  14806. });
  14807. }
  14808. this._requests.length = 0;
  14809. }
  14810. _onError(status) {
  14811. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  14812. this._headersReceivedCapability.reject(this._storedError);
  14813. for (const requestCapability of this._requests) {
  14814. requestCapability.reject(this._storedError);
  14815. }
  14816. this._requests.length = 0;
  14817. this._cachedChunks.length = 0;
  14818. }
  14819. _onProgress(evt) {
  14820. this.onProgress?.({
  14821. loaded: evt.loaded,
  14822. total: evt.lengthComputable ? evt.total : this._contentLength
  14823. });
  14824. }
  14825. get filename() {
  14826. return this._filename;
  14827. }
  14828. get isRangeSupported() {
  14829. return this._isRangeSupported;
  14830. }
  14831. get isStreamingSupported() {
  14832. return this._isStreamingSupported;
  14833. }
  14834. get contentLength() {
  14835. return this._contentLength;
  14836. }
  14837. get headersReady() {
  14838. return this._headersReceivedCapability.promise;
  14839. }
  14840. async read() {
  14841. if (this._storedError) {
  14842. throw this._storedError;
  14843. }
  14844. if (this._cachedChunks.length > 0) {
  14845. const chunk = this._cachedChunks.shift();
  14846. return {
  14847. value: chunk,
  14848. done: false
  14849. };
  14850. }
  14851. if (this._done) {
  14852. return {
  14853. value: undefined,
  14854. done: true
  14855. };
  14856. }
  14857. const requestCapability = (0, _util.createPromiseCapability)();
  14858. this._requests.push(requestCapability);
  14859. return requestCapability.promise;
  14860. }
  14861. cancel(reason) {
  14862. this._done = true;
  14863. this._headersReceivedCapability.reject(reason);
  14864. for (const requestCapability of this._requests) {
  14865. requestCapability.resolve({
  14866. value: undefined,
  14867. done: true
  14868. });
  14869. }
  14870. this._requests.length = 0;
  14871. if (this._manager.isPendingRequest(this._fullRequestId)) {
  14872. this._manager.abortRequest(this._fullRequestId);
  14873. }
  14874. this._fullRequestReader = null;
  14875. }
  14876. }
  14877. class PDFNetworkStreamRangeRequestReader {
  14878. constructor(manager, begin, end) {
  14879. this._manager = manager;
  14880. const args = {
  14881. onDone: this._onDone.bind(this),
  14882. onError: this._onError.bind(this),
  14883. onProgress: this._onProgress.bind(this)
  14884. };
  14885. this._url = manager.url;
  14886. this._requestId = manager.requestRange(begin, end, args);
  14887. this._requests = [];
  14888. this._queuedChunk = null;
  14889. this._done = false;
  14890. this._storedError = undefined;
  14891. this.onProgress = null;
  14892. this.onClosed = null;
  14893. }
  14894. _close() {
  14895. this.onClosed?.(this);
  14896. }
  14897. _onDone(data) {
  14898. const chunk = data.chunk;
  14899. if (this._requests.length > 0) {
  14900. const requestCapability = this._requests.shift();
  14901. requestCapability.resolve({
  14902. value: chunk,
  14903. done: false
  14904. });
  14905. } else {
  14906. this._queuedChunk = chunk;
  14907. }
  14908. this._done = true;
  14909. for (const requestCapability of this._requests) {
  14910. requestCapability.resolve({
  14911. value: undefined,
  14912. done: true
  14913. });
  14914. }
  14915. this._requests.length = 0;
  14916. this._close();
  14917. }
  14918. _onError(status) {
  14919. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  14920. for (const requestCapability of this._requests) {
  14921. requestCapability.reject(this._storedError);
  14922. }
  14923. this._requests.length = 0;
  14924. this._queuedChunk = null;
  14925. }
  14926. _onProgress(evt) {
  14927. if (!this.isStreamingSupported) {
  14928. this.onProgress?.({
  14929. loaded: evt.loaded
  14930. });
  14931. }
  14932. }
  14933. get isStreamingSupported() {
  14934. return false;
  14935. }
  14936. async read() {
  14937. if (this._storedError) {
  14938. throw this._storedError;
  14939. }
  14940. if (this._queuedChunk !== null) {
  14941. const chunk = this._queuedChunk;
  14942. this._queuedChunk = null;
  14943. return {
  14944. value: chunk,
  14945. done: false
  14946. };
  14947. }
  14948. if (this._done) {
  14949. return {
  14950. value: undefined,
  14951. done: true
  14952. };
  14953. }
  14954. const requestCapability = (0, _util.createPromiseCapability)();
  14955. this._requests.push(requestCapability);
  14956. return requestCapability.promise;
  14957. }
  14958. cancel(reason) {
  14959. this._done = true;
  14960. for (const requestCapability of this._requests) {
  14961. requestCapability.resolve({
  14962. value: undefined,
  14963. done: true
  14964. });
  14965. }
  14966. this._requests.length = 0;
  14967. if (this._manager.isPendingRequest(this._requestId)) {
  14968. this._manager.abortRequest(this._requestId);
  14969. }
  14970. this._close();
  14971. }
  14972. }
  14973. /***/ }),
  14974. /* 35 */
  14975. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14976. Object.defineProperty(exports, "__esModule", ({
  14977. value: true
  14978. }));
  14979. exports.PDFFetchStream = void 0;
  14980. var _util = __w_pdfjs_require__(1);
  14981. var _network_utils = __w_pdfjs_require__(32);
  14982. ;
  14983. function createFetchOptions(headers, withCredentials, abortController) {
  14984. return {
  14985. method: "GET",
  14986. headers,
  14987. signal: abortController.signal,
  14988. mode: "cors",
  14989. credentials: withCredentials ? "include" : "same-origin",
  14990. redirect: "follow"
  14991. };
  14992. }
  14993. function createHeaders(httpHeaders) {
  14994. const headers = new Headers();
  14995. for (const property in httpHeaders) {
  14996. const value = httpHeaders[property];
  14997. if (typeof value === "undefined") {
  14998. continue;
  14999. }
  15000. headers.append(property, value);
  15001. }
  15002. return headers;
  15003. }
  15004. class PDFFetchStream {
  15005. constructor(source) {
  15006. this.source = source;
  15007. this.isHttp = /^https?:/i.test(source.url);
  15008. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  15009. this._fullRequestReader = null;
  15010. this._rangeRequestReaders = [];
  15011. }
  15012. get _progressiveDataLength() {
  15013. return this._fullRequestReader?._loaded ?? 0;
  15014. }
  15015. getFullReader() {
  15016. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  15017. this._fullRequestReader = new PDFFetchStreamReader(this);
  15018. return this._fullRequestReader;
  15019. }
  15020. getRangeReader(begin, end) {
  15021. if (end <= this._progressiveDataLength) {
  15022. return null;
  15023. }
  15024. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  15025. this._rangeRequestReaders.push(reader);
  15026. return reader;
  15027. }
  15028. cancelAllRequests(reason) {
  15029. this._fullRequestReader?.cancel(reason);
  15030. for (const reader of this._rangeRequestReaders.slice(0)) {
  15031. reader.cancel(reason);
  15032. }
  15033. }
  15034. }
  15035. exports.PDFFetchStream = PDFFetchStream;
  15036. class PDFFetchStreamReader {
  15037. constructor(stream) {
  15038. this._stream = stream;
  15039. this._reader = null;
  15040. this._loaded = 0;
  15041. this._filename = null;
  15042. const source = stream.source;
  15043. this._withCredentials = source.withCredentials || false;
  15044. this._contentLength = source.length;
  15045. this._headersCapability = (0, _util.createPromiseCapability)();
  15046. this._disableRange = source.disableRange || false;
  15047. this._rangeChunkSize = source.rangeChunkSize;
  15048. if (!this._rangeChunkSize && !this._disableRange) {
  15049. this._disableRange = true;
  15050. }
  15051. this._abortController = new AbortController();
  15052. this._isStreamingSupported = !source.disableStream;
  15053. this._isRangeSupported = !source.disableRange;
  15054. this._headers = createHeaders(this._stream.httpHeaders);
  15055. const url = source.url;
  15056. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15057. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15058. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15059. }
  15060. this._reader = response.body.getReader();
  15061. this._headersCapability.resolve();
  15062. const getResponseHeader = name => {
  15063. return response.headers.get(name);
  15064. };
  15065. const {
  15066. allowRangeRequests,
  15067. suggestedLength
  15068. } = (0, _network_utils.validateRangeRequestCapabilities)({
  15069. getResponseHeader,
  15070. isHttp: this._stream.isHttp,
  15071. rangeChunkSize: this._rangeChunkSize,
  15072. disableRange: this._disableRange
  15073. });
  15074. this._isRangeSupported = allowRangeRequests;
  15075. this._contentLength = suggestedLength || this._contentLength;
  15076. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  15077. if (!this._isStreamingSupported && this._isRangeSupported) {
  15078. this.cancel(new _util.AbortException("Streaming is disabled."));
  15079. }
  15080. }).catch(this._headersCapability.reject);
  15081. this.onProgress = null;
  15082. }
  15083. get headersReady() {
  15084. return this._headersCapability.promise;
  15085. }
  15086. get filename() {
  15087. return this._filename;
  15088. }
  15089. get contentLength() {
  15090. return this._contentLength;
  15091. }
  15092. get isRangeSupported() {
  15093. return this._isRangeSupported;
  15094. }
  15095. get isStreamingSupported() {
  15096. return this._isStreamingSupported;
  15097. }
  15098. async read() {
  15099. await this._headersCapability.promise;
  15100. const {
  15101. value,
  15102. done
  15103. } = await this._reader.read();
  15104. if (done) {
  15105. return {
  15106. value,
  15107. done
  15108. };
  15109. }
  15110. this._loaded += value.byteLength;
  15111. this.onProgress?.({
  15112. loaded: this._loaded,
  15113. total: this._contentLength
  15114. });
  15115. const buffer = new Uint8Array(value).buffer;
  15116. return {
  15117. value: buffer,
  15118. done: false
  15119. };
  15120. }
  15121. cancel(reason) {
  15122. this._reader?.cancel(reason);
  15123. this._abortController.abort();
  15124. }
  15125. }
  15126. class PDFFetchStreamRangeReader {
  15127. constructor(stream, begin, end) {
  15128. this._stream = stream;
  15129. this._reader = null;
  15130. this._loaded = 0;
  15131. const source = stream.source;
  15132. this._withCredentials = source.withCredentials || false;
  15133. this._readCapability = (0, _util.createPromiseCapability)();
  15134. this._isStreamingSupported = !source.disableStream;
  15135. this._abortController = new AbortController();
  15136. this._headers = createHeaders(this._stream.httpHeaders);
  15137. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  15138. const url = source.url;
  15139. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15140. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15141. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15142. }
  15143. this._readCapability.resolve();
  15144. this._reader = response.body.getReader();
  15145. }).catch(this._readCapability.reject);
  15146. this.onProgress = null;
  15147. }
  15148. get isStreamingSupported() {
  15149. return this._isStreamingSupported;
  15150. }
  15151. async read() {
  15152. await this._readCapability.promise;
  15153. const {
  15154. value,
  15155. done
  15156. } = await this._reader.read();
  15157. if (done) {
  15158. return {
  15159. value,
  15160. done
  15161. };
  15162. }
  15163. this._loaded += value.byteLength;
  15164. this.onProgress?.({
  15165. loaded: this._loaded
  15166. });
  15167. const buffer = new Uint8Array(value).buffer;
  15168. return {
  15169. value: buffer,
  15170. done: false
  15171. };
  15172. }
  15173. cancel(reason) {
  15174. this._reader?.cancel(reason);
  15175. this._abortController.abort();
  15176. }
  15177. }
  15178. /***/ })
  15179. /******/ ]);
  15180. /************************************************************************/
  15181. /******/ // The module cache
  15182. /******/ var __webpack_module_cache__ = {};
  15183. /******/
  15184. /******/ // The require function
  15185. /******/ function __w_pdfjs_require__(moduleId) {
  15186. /******/ // Check if module is in cache
  15187. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  15188. /******/ if (cachedModule !== undefined) {
  15189. /******/ return cachedModule.exports;
  15190. /******/ }
  15191. /******/ // Create a new module (and put it into the cache)
  15192. /******/ var module = __webpack_module_cache__[moduleId] = {
  15193. /******/ // no module.id needed
  15194. /******/ // no module.loaded needed
  15195. /******/ exports: {}
  15196. /******/ };
  15197. /******/
  15198. /******/ // Execute the module function
  15199. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  15200. /******/
  15201. /******/ // Return the exports of the module
  15202. /******/ return module.exports;
  15203. /******/ }
  15204. /******/
  15205. /************************************************************************/
  15206. var __webpack_exports__ = {};
  15207. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  15208. (() => {
  15209. var exports = __webpack_exports__;
  15210. Object.defineProperty(exports, "__esModule", ({
  15211. value: true
  15212. }));
  15213. Object.defineProperty(exports, "AnnotationEditorLayer", ({
  15214. enumerable: true,
  15215. get: function () {
  15216. return _annotation_editor_layer.AnnotationEditorLayer;
  15217. }
  15218. }));
  15219. Object.defineProperty(exports, "AnnotationEditorParamsType", ({
  15220. enumerable: true,
  15221. get: function () {
  15222. return _util.AnnotationEditorParamsType;
  15223. }
  15224. }));
  15225. Object.defineProperty(exports, "AnnotationEditorType", ({
  15226. enumerable: true,
  15227. get: function () {
  15228. return _util.AnnotationEditorType;
  15229. }
  15230. }));
  15231. Object.defineProperty(exports, "AnnotationEditorUIManager", ({
  15232. enumerable: true,
  15233. get: function () {
  15234. return _tools.AnnotationEditorUIManager;
  15235. }
  15236. }));
  15237. Object.defineProperty(exports, "AnnotationLayer", ({
  15238. enumerable: true,
  15239. get: function () {
  15240. return _annotation_layer.AnnotationLayer;
  15241. }
  15242. }));
  15243. Object.defineProperty(exports, "AnnotationMode", ({
  15244. enumerable: true,
  15245. get: function () {
  15246. return _util.AnnotationMode;
  15247. }
  15248. }));
  15249. Object.defineProperty(exports, "CMapCompressionType", ({
  15250. enumerable: true,
  15251. get: function () {
  15252. return _util.CMapCompressionType;
  15253. }
  15254. }));
  15255. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  15256. enumerable: true,
  15257. get: function () {
  15258. return _worker_options.GlobalWorkerOptions;
  15259. }
  15260. }));
  15261. Object.defineProperty(exports, "InvalidPDFException", ({
  15262. enumerable: true,
  15263. get: function () {
  15264. return _util.InvalidPDFException;
  15265. }
  15266. }));
  15267. Object.defineProperty(exports, "MissingPDFException", ({
  15268. enumerable: true,
  15269. get: function () {
  15270. return _util.MissingPDFException;
  15271. }
  15272. }));
  15273. Object.defineProperty(exports, "OPS", ({
  15274. enumerable: true,
  15275. get: function () {
  15276. return _util.OPS;
  15277. }
  15278. }));
  15279. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  15280. enumerable: true,
  15281. get: function () {
  15282. return _api.PDFDataRangeTransport;
  15283. }
  15284. }));
  15285. Object.defineProperty(exports, "PDFDateString", ({
  15286. enumerable: true,
  15287. get: function () {
  15288. return _display_utils.PDFDateString;
  15289. }
  15290. }));
  15291. Object.defineProperty(exports, "PDFWorker", ({
  15292. enumerable: true,
  15293. get: function () {
  15294. return _api.PDFWorker;
  15295. }
  15296. }));
  15297. Object.defineProperty(exports, "PasswordResponses", ({
  15298. enumerable: true,
  15299. get: function () {
  15300. return _util.PasswordResponses;
  15301. }
  15302. }));
  15303. Object.defineProperty(exports, "PermissionFlag", ({
  15304. enumerable: true,
  15305. get: function () {
  15306. return _util.PermissionFlag;
  15307. }
  15308. }));
  15309. Object.defineProperty(exports, "PixelsPerInch", ({
  15310. enumerable: true,
  15311. get: function () {
  15312. return _display_utils.PixelsPerInch;
  15313. }
  15314. }));
  15315. Object.defineProperty(exports, "RenderingCancelledException", ({
  15316. enumerable: true,
  15317. get: function () {
  15318. return _display_utils.RenderingCancelledException;
  15319. }
  15320. }));
  15321. Object.defineProperty(exports, "SVGGraphics", ({
  15322. enumerable: true,
  15323. get: function () {
  15324. return _svg.SVGGraphics;
  15325. }
  15326. }));
  15327. Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  15328. enumerable: true,
  15329. get: function () {
  15330. return _util.UNSUPPORTED_FEATURES;
  15331. }
  15332. }));
  15333. Object.defineProperty(exports, "UnexpectedResponseException", ({
  15334. enumerable: true,
  15335. get: function () {
  15336. return _util.UnexpectedResponseException;
  15337. }
  15338. }));
  15339. Object.defineProperty(exports, "Util", ({
  15340. enumerable: true,
  15341. get: function () {
  15342. return _util.Util;
  15343. }
  15344. }));
  15345. Object.defineProperty(exports, "VerbosityLevel", ({
  15346. enumerable: true,
  15347. get: function () {
  15348. return _util.VerbosityLevel;
  15349. }
  15350. }));
  15351. Object.defineProperty(exports, "XfaLayer", ({
  15352. enumerable: true,
  15353. get: function () {
  15354. return _xfa_layer.XfaLayer;
  15355. }
  15356. }));
  15357. Object.defineProperty(exports, "build", ({
  15358. enumerable: true,
  15359. get: function () {
  15360. return _api.build;
  15361. }
  15362. }));
  15363. Object.defineProperty(exports, "createPromiseCapability", ({
  15364. enumerable: true,
  15365. get: function () {
  15366. return _util.createPromiseCapability;
  15367. }
  15368. }));
  15369. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  15370. enumerable: true,
  15371. get: function () {
  15372. return _util.createValidAbsoluteUrl;
  15373. }
  15374. }));
  15375. Object.defineProperty(exports, "getDocument", ({
  15376. enumerable: true,
  15377. get: function () {
  15378. return _api.getDocument;
  15379. }
  15380. }));
  15381. Object.defineProperty(exports, "getFilenameFromUrl", ({
  15382. enumerable: true,
  15383. get: function () {
  15384. return _display_utils.getFilenameFromUrl;
  15385. }
  15386. }));
  15387. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  15388. enumerable: true,
  15389. get: function () {
  15390. return _display_utils.getPdfFilenameFromUrl;
  15391. }
  15392. }));
  15393. Object.defineProperty(exports, "getXfaPageViewport", ({
  15394. enumerable: true,
  15395. get: function () {
  15396. return _display_utils.getXfaPageViewport;
  15397. }
  15398. }));
  15399. Object.defineProperty(exports, "isPdfFile", ({
  15400. enumerable: true,
  15401. get: function () {
  15402. return _display_utils.isPdfFile;
  15403. }
  15404. }));
  15405. Object.defineProperty(exports, "loadScript", ({
  15406. enumerable: true,
  15407. get: function () {
  15408. return _display_utils.loadScript;
  15409. }
  15410. }));
  15411. Object.defineProperty(exports, "renderTextLayer", ({
  15412. enumerable: true,
  15413. get: function () {
  15414. return _text_layer.renderTextLayer;
  15415. }
  15416. }));
  15417. Object.defineProperty(exports, "shadow", ({
  15418. enumerable: true,
  15419. get: function () {
  15420. return _util.shadow;
  15421. }
  15422. }));
  15423. Object.defineProperty(exports, "version", ({
  15424. enumerable: true,
  15425. get: function () {
  15426. return _api.version;
  15427. }
  15428. }));
  15429. var _util = __w_pdfjs_require__(1);
  15430. var _api = __w_pdfjs_require__(2);
  15431. var _display_utils = __w_pdfjs_require__(6);
  15432. var _annotation_editor_layer = __w_pdfjs_require__(21);
  15433. var _tools = __w_pdfjs_require__(5);
  15434. var _annotation_layer = __w_pdfjs_require__(26);
  15435. var _worker_options = __w_pdfjs_require__(14);
  15436. var _is_node = __w_pdfjs_require__(12);
  15437. var _text_layer = __w_pdfjs_require__(29);
  15438. var _svg = __w_pdfjs_require__(30);
  15439. var _xfa_layer = __w_pdfjs_require__(28);
  15440. const pdfjsVersion = '3.1.81';
  15441. const pdfjsBuild = '0766898d5';
  15442. {
  15443. if (_is_node.isNodeJS) {
  15444. const {
  15445. PDFNodeStream
  15446. } = __w_pdfjs_require__(31);
  15447. (0, _api.setPDFNetworkStreamFactory)(params => {
  15448. return new PDFNodeStream(params);
  15449. });
  15450. } else {
  15451. const {
  15452. PDFNetworkStream
  15453. } = __w_pdfjs_require__(34);
  15454. const {
  15455. PDFFetchStream
  15456. } = __w_pdfjs_require__(35);
  15457. (0, _api.setPDFNetworkStreamFactory)(params => {
  15458. if ((0, _display_utils.isValidFetchUrl)(params.url)) {
  15459. return new PDFFetchStream(params);
  15460. }
  15461. return new PDFNetworkStream(params);
  15462. });
  15463. }
  15464. }
  15465. })();
  15466. /******/ return __webpack_exports__;
  15467. /******/ })()
  15468. ;
  15469. });
  15470. //# sourceMappingURL=pdf.js.map