pdf.js 508 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029
  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, __w_pdfjs_require__) => {
  38. Object.defineProperty(exports, "__esModule", ({
  39. value: true
  40. }));
  41. exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
  42. exports.arrayByteLength = arrayByteLength;
  43. exports.arraysToBytes = arraysToBytes;
  44. exports.assert = assert;
  45. exports.bytesToString = bytesToString;
  46. exports.createPromiseCapability = createPromiseCapability;
  47. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  48. exports.escapeString = escapeString;
  49. exports.getModificationDate = getModificationDate;
  50. exports.getVerbosityLevel = getVerbosityLevel;
  51. exports.info = info;
  52. exports.isArrayBuffer = isArrayBuffer;
  53. exports.isArrayEqual = isArrayEqual;
  54. exports.isAscii = isAscii;
  55. exports.objectFromMap = objectFromMap;
  56. exports.objectSize = objectSize;
  57. exports.setVerbosityLevel = setVerbosityLevel;
  58. exports.shadow = shadow;
  59. exports.string32 = string32;
  60. exports.stringToBytes = stringToBytes;
  61. exports.stringToPDFString = stringToPDFString;
  62. exports.stringToUTF16BEString = stringToUTF16BEString;
  63. exports.stringToUTF8String = stringToUTF8String;
  64. exports.unreachable = unreachable;
  65. exports.utf8StringToString = utf8StringToString;
  66. exports.warn = warn;
  67. __w_pdfjs_require__(2);
  68. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  69. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  70. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  71. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  72. const LINE_FACTOR = 1.35;
  73. exports.LINE_FACTOR = LINE_FACTOR;
  74. const LINE_DESCENT_FACTOR = 0.35;
  75. exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
  76. const RenderingIntentFlag = {
  77. ANY: 0x01,
  78. DISPLAY: 0x02,
  79. PRINT: 0x04,
  80. ANNOTATIONS_FORMS: 0x10,
  81. ANNOTATIONS_STORAGE: 0x20,
  82. ANNOTATIONS_DISABLE: 0x40,
  83. OPLIST: 0x100
  84. };
  85. exports.RenderingIntentFlag = RenderingIntentFlag;
  86. const AnnotationMode = {
  87. DISABLE: 0,
  88. ENABLE: 1,
  89. ENABLE_FORMS: 2,
  90. ENABLE_STORAGE: 3
  91. };
  92. exports.AnnotationMode = AnnotationMode;
  93. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  94. exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
  95. const AnnotationEditorType = {
  96. DISABLE: -1,
  97. NONE: 0,
  98. FREETEXT: 3,
  99. INK: 15
  100. };
  101. exports.AnnotationEditorType = AnnotationEditorType;
  102. const AnnotationEditorParamsType = {
  103. FREETEXT_SIZE: 1,
  104. FREETEXT_COLOR: 2,
  105. FREETEXT_OPACITY: 3,
  106. INK_COLOR: 11,
  107. INK_THICKNESS: 12,
  108. INK_OPACITY: 13
  109. };
  110. exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
  111. const PermissionFlag = {
  112. PRINT: 0x04,
  113. MODIFY_CONTENTS: 0x08,
  114. COPY: 0x10,
  115. MODIFY_ANNOTATIONS: 0x20,
  116. FILL_INTERACTIVE_FORMS: 0x100,
  117. COPY_FOR_ACCESSIBILITY: 0x200,
  118. ASSEMBLE: 0x400,
  119. PRINT_HIGH_QUALITY: 0x800
  120. };
  121. exports.PermissionFlag = PermissionFlag;
  122. const TextRenderingMode = {
  123. FILL: 0,
  124. STROKE: 1,
  125. FILL_STROKE: 2,
  126. INVISIBLE: 3,
  127. FILL_ADD_TO_PATH: 4,
  128. STROKE_ADD_TO_PATH: 5,
  129. FILL_STROKE_ADD_TO_PATH: 6,
  130. ADD_TO_PATH: 7,
  131. FILL_STROKE_MASK: 3,
  132. ADD_TO_PATH_FLAG: 4
  133. };
  134. exports.TextRenderingMode = TextRenderingMode;
  135. const ImageKind = {
  136. GRAYSCALE_1BPP: 1,
  137. RGB_24BPP: 2,
  138. RGBA_32BPP: 3
  139. };
  140. exports.ImageKind = ImageKind;
  141. const AnnotationType = {
  142. TEXT: 1,
  143. LINK: 2,
  144. FREETEXT: 3,
  145. LINE: 4,
  146. SQUARE: 5,
  147. CIRCLE: 6,
  148. POLYGON: 7,
  149. POLYLINE: 8,
  150. HIGHLIGHT: 9,
  151. UNDERLINE: 10,
  152. SQUIGGLY: 11,
  153. STRIKEOUT: 12,
  154. STAMP: 13,
  155. CARET: 14,
  156. INK: 15,
  157. POPUP: 16,
  158. FILEATTACHMENT: 17,
  159. SOUND: 18,
  160. MOVIE: 19,
  161. WIDGET: 20,
  162. SCREEN: 21,
  163. PRINTERMARK: 22,
  164. TRAPNET: 23,
  165. WATERMARK: 24,
  166. THREED: 25,
  167. REDACT: 26
  168. };
  169. exports.AnnotationType = AnnotationType;
  170. const AnnotationStateModelType = {
  171. MARKED: "Marked",
  172. REVIEW: "Review"
  173. };
  174. exports.AnnotationStateModelType = AnnotationStateModelType;
  175. const AnnotationMarkedState = {
  176. MARKED: "Marked",
  177. UNMARKED: "Unmarked"
  178. };
  179. exports.AnnotationMarkedState = AnnotationMarkedState;
  180. const AnnotationReviewState = {
  181. ACCEPTED: "Accepted",
  182. REJECTED: "Rejected",
  183. CANCELLED: "Cancelled",
  184. COMPLETED: "Completed",
  185. NONE: "None"
  186. };
  187. exports.AnnotationReviewState = AnnotationReviewState;
  188. const AnnotationReplyType = {
  189. GROUP: "Group",
  190. REPLY: "R"
  191. };
  192. exports.AnnotationReplyType = AnnotationReplyType;
  193. const AnnotationFlag = {
  194. INVISIBLE: 0x01,
  195. HIDDEN: 0x02,
  196. PRINT: 0x04,
  197. NOZOOM: 0x08,
  198. NOROTATE: 0x10,
  199. NOVIEW: 0x20,
  200. READONLY: 0x40,
  201. LOCKED: 0x80,
  202. TOGGLENOVIEW: 0x100,
  203. LOCKEDCONTENTS: 0x200
  204. };
  205. exports.AnnotationFlag = AnnotationFlag;
  206. const AnnotationFieldFlag = {
  207. READONLY: 0x0000001,
  208. REQUIRED: 0x0000002,
  209. NOEXPORT: 0x0000004,
  210. MULTILINE: 0x0001000,
  211. PASSWORD: 0x0002000,
  212. NOTOGGLETOOFF: 0x0004000,
  213. RADIO: 0x0008000,
  214. PUSHBUTTON: 0x0010000,
  215. COMBO: 0x0020000,
  216. EDIT: 0x0040000,
  217. SORT: 0x0080000,
  218. FILESELECT: 0x0100000,
  219. MULTISELECT: 0x0200000,
  220. DONOTSPELLCHECK: 0x0400000,
  221. DONOTSCROLL: 0x0800000,
  222. COMB: 0x1000000,
  223. RICHTEXT: 0x2000000,
  224. RADIOSINUNISON: 0x2000000,
  225. COMMITONSELCHANGE: 0x4000000
  226. };
  227. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  228. const AnnotationBorderStyleType = {
  229. SOLID: 1,
  230. DASHED: 2,
  231. BEVELED: 3,
  232. INSET: 4,
  233. UNDERLINE: 5
  234. };
  235. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  236. const AnnotationActionEventType = {
  237. E: "Mouse Enter",
  238. X: "Mouse Exit",
  239. D: "Mouse Down",
  240. U: "Mouse Up",
  241. Fo: "Focus",
  242. Bl: "Blur",
  243. PO: "PageOpen",
  244. PC: "PageClose",
  245. PV: "PageVisible",
  246. PI: "PageInvisible",
  247. K: "Keystroke",
  248. F: "Format",
  249. V: "Validate",
  250. C: "Calculate"
  251. };
  252. exports.AnnotationActionEventType = AnnotationActionEventType;
  253. const DocumentActionEventType = {
  254. WC: "WillClose",
  255. WS: "WillSave",
  256. DS: "DidSave",
  257. WP: "WillPrint",
  258. DP: "DidPrint"
  259. };
  260. exports.DocumentActionEventType = DocumentActionEventType;
  261. const PageActionEventType = {
  262. O: "PageOpen",
  263. C: "PageClose"
  264. };
  265. exports.PageActionEventType = PageActionEventType;
  266. const StreamType = {
  267. UNKNOWN: "UNKNOWN",
  268. FLATE: "FLATE",
  269. LZW: "LZW",
  270. DCT: "DCT",
  271. JPX: "JPX",
  272. JBIG: "JBIG",
  273. A85: "A85",
  274. AHX: "AHX",
  275. CCF: "CCF",
  276. RLX: "RLX"
  277. };
  278. exports.StreamType = StreamType;
  279. const FontType = {
  280. UNKNOWN: "UNKNOWN",
  281. TYPE1: "TYPE1",
  282. TYPE1STANDARD: "TYPE1STANDARD",
  283. TYPE1C: "TYPE1C",
  284. CIDFONTTYPE0: "CIDFONTTYPE0",
  285. CIDFONTTYPE0C: "CIDFONTTYPE0C",
  286. TRUETYPE: "TRUETYPE",
  287. CIDFONTTYPE2: "CIDFONTTYPE2",
  288. TYPE3: "TYPE3",
  289. OPENTYPE: "OPENTYPE",
  290. TYPE0: "TYPE0",
  291. MMTYPE1: "MMTYPE1"
  292. };
  293. exports.FontType = FontType;
  294. const VerbosityLevel = {
  295. ERRORS: 0,
  296. WARNINGS: 1,
  297. INFOS: 5
  298. };
  299. exports.VerbosityLevel = VerbosityLevel;
  300. const CMapCompressionType = {
  301. NONE: 0,
  302. BINARY: 1,
  303. STREAM: 2
  304. };
  305. exports.CMapCompressionType = CMapCompressionType;
  306. const OPS = {
  307. dependency: 1,
  308. setLineWidth: 2,
  309. setLineCap: 3,
  310. setLineJoin: 4,
  311. setMiterLimit: 5,
  312. setDash: 6,
  313. setRenderingIntent: 7,
  314. setFlatness: 8,
  315. setGState: 9,
  316. save: 10,
  317. restore: 11,
  318. transform: 12,
  319. moveTo: 13,
  320. lineTo: 14,
  321. curveTo: 15,
  322. curveTo2: 16,
  323. curveTo3: 17,
  324. closePath: 18,
  325. rectangle: 19,
  326. stroke: 20,
  327. closeStroke: 21,
  328. fill: 22,
  329. eoFill: 23,
  330. fillStroke: 24,
  331. eoFillStroke: 25,
  332. closeFillStroke: 26,
  333. closeEOFillStroke: 27,
  334. endPath: 28,
  335. clip: 29,
  336. eoClip: 30,
  337. beginText: 31,
  338. endText: 32,
  339. setCharSpacing: 33,
  340. setWordSpacing: 34,
  341. setHScale: 35,
  342. setLeading: 36,
  343. setFont: 37,
  344. setTextRenderingMode: 38,
  345. setTextRise: 39,
  346. moveText: 40,
  347. setLeadingMoveText: 41,
  348. setTextMatrix: 42,
  349. nextLine: 43,
  350. showText: 44,
  351. showSpacedText: 45,
  352. nextLineShowText: 46,
  353. nextLineSetSpacingShowText: 47,
  354. setCharWidth: 48,
  355. setCharWidthAndBounds: 49,
  356. setStrokeColorSpace: 50,
  357. setFillColorSpace: 51,
  358. setStrokeColor: 52,
  359. setStrokeColorN: 53,
  360. setFillColor: 54,
  361. setFillColorN: 55,
  362. setStrokeGray: 56,
  363. setFillGray: 57,
  364. setStrokeRGBColor: 58,
  365. setFillRGBColor: 59,
  366. setStrokeCMYKColor: 60,
  367. setFillCMYKColor: 61,
  368. shadingFill: 62,
  369. beginInlineImage: 63,
  370. beginImageData: 64,
  371. endInlineImage: 65,
  372. paintXObject: 66,
  373. markPoint: 67,
  374. markPointProps: 68,
  375. beginMarkedContent: 69,
  376. beginMarkedContentProps: 70,
  377. endMarkedContent: 71,
  378. beginCompat: 72,
  379. endCompat: 73,
  380. paintFormXObjectBegin: 74,
  381. paintFormXObjectEnd: 75,
  382. beginGroup: 76,
  383. endGroup: 77,
  384. beginAnnotations: 78,
  385. endAnnotations: 79,
  386. beginAnnotation: 80,
  387. endAnnotation: 81,
  388. paintJpegXObject: 82,
  389. paintImageMaskXObject: 83,
  390. paintImageMaskXObjectGroup: 84,
  391. paintImageXObject: 85,
  392. paintInlineImageXObject: 86,
  393. paintInlineImageXObjectGroup: 87,
  394. paintImageXObjectRepeat: 88,
  395. paintImageMaskXObjectRepeat: 89,
  396. paintSolidColorImageMask: 90,
  397. constructPath: 91
  398. };
  399. exports.OPS = OPS;
  400. const UNSUPPORTED_FEATURES = {
  401. unknown: "unknown",
  402. forms: "forms",
  403. javaScript: "javaScript",
  404. signatures: "signatures",
  405. smask: "smask",
  406. shadingPattern: "shadingPattern",
  407. font: "font",
  408. errorTilingPattern: "errorTilingPattern",
  409. errorExtGState: "errorExtGState",
  410. errorXObject: "errorXObject",
  411. errorFontLoadType3: "errorFontLoadType3",
  412. errorFontState: "errorFontState",
  413. errorFontMissing: "errorFontMissing",
  414. errorFontTranslate: "errorFontTranslate",
  415. errorColorSpace: "errorColorSpace",
  416. errorOperatorList: "errorOperatorList",
  417. errorFontToUnicode: "errorFontToUnicode",
  418. errorFontLoadNative: "errorFontLoadNative",
  419. errorFontBuildPath: "errorFontBuildPath",
  420. errorFontGetPath: "errorFontGetPath",
  421. errorMarkedContent: "errorMarkedContent",
  422. errorContentSubStream: "errorContentSubStream"
  423. };
  424. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  425. const PasswordResponses = {
  426. NEED_PASSWORD: 1,
  427. INCORRECT_PASSWORD: 2
  428. };
  429. exports.PasswordResponses = PasswordResponses;
  430. let verbosity = VerbosityLevel.WARNINGS;
  431. function setVerbosityLevel(level) {
  432. if (Number.isInteger(level)) {
  433. verbosity = level;
  434. }
  435. }
  436. function getVerbosityLevel() {
  437. return verbosity;
  438. }
  439. function info(msg) {
  440. if (verbosity >= VerbosityLevel.INFOS) {
  441. console.log(`Info: ${msg}`);
  442. }
  443. }
  444. function warn(msg) {
  445. if (verbosity >= VerbosityLevel.WARNINGS) {
  446. console.log(`Warning: ${msg}`);
  447. }
  448. }
  449. function unreachable(msg) {
  450. throw new Error(msg);
  451. }
  452. function assert(cond, msg) {
  453. if (!cond) {
  454. unreachable(msg);
  455. }
  456. }
  457. function _isValidProtocol(url) {
  458. if (!url) {
  459. return false;
  460. }
  461. switch (url.protocol) {
  462. case "http:":
  463. case "https:":
  464. case "ftp:":
  465. case "mailto:":
  466. case "tel:":
  467. return true;
  468. default:
  469. return false;
  470. }
  471. }
  472. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  473. if (!url) {
  474. return null;
  475. }
  476. try {
  477. if (options && typeof url === "string") {
  478. if (options.addDefaultProtocol && url.startsWith("www.")) {
  479. const dots = url.match(/\./g);
  480. if (dots && dots.length >= 2) {
  481. url = `http://${url}`;
  482. }
  483. }
  484. if (options.tryConvertEncoding) {
  485. try {
  486. url = stringToUTF8String(url);
  487. } catch (ex) {}
  488. }
  489. }
  490. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  491. if (_isValidProtocol(absoluteUrl)) {
  492. return absoluteUrl;
  493. }
  494. } catch (ex) {}
  495. return null;
  496. }
  497. function shadow(obj, prop, value) {
  498. Object.defineProperty(obj, prop, {
  499. value,
  500. enumerable: true,
  501. configurable: true,
  502. writable: false
  503. });
  504. return value;
  505. }
  506. const BaseException = function BaseExceptionClosure() {
  507. function BaseException(message, name) {
  508. if (this.constructor === BaseException) {
  509. unreachable("Cannot initialize BaseException.");
  510. }
  511. this.message = message;
  512. this.name = name;
  513. }
  514. BaseException.prototype = new Error();
  515. BaseException.constructor = BaseException;
  516. return BaseException;
  517. }();
  518. exports.BaseException = BaseException;
  519. class PasswordException extends BaseException {
  520. constructor(msg, code) {
  521. super(msg, "PasswordException");
  522. this.code = code;
  523. }
  524. }
  525. exports.PasswordException = PasswordException;
  526. class UnknownErrorException extends BaseException {
  527. constructor(msg, details) {
  528. super(msg, "UnknownErrorException");
  529. this.details = details;
  530. }
  531. }
  532. exports.UnknownErrorException = UnknownErrorException;
  533. class InvalidPDFException extends BaseException {
  534. constructor(msg) {
  535. super(msg, "InvalidPDFException");
  536. }
  537. }
  538. exports.InvalidPDFException = InvalidPDFException;
  539. class MissingPDFException extends BaseException {
  540. constructor(msg) {
  541. super(msg, "MissingPDFException");
  542. }
  543. }
  544. exports.MissingPDFException = MissingPDFException;
  545. class UnexpectedResponseException extends BaseException {
  546. constructor(msg, status) {
  547. super(msg, "UnexpectedResponseException");
  548. this.status = status;
  549. }
  550. }
  551. exports.UnexpectedResponseException = UnexpectedResponseException;
  552. class FormatError extends BaseException {
  553. constructor(msg) {
  554. super(msg, "FormatError");
  555. }
  556. }
  557. exports.FormatError = FormatError;
  558. class AbortException extends BaseException {
  559. constructor(msg) {
  560. super(msg, "AbortException");
  561. }
  562. }
  563. exports.AbortException = AbortException;
  564. function bytesToString(bytes) {
  565. if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
  566. unreachable("Invalid argument for bytesToString");
  567. }
  568. const length = bytes.length;
  569. const MAX_ARGUMENT_COUNT = 8192;
  570. if (length < MAX_ARGUMENT_COUNT) {
  571. return String.fromCharCode.apply(null, bytes);
  572. }
  573. const strBuf = [];
  574. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  575. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  576. const chunk = bytes.subarray(i, chunkEnd);
  577. strBuf.push(String.fromCharCode.apply(null, chunk));
  578. }
  579. return strBuf.join("");
  580. }
  581. function stringToBytes(str) {
  582. if (typeof str !== "string") {
  583. unreachable("Invalid argument for stringToBytes");
  584. }
  585. const length = str.length;
  586. const bytes = new Uint8Array(length);
  587. for (let i = 0; i < length; ++i) {
  588. bytes[i] = str.charCodeAt(i) & 0xff;
  589. }
  590. return bytes;
  591. }
  592. function arrayByteLength(arr) {
  593. if (arr.length !== undefined) {
  594. return arr.length;
  595. }
  596. if (arr.byteLength !== undefined) {
  597. return arr.byteLength;
  598. }
  599. unreachable("Invalid argument for arrayByteLength");
  600. }
  601. function arraysToBytes(arr) {
  602. const length = arr.length;
  603. if (length === 1 && arr[0] instanceof Uint8Array) {
  604. return arr[0];
  605. }
  606. let resultLength = 0;
  607. for (let i = 0; i < length; i++) {
  608. resultLength += arrayByteLength(arr[i]);
  609. }
  610. let pos = 0;
  611. const data = new Uint8Array(resultLength);
  612. for (let i = 0; i < length; i++) {
  613. let item = arr[i];
  614. if (!(item instanceof Uint8Array)) {
  615. if (typeof item === "string") {
  616. item = stringToBytes(item);
  617. } else {
  618. item = new Uint8Array(item);
  619. }
  620. }
  621. const itemLength = item.byteLength;
  622. data.set(item, pos);
  623. pos += itemLength;
  624. }
  625. return data;
  626. }
  627. function string32(value) {
  628. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  629. }
  630. function objectSize(obj) {
  631. return Object.keys(obj).length;
  632. }
  633. function objectFromMap(map) {
  634. const obj = Object.create(null);
  635. for (const [key, value] of map) {
  636. obj[key] = value;
  637. }
  638. return obj;
  639. }
  640. function isLittleEndian() {
  641. const buffer8 = new Uint8Array(4);
  642. buffer8[0] = 1;
  643. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  644. return view32[0] === 1;
  645. }
  646. function isEvalSupported() {
  647. try {
  648. new Function("");
  649. return true;
  650. } catch (e) {
  651. return false;
  652. }
  653. }
  654. class FeatureTest {
  655. static get isLittleEndian() {
  656. return shadow(this, "isLittleEndian", isLittleEndian());
  657. }
  658. static get isEvalSupported() {
  659. return shadow(this, "isEvalSupported", isEvalSupported());
  660. }
  661. static get isOffscreenCanvasSupported() {
  662. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  663. }
  664. }
  665. exports.FeatureTest = FeatureTest;
  666. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  667. class Util {
  668. static makeHexColor(r, g, b) {
  669. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  670. }
  671. static scaleMinMax(transform, minMax) {
  672. let temp;
  673. if (transform[0]) {
  674. if (transform[0] < 0) {
  675. temp = minMax[0];
  676. minMax[0] = minMax[1];
  677. minMax[1] = temp;
  678. }
  679. minMax[0] *= transform[0];
  680. minMax[1] *= transform[0];
  681. if (transform[3] < 0) {
  682. temp = minMax[2];
  683. minMax[2] = minMax[3];
  684. minMax[3] = temp;
  685. }
  686. minMax[2] *= transform[3];
  687. minMax[3] *= transform[3];
  688. } else {
  689. temp = minMax[0];
  690. minMax[0] = minMax[2];
  691. minMax[2] = temp;
  692. temp = minMax[1];
  693. minMax[1] = minMax[3];
  694. minMax[3] = temp;
  695. if (transform[1] < 0) {
  696. temp = minMax[2];
  697. minMax[2] = minMax[3];
  698. minMax[3] = temp;
  699. }
  700. minMax[2] *= transform[1];
  701. minMax[3] *= transform[1];
  702. if (transform[2] < 0) {
  703. temp = minMax[0];
  704. minMax[0] = minMax[1];
  705. minMax[1] = temp;
  706. }
  707. minMax[0] *= transform[2];
  708. minMax[1] *= transform[2];
  709. }
  710. minMax[0] += transform[4];
  711. minMax[1] += transform[4];
  712. minMax[2] += transform[5];
  713. minMax[3] += transform[5];
  714. }
  715. static transform(m1, m2) {
  716. 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]];
  717. }
  718. static applyTransform(p, m) {
  719. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  720. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  721. return [xt, yt];
  722. }
  723. static applyInverseTransform(p, m) {
  724. const d = m[0] * m[3] - m[1] * m[2];
  725. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  726. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  727. return [xt, yt];
  728. }
  729. static getAxialAlignedBoundingBox(r, m) {
  730. const p1 = Util.applyTransform(r, m);
  731. const p2 = Util.applyTransform(r.slice(2, 4), m);
  732. const p3 = Util.applyTransform([r[0], r[3]], m);
  733. const p4 = Util.applyTransform([r[2], r[1]], m);
  734. 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])];
  735. }
  736. static inverseTransform(m) {
  737. const d = m[0] * m[3] - m[1] * m[2];
  738. 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];
  739. }
  740. static apply3dTransform(m, v) {
  741. return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
  742. }
  743. static singularValueDecompose2dScale(m) {
  744. const transpose = [m[0], m[2], m[1], m[3]];
  745. const a = m[0] * transpose[0] + m[1] * transpose[2];
  746. const b = m[0] * transpose[1] + m[1] * transpose[3];
  747. const c = m[2] * transpose[0] + m[3] * transpose[2];
  748. const d = m[2] * transpose[1] + m[3] * transpose[3];
  749. const first = (a + d) / 2;
  750. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  751. const sx = first + second || 1;
  752. const sy = first - second || 1;
  753. return [Math.sqrt(sx), Math.sqrt(sy)];
  754. }
  755. static normalizeRect(rect) {
  756. const r = rect.slice(0);
  757. if (rect[0] > rect[2]) {
  758. r[0] = rect[2];
  759. r[2] = rect[0];
  760. }
  761. if (rect[1] > rect[3]) {
  762. r[1] = rect[3];
  763. r[3] = rect[1];
  764. }
  765. return r;
  766. }
  767. static intersect(rect1, rect2) {
  768. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  769. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  770. if (xLow > xHigh) {
  771. return null;
  772. }
  773. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  774. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  775. if (yLow > yHigh) {
  776. return null;
  777. }
  778. return [xLow, yLow, xHigh, yHigh];
  779. }
  780. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
  781. const tvalues = [],
  782. bounds = [[], []];
  783. let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  784. for (let i = 0; i < 2; ++i) {
  785. if (i === 0) {
  786. b = 6 * x0 - 12 * x1 + 6 * x2;
  787. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  788. c = 3 * x1 - 3 * x0;
  789. } else {
  790. b = 6 * y0 - 12 * y1 + 6 * y2;
  791. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  792. c = 3 * y1 - 3 * y0;
  793. }
  794. if (Math.abs(a) < 1e-12) {
  795. if (Math.abs(b) < 1e-12) {
  796. continue;
  797. }
  798. t = -c / b;
  799. if (0 < t && t < 1) {
  800. tvalues.push(t);
  801. }
  802. continue;
  803. }
  804. b2ac = b * b - 4 * c * a;
  805. sqrtb2ac = Math.sqrt(b2ac);
  806. if (b2ac < 0) {
  807. continue;
  808. }
  809. t1 = (-b + sqrtb2ac) / (2 * a);
  810. if (0 < t1 && t1 < 1) {
  811. tvalues.push(t1);
  812. }
  813. t2 = (-b - sqrtb2ac) / (2 * a);
  814. if (0 < t2 && t2 < 1) {
  815. tvalues.push(t2);
  816. }
  817. }
  818. let j = tvalues.length,
  819. mt;
  820. const jlen = j;
  821. while (j--) {
  822. t = tvalues[j];
  823. mt = 1 - t;
  824. bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
  825. bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
  826. }
  827. bounds[0][jlen] = x0;
  828. bounds[1][jlen] = y0;
  829. bounds[0][jlen + 1] = x3;
  830. bounds[1][jlen + 1] = y3;
  831. bounds[0].length = bounds[1].length = jlen + 2;
  832. return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  833. }
  834. }
  835. exports.Util = Util;
  836. 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];
  837. function stringToPDFString(str) {
  838. if (str[0] >= "\xEF") {
  839. let encoding;
  840. if (str[0] === "\xFE" && str[1] === "\xFF") {
  841. encoding = "utf-16be";
  842. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  843. encoding = "utf-16le";
  844. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  845. encoding = "utf-8";
  846. }
  847. if (encoding) {
  848. try {
  849. const decoder = new TextDecoder(encoding, {
  850. fatal: true
  851. });
  852. const buffer = stringToBytes(str);
  853. return decoder.decode(buffer);
  854. } catch (ex) {
  855. warn(`stringToPDFString: "${ex}".`);
  856. }
  857. }
  858. }
  859. const strBuf = [];
  860. for (let i = 0, ii = str.length; i < ii; i++) {
  861. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  862. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  863. }
  864. return strBuf.join("");
  865. }
  866. function escapeString(str) {
  867. return str.replace(/([()\\\n\r])/g, match => {
  868. if (match === "\n") {
  869. return "\\n";
  870. } else if (match === "\r") {
  871. return "\\r";
  872. }
  873. return `\\${match}`;
  874. });
  875. }
  876. function isAscii(str) {
  877. return /^[\x00-\x7F]*$/.test(str);
  878. }
  879. function stringToUTF16BEString(str) {
  880. const buf = ["\xFE\xFF"];
  881. for (let i = 0, ii = str.length; i < ii; i++) {
  882. const char = str.charCodeAt(i);
  883. buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
  884. }
  885. return buf.join("");
  886. }
  887. function stringToUTF8String(str) {
  888. return decodeURIComponent(escape(str));
  889. }
  890. function utf8StringToString(str) {
  891. return unescape(encodeURIComponent(str));
  892. }
  893. function isArrayBuffer(v) {
  894. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  895. }
  896. function isArrayEqual(arr1, arr2) {
  897. if (arr1.length !== arr2.length) {
  898. return false;
  899. }
  900. for (let i = 0, ii = arr1.length; i < ii; i++) {
  901. if (arr1[i] !== arr2[i]) {
  902. return false;
  903. }
  904. }
  905. return true;
  906. }
  907. function getModificationDate(date = new Date()) {
  908. 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")];
  909. return buffer.join("");
  910. }
  911. function createPromiseCapability() {
  912. const capability = Object.create(null);
  913. let isSettled = false;
  914. Object.defineProperty(capability, "settled", {
  915. get() {
  916. return isSettled;
  917. }
  918. });
  919. capability.promise = new Promise(function (resolve, reject) {
  920. capability.resolve = function (data) {
  921. isSettled = true;
  922. resolve(data);
  923. };
  924. capability.reject = function (reason) {
  925. isSettled = true;
  926. reject(reason);
  927. };
  928. });
  929. return capability;
  930. }
  931. /***/ }),
  932. /* 2 */
  933. /***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
  934. var _is_node = __w_pdfjs_require__(3);
  935. ;
  936. /***/ }),
  937. /* 3 */
  938. /***/ ((__unused_webpack_module, exports) => {
  939. Object.defineProperty(exports, "__esModule", ({
  940. value: true
  941. }));
  942. exports.isNodeJS = void 0;
  943. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  944. exports.isNodeJS = isNodeJS;
  945. /***/ }),
  946. /* 4 */
  947. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  948. Object.defineProperty(exports, "__esModule", ({
  949. value: true
  950. }));
  951. exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = void 0;
  952. exports.binarySearchFirstItem = binarySearchFirstItem;
  953. exports.deprecated = deprecated;
  954. exports.getColorValues = getColorValues;
  955. exports.getFilenameFromUrl = getFilenameFromUrl;
  956. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  957. exports.getRGB = getRGB;
  958. exports.getXfaPageViewport = getXfaPageViewport;
  959. exports.isDataScheme = isDataScheme;
  960. exports.isPdfFile = isPdfFile;
  961. exports.isValidFetchUrl = isValidFetchUrl;
  962. exports.loadScript = loadScript;
  963. var _base_factory = __w_pdfjs_require__(5);
  964. var _util = __w_pdfjs_require__(1);
  965. const SVG_NS = "http://www.w3.org/2000/svg";
  966. class PixelsPerInch {
  967. static CSS = 96.0;
  968. static PDF = 72.0;
  969. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  970. }
  971. exports.PixelsPerInch = PixelsPerInch;
  972. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  973. constructor({
  974. ownerDocument = globalThis.document
  975. } = {}) {
  976. super();
  977. this._document = ownerDocument;
  978. }
  979. _createCanvas(width, height) {
  980. const canvas = this._document.createElement("canvas");
  981. canvas.width = width;
  982. canvas.height = height;
  983. return canvas;
  984. }
  985. }
  986. exports.DOMCanvasFactory = DOMCanvasFactory;
  987. async function fetchData(url, asTypedArray = false) {
  988. if (isValidFetchUrl(url, document.baseURI)) {
  989. const response = await fetch(url);
  990. if (!response.ok) {
  991. throw new Error(response.statusText);
  992. }
  993. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  994. }
  995. return new Promise((resolve, reject) => {
  996. const request = new XMLHttpRequest();
  997. request.open("GET", url, true);
  998. if (asTypedArray) {
  999. request.responseType = "arraybuffer";
  1000. }
  1001. request.onreadystatechange = () => {
  1002. if (request.readyState !== XMLHttpRequest.DONE) {
  1003. return;
  1004. }
  1005. if (request.status === 200 || request.status === 0) {
  1006. let data;
  1007. if (asTypedArray && request.response) {
  1008. data = new Uint8Array(request.response);
  1009. } else if (!asTypedArray && request.responseText) {
  1010. data = (0, _util.stringToBytes)(request.responseText);
  1011. }
  1012. if (data) {
  1013. resolve(data);
  1014. return;
  1015. }
  1016. }
  1017. reject(new Error(request.statusText));
  1018. };
  1019. request.send(null);
  1020. });
  1021. }
  1022. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  1023. _fetchData(url, compressionType) {
  1024. return fetchData(url, this.isCompressed).then(data => {
  1025. return {
  1026. cMapData: data,
  1027. compressionType
  1028. };
  1029. });
  1030. }
  1031. }
  1032. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  1033. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  1034. _fetchData(url) {
  1035. return fetchData(url, true);
  1036. }
  1037. }
  1038. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  1039. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  1040. _createSVG(type) {
  1041. return document.createElementNS(SVG_NS, type);
  1042. }
  1043. }
  1044. exports.DOMSVGFactory = DOMSVGFactory;
  1045. class PageViewport {
  1046. constructor({
  1047. viewBox,
  1048. scale,
  1049. rotation,
  1050. offsetX = 0,
  1051. offsetY = 0,
  1052. dontFlip = false
  1053. }) {
  1054. this.viewBox = viewBox;
  1055. this.scale = scale;
  1056. this.rotation = rotation;
  1057. this.offsetX = offsetX;
  1058. this.offsetY = offsetY;
  1059. const centerX = (viewBox[2] + viewBox[0]) / 2;
  1060. const centerY = (viewBox[3] + viewBox[1]) / 2;
  1061. let rotateA, rotateB, rotateC, rotateD;
  1062. rotation %= 360;
  1063. if (rotation < 0) {
  1064. rotation += 360;
  1065. }
  1066. switch (rotation) {
  1067. case 180:
  1068. rotateA = -1;
  1069. rotateB = 0;
  1070. rotateC = 0;
  1071. rotateD = 1;
  1072. break;
  1073. case 90:
  1074. rotateA = 0;
  1075. rotateB = 1;
  1076. rotateC = 1;
  1077. rotateD = 0;
  1078. break;
  1079. case 270:
  1080. rotateA = 0;
  1081. rotateB = -1;
  1082. rotateC = -1;
  1083. rotateD = 0;
  1084. break;
  1085. case 0:
  1086. rotateA = 1;
  1087. rotateB = 0;
  1088. rotateC = 0;
  1089. rotateD = -1;
  1090. break;
  1091. default:
  1092. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  1093. }
  1094. if (dontFlip) {
  1095. rotateC = -rotateC;
  1096. rotateD = -rotateD;
  1097. }
  1098. let offsetCanvasX, offsetCanvasY;
  1099. let width, height;
  1100. if (rotateA === 0) {
  1101. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  1102. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  1103. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  1104. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  1105. } else {
  1106. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  1107. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  1108. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  1109. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  1110. }
  1111. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  1112. this.width = width;
  1113. this.height = height;
  1114. }
  1115. clone({
  1116. scale = this.scale,
  1117. rotation = this.rotation,
  1118. offsetX = this.offsetX,
  1119. offsetY = this.offsetY,
  1120. dontFlip = false
  1121. } = {}) {
  1122. return new PageViewport({
  1123. viewBox: this.viewBox.slice(),
  1124. scale,
  1125. rotation,
  1126. offsetX,
  1127. offsetY,
  1128. dontFlip
  1129. });
  1130. }
  1131. convertToViewportPoint(x, y) {
  1132. return _util.Util.applyTransform([x, y], this.transform);
  1133. }
  1134. convertToViewportRectangle(rect) {
  1135. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  1136. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  1137. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  1138. }
  1139. convertToPdfPoint(x, y) {
  1140. return _util.Util.applyInverseTransform([x, y], this.transform);
  1141. }
  1142. }
  1143. exports.PageViewport = PageViewport;
  1144. class RenderingCancelledException extends _util.BaseException {
  1145. constructor(msg, type) {
  1146. super(msg, "RenderingCancelledException");
  1147. this.type = type;
  1148. }
  1149. }
  1150. exports.RenderingCancelledException = RenderingCancelledException;
  1151. function isDataScheme(url) {
  1152. const ii = url.length;
  1153. let i = 0;
  1154. while (i < ii && url[i].trim() === "") {
  1155. i++;
  1156. }
  1157. return url.substring(i, i + 5).toLowerCase() === "data:";
  1158. }
  1159. function isPdfFile(filename) {
  1160. return typeof filename === "string" && /\.pdf$/i.test(filename);
  1161. }
  1162. function getFilenameFromUrl(url) {
  1163. const anchor = url.indexOf("#");
  1164. const query = url.indexOf("?");
  1165. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  1166. return url.substring(url.lastIndexOf("/", end) + 1, end);
  1167. }
  1168. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  1169. if (typeof url !== "string") {
  1170. return defaultFilename;
  1171. }
  1172. if (isDataScheme(url)) {
  1173. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  1174. return defaultFilename;
  1175. }
  1176. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  1177. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  1178. const splitURI = reURI.exec(url);
  1179. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  1180. if (suggestedFilename) {
  1181. suggestedFilename = suggestedFilename[0];
  1182. if (suggestedFilename.includes("%")) {
  1183. try {
  1184. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  1185. } catch (ex) {}
  1186. }
  1187. }
  1188. return suggestedFilename || defaultFilename;
  1189. }
  1190. class StatTimer {
  1191. constructor() {
  1192. this.started = Object.create(null);
  1193. this.times = [];
  1194. }
  1195. time(name) {
  1196. if (name in this.started) {
  1197. (0, _util.warn)(`Timer is already running for ${name}`);
  1198. }
  1199. this.started[name] = Date.now();
  1200. }
  1201. timeEnd(name) {
  1202. if (!(name in this.started)) {
  1203. (0, _util.warn)(`Timer has not been started for ${name}`);
  1204. }
  1205. this.times.push({
  1206. name,
  1207. start: this.started[name],
  1208. end: Date.now()
  1209. });
  1210. delete this.started[name];
  1211. }
  1212. toString() {
  1213. const outBuf = [];
  1214. let longest = 0;
  1215. for (const time of this.times) {
  1216. const name = time.name;
  1217. if (name.length > longest) {
  1218. longest = name.length;
  1219. }
  1220. }
  1221. for (const time of this.times) {
  1222. const duration = time.end - time.start;
  1223. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  1224. }
  1225. return outBuf.join("");
  1226. }
  1227. }
  1228. exports.StatTimer = StatTimer;
  1229. function isValidFetchUrl(url, baseUrl) {
  1230. try {
  1231. const {
  1232. protocol
  1233. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  1234. return protocol === "http:" || protocol === "https:";
  1235. } catch (ex) {
  1236. return false;
  1237. }
  1238. }
  1239. function loadScript(src, removeScriptElement = false) {
  1240. return new Promise((resolve, reject) => {
  1241. const script = document.createElement("script");
  1242. script.src = src;
  1243. script.onload = function (evt) {
  1244. if (removeScriptElement) {
  1245. script.remove();
  1246. }
  1247. resolve(evt);
  1248. };
  1249. script.onerror = function () {
  1250. reject(new Error(`Cannot load script at: ${script.src}`));
  1251. };
  1252. (document.head || document.documentElement).append(script);
  1253. });
  1254. }
  1255. function deprecated(details) {
  1256. console.log("Deprecated API usage: " + details);
  1257. }
  1258. let pdfDateStringRegex;
  1259. class PDFDateString {
  1260. static toDateObject(input) {
  1261. if (!input || typeof input !== "string") {
  1262. return null;
  1263. }
  1264. if (!pdfDateStringRegex) {
  1265. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  1266. }
  1267. const matches = pdfDateStringRegex.exec(input);
  1268. if (!matches) {
  1269. return null;
  1270. }
  1271. const year = parseInt(matches[1], 10);
  1272. let month = parseInt(matches[2], 10);
  1273. month = month >= 1 && month <= 12 ? month - 1 : 0;
  1274. let day = parseInt(matches[3], 10);
  1275. day = day >= 1 && day <= 31 ? day : 1;
  1276. let hour = parseInt(matches[4], 10);
  1277. hour = hour >= 0 && hour <= 23 ? hour : 0;
  1278. let minute = parseInt(matches[5], 10);
  1279. minute = minute >= 0 && minute <= 59 ? minute : 0;
  1280. let second = parseInt(matches[6], 10);
  1281. second = second >= 0 && second <= 59 ? second : 0;
  1282. const universalTimeRelation = matches[7] || "Z";
  1283. let offsetHour = parseInt(matches[8], 10);
  1284. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  1285. let offsetMinute = parseInt(matches[9], 10) || 0;
  1286. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  1287. if (universalTimeRelation === "-") {
  1288. hour += offsetHour;
  1289. minute += offsetMinute;
  1290. } else if (universalTimeRelation === "+") {
  1291. hour -= offsetHour;
  1292. minute -= offsetMinute;
  1293. }
  1294. return new Date(Date.UTC(year, month, day, hour, minute, second));
  1295. }
  1296. }
  1297. exports.PDFDateString = PDFDateString;
  1298. function getXfaPageViewport(xfaPage, {
  1299. scale = 1,
  1300. rotation = 0
  1301. }) {
  1302. const {
  1303. width,
  1304. height
  1305. } = xfaPage.attributes.style;
  1306. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  1307. return new PageViewport({
  1308. viewBox,
  1309. scale,
  1310. rotation
  1311. });
  1312. }
  1313. function getRGB(color) {
  1314. if (color.startsWith("#")) {
  1315. const colorRGB = parseInt(color.slice(1), 16);
  1316. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  1317. }
  1318. if (color.startsWith("rgb(")) {
  1319. return color.slice(4, -1).split(",").map(x => parseInt(x));
  1320. }
  1321. if (color.startsWith("rgba(")) {
  1322. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  1323. }
  1324. (0, _util.warn)(`Not a valid color format: "${color}"`);
  1325. return [0, 0, 0];
  1326. }
  1327. function getColorValues(colors) {
  1328. const span = document.createElement("span");
  1329. span.style.visibility = "hidden";
  1330. document.body.append(span);
  1331. for (const name of colors.keys()) {
  1332. span.style.color = name;
  1333. const computedColor = window.getComputedStyle(span).color;
  1334. colors.set(name, getRGB(computedColor));
  1335. }
  1336. span.remove();
  1337. }
  1338. function binarySearchFirstItem(items, condition, start = 0) {
  1339. let minIndex = start;
  1340. let maxIndex = items.length - 1;
  1341. if (maxIndex < 0 || !condition(items[maxIndex])) {
  1342. return items.length;
  1343. }
  1344. if (condition(items[minIndex])) {
  1345. return minIndex;
  1346. }
  1347. while (minIndex < maxIndex) {
  1348. const currentIndex = minIndex + maxIndex >> 1;
  1349. const currentItem = items[currentIndex];
  1350. if (condition(currentItem)) {
  1351. maxIndex = currentIndex;
  1352. } else {
  1353. minIndex = currentIndex + 1;
  1354. }
  1355. }
  1356. return minIndex;
  1357. }
  1358. /***/ }),
  1359. /* 5 */
  1360. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1361. Object.defineProperty(exports, "__esModule", ({
  1362. value: true
  1363. }));
  1364. exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
  1365. var _util = __w_pdfjs_require__(1);
  1366. class BaseCanvasFactory {
  1367. constructor() {
  1368. if (this.constructor === BaseCanvasFactory) {
  1369. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  1370. }
  1371. }
  1372. create(width, height) {
  1373. if (width <= 0 || height <= 0) {
  1374. throw new Error("Invalid canvas size");
  1375. }
  1376. const canvas = this._createCanvas(width, height);
  1377. return {
  1378. canvas,
  1379. context: canvas.getContext("2d")
  1380. };
  1381. }
  1382. reset(canvasAndContext, width, height) {
  1383. if (!canvasAndContext.canvas) {
  1384. throw new Error("Canvas is not specified");
  1385. }
  1386. if (width <= 0 || height <= 0) {
  1387. throw new Error("Invalid canvas size");
  1388. }
  1389. canvasAndContext.canvas.width = width;
  1390. canvasAndContext.canvas.height = height;
  1391. }
  1392. destroy(canvasAndContext) {
  1393. if (!canvasAndContext.canvas) {
  1394. throw new Error("Canvas is not specified");
  1395. }
  1396. canvasAndContext.canvas.width = 0;
  1397. canvasAndContext.canvas.height = 0;
  1398. canvasAndContext.canvas = null;
  1399. canvasAndContext.context = null;
  1400. }
  1401. _createCanvas(width, height) {
  1402. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  1403. }
  1404. }
  1405. exports.BaseCanvasFactory = BaseCanvasFactory;
  1406. class BaseCMapReaderFactory {
  1407. constructor({
  1408. baseUrl = null,
  1409. isCompressed = false
  1410. }) {
  1411. if (this.constructor === BaseCMapReaderFactory) {
  1412. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  1413. }
  1414. this.baseUrl = baseUrl;
  1415. this.isCompressed = isCompressed;
  1416. }
  1417. async fetch({
  1418. name
  1419. }) {
  1420. if (!this.baseUrl) {
  1421. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  1422. }
  1423. if (!name) {
  1424. throw new Error("CMap name must be specified.");
  1425. }
  1426. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  1427. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  1428. return this._fetchData(url, compressionType).catch(reason => {
  1429. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  1430. });
  1431. }
  1432. _fetchData(url, compressionType) {
  1433. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  1434. }
  1435. }
  1436. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  1437. class BaseStandardFontDataFactory {
  1438. constructor({
  1439. baseUrl = null
  1440. }) {
  1441. if (this.constructor === BaseStandardFontDataFactory) {
  1442. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  1443. }
  1444. this.baseUrl = baseUrl;
  1445. }
  1446. async fetch({
  1447. filename
  1448. }) {
  1449. if (!this.baseUrl) {
  1450. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  1451. }
  1452. if (!filename) {
  1453. throw new Error("Font filename must be specified.");
  1454. }
  1455. const url = `${this.baseUrl}${filename}`;
  1456. return this._fetchData(url).catch(reason => {
  1457. throw new Error(`Unable to load font data at: ${url}`);
  1458. });
  1459. }
  1460. _fetchData(url) {
  1461. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  1462. }
  1463. }
  1464. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  1465. class BaseSVGFactory {
  1466. constructor() {
  1467. if (this.constructor === BaseSVGFactory) {
  1468. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  1469. }
  1470. }
  1471. create(width, height, skipDimensions = false) {
  1472. if (width <= 0 || height <= 0) {
  1473. throw new Error("Invalid SVG dimensions");
  1474. }
  1475. const svg = this._createSVG("svg:svg");
  1476. svg.setAttribute("version", "1.1");
  1477. if (!skipDimensions) {
  1478. svg.setAttribute("width", `${width}px`);
  1479. svg.setAttribute("height", `${height}px`);
  1480. }
  1481. svg.setAttribute("preserveAspectRatio", "none");
  1482. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  1483. return svg;
  1484. }
  1485. createElement(type) {
  1486. if (typeof type !== "string") {
  1487. throw new Error("Invalid SVG element type");
  1488. }
  1489. return this._createSVG(type);
  1490. }
  1491. _createSVG(type) {
  1492. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  1493. }
  1494. }
  1495. exports.BaseSVGFactory = BaseSVGFactory;
  1496. /***/ }),
  1497. /* 6 */
  1498. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1499. Object.defineProperty(exports, "__esModule", ({
  1500. value: true
  1501. }));
  1502. 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;
  1503. exports.getDocument = getDocument;
  1504. exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
  1505. exports.version = void 0;
  1506. var _util = __w_pdfjs_require__(1);
  1507. var _annotation_storage = __w_pdfjs_require__(7);
  1508. var _display_utils = __w_pdfjs_require__(4);
  1509. var _font_loader = __w_pdfjs_require__(11);
  1510. var _canvas = __w_pdfjs_require__(12);
  1511. var _worker_options = __w_pdfjs_require__(15);
  1512. var _is_node = __w_pdfjs_require__(3);
  1513. var _message_handler = __w_pdfjs_require__(16);
  1514. var _metadata = __w_pdfjs_require__(17);
  1515. var _optional_content_config = __w_pdfjs_require__(18);
  1516. var _transport_stream = __w_pdfjs_require__(19);
  1517. var _xfa_text = __w_pdfjs_require__(20);
  1518. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  1519. const RENDERING_CANCELLED_TIMEOUT = 100;
  1520. let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
  1521. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  1522. let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
  1523. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  1524. let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
  1525. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  1526. if (_is_node.isNodeJS) {
  1527. const {
  1528. NodeCanvasFactory,
  1529. NodeCMapReaderFactory,
  1530. NodeStandardFontDataFactory
  1531. } = __w_pdfjs_require__(21);
  1532. exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
  1533. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
  1534. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
  1535. }
  1536. let createPDFNetworkStream;
  1537. function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
  1538. createPDFNetworkStream = pdfNetworkStreamFactory;
  1539. }
  1540. function getDocument(src) {
  1541. const task = new PDFDocumentLoadingTask();
  1542. let source;
  1543. if (typeof src === "string" || src instanceof URL) {
  1544. source = {
  1545. url: src
  1546. };
  1547. } else if ((0, _util.isArrayBuffer)(src)) {
  1548. source = {
  1549. data: src
  1550. };
  1551. } else if (src instanceof PDFDataRangeTransport) {
  1552. source = {
  1553. range: src
  1554. };
  1555. } else {
  1556. if (typeof src !== "object") {
  1557. throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
  1558. }
  1559. if (!src.url && !src.data && !src.range) {
  1560. throw new Error("Invalid parameter object: need either .data, .range or .url");
  1561. }
  1562. source = src;
  1563. }
  1564. const params = Object.create(null);
  1565. let rangeTransport = null,
  1566. worker = null;
  1567. for (const key in source) {
  1568. const value = source[key];
  1569. switch (key) {
  1570. case "url":
  1571. if (typeof window !== "undefined") {
  1572. try {
  1573. params[key] = new URL(value, window.location).href;
  1574. continue;
  1575. } catch (ex) {
  1576. (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
  1577. }
  1578. } else if (typeof value === "string" || value instanceof URL) {
  1579. params[key] = value.toString();
  1580. continue;
  1581. }
  1582. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1583. case "range":
  1584. rangeTransport = value;
  1585. continue;
  1586. case "worker":
  1587. worker = value;
  1588. continue;
  1589. case "data":
  1590. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
  1591. params[key] = new Uint8Array(value);
  1592. } else if (value instanceof Uint8Array) {
  1593. break;
  1594. } else if (typeof value === "string") {
  1595. params[key] = (0, _util.stringToBytes)(value);
  1596. } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
  1597. params[key] = new Uint8Array(value);
  1598. } else if ((0, _util.isArrayBuffer)(value)) {
  1599. params[key] = new Uint8Array(value);
  1600. } else {
  1601. throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
  1602. }
  1603. continue;
  1604. }
  1605. params[key] = value;
  1606. }
  1607. params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
  1608. params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
  1609. params.ignoreErrors = params.stopAtErrors !== true;
  1610. params.fontExtraProperties = params.fontExtraProperties === true;
  1611. params.pdfBug = params.pdfBug === true;
  1612. params.enableXfa = params.enableXfa === true;
  1613. if (!Number.isInteger(params.rangeChunkSize) || params.rangeChunkSize < 1) {
  1614. params.rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE;
  1615. }
  1616. if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
  1617. params.docBaseUrl = null;
  1618. }
  1619. if (!Number.isInteger(params.maxImageSize) || params.maxImageSize < -1) {
  1620. params.maxImageSize = -1;
  1621. }
  1622. if (typeof params.cMapUrl !== "string") {
  1623. params.cMapUrl = null;
  1624. }
  1625. if (typeof params.standardFontDataUrl !== "string") {
  1626. params.standardFontDataUrl = null;
  1627. }
  1628. if (typeof params.useWorkerFetch !== "boolean") {
  1629. params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
  1630. }
  1631. if (typeof params.isEvalSupported !== "boolean") {
  1632. params.isEvalSupported = true;
  1633. }
  1634. if (typeof params.disableFontFace !== "boolean") {
  1635. params.disableFontFace = _is_node.isNodeJS;
  1636. }
  1637. if (typeof params.useSystemFonts !== "boolean") {
  1638. params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
  1639. }
  1640. if (typeof params.ownerDocument !== "object" || params.ownerDocument === null) {
  1641. params.ownerDocument = globalThis.document;
  1642. }
  1643. if (typeof params.disableRange !== "boolean") {
  1644. params.disableRange = false;
  1645. }
  1646. if (typeof params.disableStream !== "boolean") {
  1647. params.disableStream = false;
  1648. }
  1649. if (typeof params.disableAutoFetch !== "boolean") {
  1650. params.disableAutoFetch = false;
  1651. }
  1652. (0, _util.setVerbosityLevel)(params.verbosity);
  1653. if (!worker) {
  1654. const workerParams = {
  1655. verbosity: params.verbosity,
  1656. port: _worker_options.GlobalWorkerOptions.workerPort
  1657. };
  1658. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  1659. task._worker = worker;
  1660. }
  1661. const docId = task.docId;
  1662. worker.promise.then(function () {
  1663. if (task.destroyed) {
  1664. throw new Error("Loading aborted");
  1665. }
  1666. const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
  1667. const networkStreamPromise = new Promise(function (resolve) {
  1668. let networkStream;
  1669. if (rangeTransport) {
  1670. networkStream = new _transport_stream.PDFDataTransportStream({
  1671. length: params.length,
  1672. initialData: params.initialData,
  1673. progressiveDone: params.progressiveDone,
  1674. contentDispositionFilename: params.contentDispositionFilename,
  1675. disableRange: params.disableRange,
  1676. disableStream: params.disableStream
  1677. }, rangeTransport);
  1678. } else if (!params.data) {
  1679. networkStream = createPDFNetworkStream({
  1680. url: params.url,
  1681. length: params.length,
  1682. httpHeaders: params.httpHeaders,
  1683. withCredentials: params.withCredentials,
  1684. rangeChunkSize: params.rangeChunkSize,
  1685. disableRange: params.disableRange,
  1686. disableStream: params.disableStream
  1687. });
  1688. }
  1689. resolve(networkStream);
  1690. });
  1691. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1692. if (task.destroyed) {
  1693. throw new Error("Loading aborted");
  1694. }
  1695. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1696. const transport = new WorkerTransport(messageHandler, task, networkStream, params);
  1697. task._transport = transport;
  1698. messageHandler.send("Ready", null);
  1699. });
  1700. }).catch(task._capability.reject);
  1701. return task;
  1702. }
  1703. async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  1704. if (worker.destroyed) {
  1705. throw new Error("Worker was destroyed");
  1706. }
  1707. if (pdfDataRangeTransport) {
  1708. source.length = pdfDataRangeTransport.length;
  1709. source.initialData = pdfDataRangeTransport.initialData;
  1710. source.progressiveDone = pdfDataRangeTransport.progressiveDone;
  1711. source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
  1712. }
  1713. const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
  1714. docId,
  1715. apiVersion: '2.15.349',
  1716. source: {
  1717. data: source.data,
  1718. url: source.url,
  1719. password: source.password,
  1720. disableAutoFetch: source.disableAutoFetch,
  1721. rangeChunkSize: source.rangeChunkSize,
  1722. length: source.length
  1723. },
  1724. maxImageSize: source.maxImageSize,
  1725. disableFontFace: source.disableFontFace,
  1726. docBaseUrl: source.docBaseUrl,
  1727. ignoreErrors: source.ignoreErrors,
  1728. isEvalSupported: source.isEvalSupported,
  1729. fontExtraProperties: source.fontExtraProperties,
  1730. enableXfa: source.enableXfa,
  1731. useSystemFonts: source.useSystemFonts,
  1732. cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
  1733. standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
  1734. });
  1735. if (source.data) {
  1736. source.data = null;
  1737. }
  1738. if (worker.destroyed) {
  1739. throw new Error("Worker was destroyed");
  1740. }
  1741. return workerId;
  1742. }
  1743. class PDFDocumentLoadingTask {
  1744. static #docId = 0;
  1745. constructor() {
  1746. this._capability = (0, _util.createPromiseCapability)();
  1747. this._transport = null;
  1748. this._worker = null;
  1749. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  1750. this.destroyed = false;
  1751. this.onPassword = null;
  1752. this.onProgress = null;
  1753. this.onUnsupportedFeature = null;
  1754. }
  1755. get promise() {
  1756. return this._capability.promise;
  1757. }
  1758. async destroy() {
  1759. this.destroyed = true;
  1760. await this._transport?.destroy();
  1761. this._transport = null;
  1762. if (this._worker) {
  1763. this._worker.destroy();
  1764. this._worker = null;
  1765. }
  1766. }
  1767. }
  1768. exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
  1769. class PDFDataRangeTransport {
  1770. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1771. this.length = length;
  1772. this.initialData = initialData;
  1773. this.progressiveDone = progressiveDone;
  1774. this.contentDispositionFilename = contentDispositionFilename;
  1775. this._rangeListeners = [];
  1776. this._progressListeners = [];
  1777. this._progressiveReadListeners = [];
  1778. this._progressiveDoneListeners = [];
  1779. this._readyCapability = (0, _util.createPromiseCapability)();
  1780. }
  1781. addRangeListener(listener) {
  1782. this._rangeListeners.push(listener);
  1783. }
  1784. addProgressListener(listener) {
  1785. this._progressListeners.push(listener);
  1786. }
  1787. addProgressiveReadListener(listener) {
  1788. this._progressiveReadListeners.push(listener);
  1789. }
  1790. addProgressiveDoneListener(listener) {
  1791. this._progressiveDoneListeners.push(listener);
  1792. }
  1793. onDataRange(begin, chunk) {
  1794. for (const listener of this._rangeListeners) {
  1795. listener(begin, chunk);
  1796. }
  1797. }
  1798. onDataProgress(loaded, total) {
  1799. this._readyCapability.promise.then(() => {
  1800. for (const listener of this._progressListeners) {
  1801. listener(loaded, total);
  1802. }
  1803. });
  1804. }
  1805. onDataProgressiveRead(chunk) {
  1806. this._readyCapability.promise.then(() => {
  1807. for (const listener of this._progressiveReadListeners) {
  1808. listener(chunk);
  1809. }
  1810. });
  1811. }
  1812. onDataProgressiveDone() {
  1813. this._readyCapability.promise.then(() => {
  1814. for (const listener of this._progressiveDoneListeners) {
  1815. listener();
  1816. }
  1817. });
  1818. }
  1819. transportReady() {
  1820. this._readyCapability.resolve();
  1821. }
  1822. requestDataRange(begin, end) {
  1823. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1824. }
  1825. abort() {}
  1826. }
  1827. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1828. class PDFDocumentProxy {
  1829. constructor(pdfInfo, transport) {
  1830. this._pdfInfo = pdfInfo;
  1831. this._transport = transport;
  1832. Object.defineProperty(this, "fingerprint", {
  1833. get() {
  1834. (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
  1835. return this.fingerprints[0];
  1836. }
  1837. });
  1838. Object.defineProperty(this, "getStats", {
  1839. value: async () => {
  1840. (0, _display_utils.deprecated)("`PDFDocumentProxy.getStats`, " + "please use the `PDFDocumentProxy.stats`-getter instead.");
  1841. return this.stats || {
  1842. streamTypes: {},
  1843. fontTypes: {}
  1844. };
  1845. }
  1846. });
  1847. }
  1848. get annotationStorage() {
  1849. return this._transport.annotationStorage;
  1850. }
  1851. get numPages() {
  1852. return this._pdfInfo.numPages;
  1853. }
  1854. get fingerprints() {
  1855. return this._pdfInfo.fingerprints;
  1856. }
  1857. get stats() {
  1858. return this._transport.stats;
  1859. }
  1860. get isPureXfa() {
  1861. return !!this._transport._htmlForXfa;
  1862. }
  1863. get allXfaHtml() {
  1864. return this._transport._htmlForXfa;
  1865. }
  1866. getPage(pageNumber) {
  1867. return this._transport.getPage(pageNumber);
  1868. }
  1869. getPageIndex(ref) {
  1870. return this._transport.getPageIndex(ref);
  1871. }
  1872. getDestinations() {
  1873. return this._transport.getDestinations();
  1874. }
  1875. getDestination(id) {
  1876. return this._transport.getDestination(id);
  1877. }
  1878. getPageLabels() {
  1879. return this._transport.getPageLabels();
  1880. }
  1881. getPageLayout() {
  1882. return this._transport.getPageLayout();
  1883. }
  1884. getPageMode() {
  1885. return this._transport.getPageMode();
  1886. }
  1887. getViewerPreferences() {
  1888. return this._transport.getViewerPreferences();
  1889. }
  1890. getOpenAction() {
  1891. return this._transport.getOpenAction();
  1892. }
  1893. getAttachments() {
  1894. return this._transport.getAttachments();
  1895. }
  1896. getJavaScript() {
  1897. return this._transport.getJavaScript();
  1898. }
  1899. getJSActions() {
  1900. return this._transport.getDocJSActions();
  1901. }
  1902. getOutline() {
  1903. return this._transport.getOutline();
  1904. }
  1905. getOptionalContentConfig() {
  1906. return this._transport.getOptionalContentConfig();
  1907. }
  1908. getPermissions() {
  1909. return this._transport.getPermissions();
  1910. }
  1911. getMetadata() {
  1912. return this._transport.getMetadata();
  1913. }
  1914. getMarkInfo() {
  1915. return this._transport.getMarkInfo();
  1916. }
  1917. getData() {
  1918. return this._transport.getData();
  1919. }
  1920. getDownloadInfo() {
  1921. return this._transport.downloadInfoCapability.promise;
  1922. }
  1923. cleanup(keepLoadedFonts = false) {
  1924. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1925. }
  1926. destroy() {
  1927. return this.loadingTask.destroy();
  1928. }
  1929. get loadingParams() {
  1930. return this._transport.loadingParams;
  1931. }
  1932. get loadingTask() {
  1933. return this._transport.loadingTask;
  1934. }
  1935. saveDocument() {
  1936. if (this._transport.annotationStorage.size <= 0) {
  1937. (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  1938. }
  1939. return this._transport.saveDocument();
  1940. }
  1941. getFieldObjects() {
  1942. return this._transport.getFieldObjects();
  1943. }
  1944. hasJSActions() {
  1945. return this._transport.hasJSActions();
  1946. }
  1947. getCalculationOrderIds() {
  1948. return this._transport.getCalculationOrderIds();
  1949. }
  1950. }
  1951. exports.PDFDocumentProxy = PDFDocumentProxy;
  1952. class PDFPageProxy {
  1953. constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
  1954. this._pageIndex = pageIndex;
  1955. this._pageInfo = pageInfo;
  1956. this._ownerDocument = ownerDocument;
  1957. this._transport = transport;
  1958. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1959. this._pdfBug = pdfBug;
  1960. this.commonObjs = transport.commonObjs;
  1961. this.objs = new PDFObjects();
  1962. this._bitmaps = new Set();
  1963. this.cleanupAfterRender = false;
  1964. this.pendingCleanup = false;
  1965. this._intentStates = new Map();
  1966. this._annotationPromises = new Map();
  1967. this.destroyed = false;
  1968. }
  1969. get pageNumber() {
  1970. return this._pageIndex + 1;
  1971. }
  1972. get rotate() {
  1973. return this._pageInfo.rotate;
  1974. }
  1975. get ref() {
  1976. return this._pageInfo.ref;
  1977. }
  1978. get userUnit() {
  1979. return this._pageInfo.userUnit;
  1980. }
  1981. get view() {
  1982. return this._pageInfo.view;
  1983. }
  1984. getViewport({
  1985. scale,
  1986. rotation = this.rotate,
  1987. offsetX = 0,
  1988. offsetY = 0,
  1989. dontFlip = false
  1990. } = {}) {
  1991. return new _display_utils.PageViewport({
  1992. viewBox: this.view,
  1993. scale,
  1994. rotation,
  1995. offsetX,
  1996. offsetY,
  1997. dontFlip
  1998. });
  1999. }
  2000. getAnnotations({
  2001. intent = "display"
  2002. } = {}) {
  2003. const intentArgs = this._transport.getRenderingIntent(intent);
  2004. let promise = this._annotationPromises.get(intentArgs.cacheKey);
  2005. if (!promise) {
  2006. promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  2007. this._annotationPromises.set(intentArgs.cacheKey, promise);
  2008. promise = promise.then(annotations => {
  2009. for (const annotation of annotations) {
  2010. if (annotation.titleObj !== undefined) {
  2011. Object.defineProperty(annotation, "title", {
  2012. get() {
  2013. (0, _display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead.");
  2014. return annotation.titleObj.str;
  2015. }
  2016. });
  2017. }
  2018. if (annotation.contentsObj !== undefined) {
  2019. Object.defineProperty(annotation, "contents", {
  2020. get() {
  2021. (0, _display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead.");
  2022. return annotation.contentsObj.str;
  2023. }
  2024. });
  2025. }
  2026. }
  2027. return annotations;
  2028. });
  2029. }
  2030. return promise;
  2031. }
  2032. getJSActions() {
  2033. return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
  2034. }
  2035. async getXfa() {
  2036. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  2037. }
  2038. render({
  2039. canvasContext,
  2040. viewport,
  2041. intent = "display",
  2042. annotationMode = _util.AnnotationMode.ENABLE,
  2043. transform = null,
  2044. imageLayer = null,
  2045. canvasFactory = null,
  2046. background = null,
  2047. optionalContentConfigPromise = null,
  2048. annotationCanvasMap = null,
  2049. pageColors = null,
  2050. printAnnotationStorage = null
  2051. }) {
  2052. if (arguments[0]?.renderInteractiveForms !== undefined) {
  2053. (0, _display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, " + "please use the `annotationMode`-option instead.");
  2054. if (arguments[0].renderInteractiveForms === true && annotationMode === _util.AnnotationMode.ENABLE) {
  2055. annotationMode = _util.AnnotationMode.ENABLE_FORMS;
  2056. }
  2057. }
  2058. if (arguments[0]?.includeAnnotationStorage !== undefined) {
  2059. (0, _display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, " + "please use the `annotationMode`-option instead.");
  2060. if (arguments[0].includeAnnotationStorage === true && annotationMode === _util.AnnotationMode.ENABLE) {
  2061. annotationMode = _util.AnnotationMode.ENABLE_STORAGE;
  2062. }
  2063. }
  2064. if (this._stats) {
  2065. this._stats.time("Overall");
  2066. }
  2067. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
  2068. this.pendingCleanup = false;
  2069. if (!optionalContentConfigPromise) {
  2070. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  2071. }
  2072. let intentState = this._intentStates.get(intentArgs.cacheKey);
  2073. if (!intentState) {
  2074. intentState = Object.create(null);
  2075. this._intentStates.set(intentArgs.cacheKey, intentState);
  2076. }
  2077. if (intentState.streamReaderCancelTimeout) {
  2078. clearTimeout(intentState.streamReaderCancelTimeout);
  2079. intentState.streamReaderCancelTimeout = null;
  2080. }
  2081. const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
  2082. ownerDocument: this._ownerDocument
  2083. });
  2084. const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
  2085. if (!intentState.displayReadyCapability) {
  2086. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  2087. intentState.operatorList = {
  2088. fnArray: [],
  2089. argsArray: [],
  2090. lastChunk: false,
  2091. separateAnnots: null
  2092. };
  2093. if (this._stats) {
  2094. this._stats.time("Page Request");
  2095. }
  2096. this._pumpOperatorList(intentArgs);
  2097. }
  2098. const complete = error => {
  2099. intentState.renderTasks.delete(internalRenderTask);
  2100. if (this.cleanupAfterRender || intentPrint) {
  2101. this.pendingCleanup = true;
  2102. }
  2103. this._tryCleanup();
  2104. if (error) {
  2105. internalRenderTask.capability.reject(error);
  2106. this._abortOperatorList({
  2107. intentState,
  2108. reason: error instanceof Error ? error : new Error(error)
  2109. });
  2110. } else {
  2111. internalRenderTask.capability.resolve();
  2112. }
  2113. if (this._stats) {
  2114. this._stats.timeEnd("Rendering");
  2115. this._stats.timeEnd("Overall");
  2116. }
  2117. };
  2118. const internalRenderTask = new InternalRenderTask({
  2119. callback: complete,
  2120. params: {
  2121. canvasContext,
  2122. viewport,
  2123. transform,
  2124. imageLayer,
  2125. background
  2126. },
  2127. objs: this.objs,
  2128. commonObjs: this.commonObjs,
  2129. annotationCanvasMap,
  2130. operatorList: intentState.operatorList,
  2131. pageIndex: this._pageIndex,
  2132. canvasFactory: canvasFactoryInstance,
  2133. useRequestAnimationFrame: !intentPrint,
  2134. pdfBug: this._pdfBug,
  2135. pageColors
  2136. });
  2137. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  2138. const renderTask = internalRenderTask.task;
  2139. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  2140. if (this.pendingCleanup) {
  2141. complete();
  2142. return;
  2143. }
  2144. if (this._stats) {
  2145. this._stats.time("Rendering");
  2146. }
  2147. internalRenderTask.initializeGraphics({
  2148. transparency,
  2149. optionalContentConfig
  2150. });
  2151. internalRenderTask.operatorListChanged();
  2152. }).catch(complete);
  2153. return renderTask;
  2154. }
  2155. getOperatorList({
  2156. intent = "display",
  2157. annotationMode = _util.AnnotationMode.ENABLE,
  2158. printAnnotationStorage = null
  2159. } = {}) {
  2160. function operatorListChanged() {
  2161. if (intentState.operatorList.lastChunk) {
  2162. intentState.opListReadCapability.resolve(intentState.operatorList);
  2163. intentState.renderTasks.delete(opListTask);
  2164. }
  2165. }
  2166. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
  2167. let intentState = this._intentStates.get(intentArgs.cacheKey);
  2168. if (!intentState) {
  2169. intentState = Object.create(null);
  2170. this._intentStates.set(intentArgs.cacheKey, intentState);
  2171. }
  2172. let opListTask;
  2173. if (!intentState.opListReadCapability) {
  2174. opListTask = Object.create(null);
  2175. opListTask.operatorListChanged = operatorListChanged;
  2176. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  2177. (intentState.renderTasks ||= new Set()).add(opListTask);
  2178. intentState.operatorList = {
  2179. fnArray: [],
  2180. argsArray: [],
  2181. lastChunk: false,
  2182. separateAnnots: null
  2183. };
  2184. if (this._stats) {
  2185. this._stats.time("Page Request");
  2186. }
  2187. this._pumpOperatorList(intentArgs);
  2188. }
  2189. return intentState.opListReadCapability.promise;
  2190. }
  2191. streamTextContent({
  2192. disableCombineTextItems = false,
  2193. includeMarkedContent = false
  2194. } = {}) {
  2195. const TEXT_CONTENT_CHUNK_SIZE = 100;
  2196. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  2197. pageIndex: this._pageIndex,
  2198. combineTextItems: disableCombineTextItems !== true,
  2199. includeMarkedContent: includeMarkedContent === true
  2200. }, {
  2201. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  2202. size(textContent) {
  2203. return textContent.items.length;
  2204. }
  2205. });
  2206. }
  2207. getTextContent(params = {}) {
  2208. if (this._transport._htmlForXfa) {
  2209. return this.getXfa().then(xfa => {
  2210. return _xfa_text.XfaText.textContent(xfa);
  2211. });
  2212. }
  2213. const readableStream = this.streamTextContent(params);
  2214. return new Promise(function (resolve, reject) {
  2215. function pump() {
  2216. reader.read().then(function ({
  2217. value,
  2218. done
  2219. }) {
  2220. if (done) {
  2221. resolve(textContent);
  2222. return;
  2223. }
  2224. Object.assign(textContent.styles, value.styles);
  2225. textContent.items.push(...value.items);
  2226. pump();
  2227. }, reject);
  2228. }
  2229. const reader = readableStream.getReader();
  2230. const textContent = {
  2231. items: [],
  2232. styles: Object.create(null)
  2233. };
  2234. pump();
  2235. });
  2236. }
  2237. getStructTree() {
  2238. return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
  2239. }
  2240. _destroy() {
  2241. this.destroyed = true;
  2242. const waitOn = [];
  2243. for (const intentState of this._intentStates.values()) {
  2244. this._abortOperatorList({
  2245. intentState,
  2246. reason: new Error("Page was destroyed."),
  2247. force: true
  2248. });
  2249. if (intentState.opListReadCapability) {
  2250. continue;
  2251. }
  2252. for (const internalRenderTask of intentState.renderTasks) {
  2253. waitOn.push(internalRenderTask.completed);
  2254. internalRenderTask.cancel();
  2255. }
  2256. }
  2257. this.objs.clear();
  2258. for (const bitmap of this._bitmaps) {
  2259. bitmap.close();
  2260. }
  2261. this._bitmaps.clear();
  2262. this._annotationPromises.clear();
  2263. this._jsActionsPromise = null;
  2264. this._structTreePromise = null;
  2265. this.pendingCleanup = false;
  2266. return Promise.all(waitOn);
  2267. }
  2268. cleanup(resetStats = false) {
  2269. this.pendingCleanup = true;
  2270. return this._tryCleanup(resetStats);
  2271. }
  2272. _tryCleanup(resetStats = false) {
  2273. if (!this.pendingCleanup) {
  2274. return false;
  2275. }
  2276. for (const {
  2277. renderTasks,
  2278. operatorList
  2279. } of this._intentStates.values()) {
  2280. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  2281. return false;
  2282. }
  2283. }
  2284. this._intentStates.clear();
  2285. this.objs.clear();
  2286. this._annotationPromises.clear();
  2287. this._jsActionsPromise = null;
  2288. this._structTreePromise = null;
  2289. if (resetStats && this._stats) {
  2290. this._stats = new _display_utils.StatTimer();
  2291. }
  2292. for (const bitmap of this._bitmaps) {
  2293. bitmap.close();
  2294. }
  2295. this._bitmaps.clear();
  2296. this.pendingCleanup = false;
  2297. return true;
  2298. }
  2299. _startRenderPage(transparency, cacheKey) {
  2300. const intentState = this._intentStates.get(cacheKey);
  2301. if (!intentState) {
  2302. return;
  2303. }
  2304. if (this._stats) {
  2305. this._stats.timeEnd("Page Request");
  2306. }
  2307. if (intentState.displayReadyCapability) {
  2308. intentState.displayReadyCapability.resolve(transparency);
  2309. }
  2310. }
  2311. _renderPageChunk(operatorListChunk, intentState) {
  2312. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2313. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2314. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  2315. }
  2316. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2317. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  2318. for (const internalRenderTask of intentState.renderTasks) {
  2319. internalRenderTask.operatorListChanged();
  2320. }
  2321. if (operatorListChunk.lastChunk) {
  2322. this._tryCleanup();
  2323. }
  2324. }
  2325. _pumpOperatorList({
  2326. renderingIntent,
  2327. cacheKey,
  2328. annotationStorageMap
  2329. }) {
  2330. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  2331. pageIndex: this._pageIndex,
  2332. intent: renderingIntent,
  2333. cacheKey,
  2334. annotationStorage: annotationStorageMap
  2335. });
  2336. const reader = readableStream.getReader();
  2337. const intentState = this._intentStates.get(cacheKey);
  2338. intentState.streamReader = reader;
  2339. const pump = () => {
  2340. reader.read().then(({
  2341. value,
  2342. done
  2343. }) => {
  2344. if (done) {
  2345. intentState.streamReader = null;
  2346. return;
  2347. }
  2348. if (this._transport.destroyed) {
  2349. return;
  2350. }
  2351. this._renderPageChunk(value, intentState);
  2352. pump();
  2353. }, reason => {
  2354. intentState.streamReader = null;
  2355. if (this._transport.destroyed) {
  2356. return;
  2357. }
  2358. if (intentState.operatorList) {
  2359. intentState.operatorList.lastChunk = true;
  2360. for (const internalRenderTask of intentState.renderTasks) {
  2361. internalRenderTask.operatorListChanged();
  2362. }
  2363. this._tryCleanup();
  2364. }
  2365. if (intentState.displayReadyCapability) {
  2366. intentState.displayReadyCapability.reject(reason);
  2367. } else if (intentState.opListReadCapability) {
  2368. intentState.opListReadCapability.reject(reason);
  2369. } else {
  2370. throw reason;
  2371. }
  2372. });
  2373. };
  2374. pump();
  2375. }
  2376. _abortOperatorList({
  2377. intentState,
  2378. reason,
  2379. force = false
  2380. }) {
  2381. if (!intentState.streamReader) {
  2382. return;
  2383. }
  2384. if (!force) {
  2385. if (intentState.renderTasks.size > 0) {
  2386. return;
  2387. }
  2388. if (reason instanceof _display_utils.RenderingCancelledException) {
  2389. intentState.streamReaderCancelTimeout = setTimeout(() => {
  2390. this._abortOperatorList({
  2391. intentState,
  2392. reason,
  2393. force: true
  2394. });
  2395. intentState.streamReaderCancelTimeout = null;
  2396. }, RENDERING_CANCELLED_TIMEOUT);
  2397. return;
  2398. }
  2399. }
  2400. intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
  2401. intentState.streamReader = null;
  2402. if (this._transport.destroyed) {
  2403. return;
  2404. }
  2405. for (const [curCacheKey, curIntentState] of this._intentStates) {
  2406. if (curIntentState === intentState) {
  2407. this._intentStates.delete(curCacheKey);
  2408. break;
  2409. }
  2410. }
  2411. this.cleanup();
  2412. }
  2413. get stats() {
  2414. return this._stats;
  2415. }
  2416. }
  2417. exports.PDFPageProxy = PDFPageProxy;
  2418. class LoopbackPort {
  2419. constructor() {
  2420. this._listeners = [];
  2421. this._deferred = Promise.resolve();
  2422. }
  2423. postMessage(obj, transfers) {
  2424. const event = {
  2425. data: structuredClone(obj, transfers)
  2426. };
  2427. this._deferred.then(() => {
  2428. for (const listener of this._listeners) {
  2429. listener.call(this, event);
  2430. }
  2431. });
  2432. }
  2433. addEventListener(name, listener) {
  2434. this._listeners.push(listener);
  2435. }
  2436. removeEventListener(name, listener) {
  2437. const i = this._listeners.indexOf(listener);
  2438. this._listeners.splice(i, 1);
  2439. }
  2440. terminate() {
  2441. this._listeners.length = 0;
  2442. }
  2443. }
  2444. exports.LoopbackPort = LoopbackPort;
  2445. const PDFWorkerUtil = {
  2446. isWorkerDisabled: false,
  2447. fallbackWorkerSrc: null,
  2448. fakeWorkerId: 0
  2449. };
  2450. exports.PDFWorkerUtil = PDFWorkerUtil;
  2451. {
  2452. if (_is_node.isNodeJS && typeof require === "function") {
  2453. PDFWorkerUtil.isWorkerDisabled = true;
  2454. PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  2455. } else if (typeof document === "object") {
  2456. const pdfjsFilePath = document?.currentScript?.src;
  2457. if (pdfjsFilePath) {
  2458. PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  2459. }
  2460. }
  2461. PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
  2462. let base;
  2463. try {
  2464. base = new URL(baseUrl);
  2465. if (!base.origin || base.origin === "null") {
  2466. return false;
  2467. }
  2468. } catch (e) {
  2469. return false;
  2470. }
  2471. const other = new URL(otherUrl, base);
  2472. return base.origin === other.origin;
  2473. };
  2474. PDFWorkerUtil.createCDNWrapper = function (url) {
  2475. const wrapper = `importScripts("${url}");`;
  2476. return URL.createObjectURL(new Blob([wrapper]));
  2477. };
  2478. }
  2479. class PDFWorker {
  2480. static #workerPorts = new WeakMap();
  2481. constructor({
  2482. name = null,
  2483. port = null,
  2484. verbosity = (0, _util.getVerbosityLevel)()
  2485. } = {}) {
  2486. if (port && PDFWorker.#workerPorts.has(port)) {
  2487. throw new Error("Cannot use more than one PDFWorker per port.");
  2488. }
  2489. this.name = name;
  2490. this.destroyed = false;
  2491. this.verbosity = verbosity;
  2492. this._readyCapability = (0, _util.createPromiseCapability)();
  2493. this._port = null;
  2494. this._webWorker = null;
  2495. this._messageHandler = null;
  2496. if (port) {
  2497. PDFWorker.#workerPorts.set(port, this);
  2498. this._initializeFromPort(port);
  2499. return;
  2500. }
  2501. this._initialize();
  2502. }
  2503. get promise() {
  2504. return this._readyCapability.promise;
  2505. }
  2506. get port() {
  2507. return this._port;
  2508. }
  2509. get messageHandler() {
  2510. return this._messageHandler;
  2511. }
  2512. _initializeFromPort(port) {
  2513. this._port = port;
  2514. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  2515. this._messageHandler.on("ready", function () {});
  2516. this._readyCapability.resolve();
  2517. }
  2518. _initialize() {
  2519. if (typeof Worker !== "undefined" && !PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
  2520. let workerSrc = PDFWorker.workerSrc;
  2521. try {
  2522. if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
  2523. workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
  2524. }
  2525. const worker = new Worker(workerSrc);
  2526. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  2527. const terminateEarly = () => {
  2528. worker.removeEventListener("error", onWorkerError);
  2529. messageHandler.destroy();
  2530. worker.terminate();
  2531. if (this.destroyed) {
  2532. this._readyCapability.reject(new Error("Worker was destroyed"));
  2533. } else {
  2534. this._setupFakeWorker();
  2535. }
  2536. };
  2537. const onWorkerError = () => {
  2538. if (!this._webWorker) {
  2539. terminateEarly();
  2540. }
  2541. };
  2542. worker.addEventListener("error", onWorkerError);
  2543. messageHandler.on("test", data => {
  2544. worker.removeEventListener("error", onWorkerError);
  2545. if (this.destroyed) {
  2546. terminateEarly();
  2547. return;
  2548. }
  2549. if (data) {
  2550. this._messageHandler = messageHandler;
  2551. this._port = worker;
  2552. this._webWorker = worker;
  2553. this._readyCapability.resolve();
  2554. messageHandler.send("configure", {
  2555. verbosity: this.verbosity
  2556. });
  2557. } else {
  2558. this._setupFakeWorker();
  2559. messageHandler.destroy();
  2560. worker.terminate();
  2561. }
  2562. });
  2563. messageHandler.on("ready", data => {
  2564. worker.removeEventListener("error", onWorkerError);
  2565. if (this.destroyed) {
  2566. terminateEarly();
  2567. return;
  2568. }
  2569. try {
  2570. sendTest();
  2571. } catch (e) {
  2572. this._setupFakeWorker();
  2573. }
  2574. });
  2575. const sendTest = () => {
  2576. const testObj = new Uint8Array();
  2577. messageHandler.send("test", testObj, [testObj.buffer]);
  2578. };
  2579. sendTest();
  2580. return;
  2581. } catch (e) {
  2582. (0, _util.info)("The worker has been disabled.");
  2583. }
  2584. }
  2585. this._setupFakeWorker();
  2586. }
  2587. _setupFakeWorker() {
  2588. if (!PDFWorkerUtil.isWorkerDisabled) {
  2589. (0, _util.warn)("Setting up fake worker.");
  2590. PDFWorkerUtil.isWorkerDisabled = true;
  2591. }
  2592. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  2593. if (this.destroyed) {
  2594. this._readyCapability.reject(new Error("Worker was destroyed"));
  2595. return;
  2596. }
  2597. const port = new LoopbackPort();
  2598. this._port = port;
  2599. const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
  2600. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  2601. WorkerMessageHandler.setup(workerHandler, port);
  2602. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  2603. this._messageHandler = messageHandler;
  2604. this._readyCapability.resolve();
  2605. messageHandler.send("configure", {
  2606. verbosity: this.verbosity
  2607. });
  2608. }).catch(reason => {
  2609. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  2610. });
  2611. }
  2612. destroy() {
  2613. this.destroyed = true;
  2614. if (this._webWorker) {
  2615. this._webWorker.terminate();
  2616. this._webWorker = null;
  2617. }
  2618. PDFWorker.#workerPorts.delete(this._port);
  2619. this._port = null;
  2620. if (this._messageHandler) {
  2621. this._messageHandler.destroy();
  2622. this._messageHandler = null;
  2623. }
  2624. }
  2625. static fromPort(params) {
  2626. if (!params?.port) {
  2627. throw new Error("PDFWorker.fromPort - invalid method signature.");
  2628. }
  2629. if (this.#workerPorts.has(params.port)) {
  2630. return this.#workerPorts.get(params.port);
  2631. }
  2632. return new PDFWorker(params);
  2633. }
  2634. static get workerSrc() {
  2635. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  2636. return _worker_options.GlobalWorkerOptions.workerSrc;
  2637. }
  2638. if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
  2639. if (!_is_node.isNodeJS) {
  2640. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  2641. }
  2642. return PDFWorkerUtil.fallbackWorkerSrc;
  2643. }
  2644. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  2645. }
  2646. static get _mainThreadWorkerMessageHandler() {
  2647. try {
  2648. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  2649. } catch (ex) {
  2650. return null;
  2651. }
  2652. }
  2653. static get _setupFakeWorkerGlobal() {
  2654. const loader = async () => {
  2655. const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
  2656. if (mainWorkerMessageHandler) {
  2657. return mainWorkerMessageHandler;
  2658. }
  2659. if (_is_node.isNodeJS && typeof require === "function") {
  2660. const worker = eval("require")(this.workerSrc);
  2661. return worker.WorkerMessageHandler;
  2662. }
  2663. await (0, _display_utils.loadScript)(this.workerSrc);
  2664. return window.pdfjsWorker.WorkerMessageHandler;
  2665. };
  2666. return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  2667. }
  2668. }
  2669. exports.PDFWorker = PDFWorker;
  2670. {
  2671. PDFWorker.getWorkerSrc = function () {
  2672. (0, _display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead.");
  2673. return this.workerSrc;
  2674. };
  2675. }
  2676. class WorkerTransport {
  2677. #docStats = null;
  2678. #pageCache = new Map();
  2679. #pagePromises = new Map();
  2680. #metadataPromise = null;
  2681. constructor(messageHandler, loadingTask, networkStream, params) {
  2682. this.messageHandler = messageHandler;
  2683. this.loadingTask = loadingTask;
  2684. this.commonObjs = new PDFObjects();
  2685. this.fontLoader = new _font_loader.FontLoader({
  2686. docId: loadingTask.docId,
  2687. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2688. ownerDocument: params.ownerDocument,
  2689. styleElement: params.styleElement
  2690. });
  2691. this._params = params;
  2692. if (!params.useWorkerFetch) {
  2693. this.CMapReaderFactory = new params.CMapReaderFactory({
  2694. baseUrl: params.cMapUrl,
  2695. isCompressed: params.cMapPacked
  2696. });
  2697. this.StandardFontDataFactory = new params.StandardFontDataFactory({
  2698. baseUrl: params.standardFontDataUrl
  2699. });
  2700. }
  2701. this.destroyed = false;
  2702. this.destroyCapability = null;
  2703. this._passwordCapability = null;
  2704. this._networkStream = networkStream;
  2705. this._fullReader = null;
  2706. this._lastProgress = null;
  2707. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  2708. this.setupMessageHandler();
  2709. }
  2710. get annotationStorage() {
  2711. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2712. }
  2713. get stats() {
  2714. return this.#docStats;
  2715. }
  2716. getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
  2717. let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
  2718. let annotationMap = null;
  2719. switch (intent) {
  2720. case "any":
  2721. renderingIntent = _util.RenderingIntentFlag.ANY;
  2722. break;
  2723. case "display":
  2724. break;
  2725. case "print":
  2726. renderingIntent = _util.RenderingIntentFlag.PRINT;
  2727. break;
  2728. default:
  2729. (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
  2730. }
  2731. switch (annotationMode) {
  2732. case _util.AnnotationMode.DISABLE:
  2733. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
  2734. break;
  2735. case _util.AnnotationMode.ENABLE:
  2736. break;
  2737. case _util.AnnotationMode.ENABLE_FORMS:
  2738. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
  2739. break;
  2740. case _util.AnnotationMode.ENABLE_STORAGE:
  2741. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
  2742. const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  2743. annotationMap = annotationStorage.serializable;
  2744. break;
  2745. default:
  2746. (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  2747. }
  2748. if (isOpList) {
  2749. renderingIntent += _util.RenderingIntentFlag.OPLIST;
  2750. }
  2751. return {
  2752. renderingIntent,
  2753. cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
  2754. annotationStorageMap: annotationMap
  2755. };
  2756. }
  2757. destroy() {
  2758. if (this.destroyCapability) {
  2759. return this.destroyCapability.promise;
  2760. }
  2761. this.destroyed = true;
  2762. this.destroyCapability = (0, _util.createPromiseCapability)();
  2763. if (this._passwordCapability) {
  2764. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2765. }
  2766. const waitOn = [];
  2767. for (const page of this.#pageCache.values()) {
  2768. waitOn.push(page._destroy());
  2769. }
  2770. this.#pageCache.clear();
  2771. this.#pagePromises.clear();
  2772. if (this.hasOwnProperty("annotationStorage")) {
  2773. this.annotationStorage.resetModified();
  2774. }
  2775. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2776. waitOn.push(terminated);
  2777. Promise.all(waitOn).then(() => {
  2778. this.commonObjs.clear();
  2779. this.fontLoader.clear();
  2780. this.#metadataPromise = null;
  2781. this._getFieldObjectsPromise = null;
  2782. this._hasJSActionsPromise = null;
  2783. if (this._networkStream) {
  2784. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2785. }
  2786. if (this.messageHandler) {
  2787. this.messageHandler.destroy();
  2788. this.messageHandler = null;
  2789. }
  2790. this.destroyCapability.resolve();
  2791. }, this.destroyCapability.reject);
  2792. return this.destroyCapability.promise;
  2793. }
  2794. setupMessageHandler() {
  2795. const {
  2796. messageHandler,
  2797. loadingTask
  2798. } = this;
  2799. messageHandler.on("GetReader", (data, sink) => {
  2800. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2801. this._fullReader = this._networkStream.getFullReader();
  2802. this._fullReader.onProgress = evt => {
  2803. this._lastProgress = {
  2804. loaded: evt.loaded,
  2805. total: evt.total
  2806. };
  2807. };
  2808. sink.onPull = () => {
  2809. this._fullReader.read().then(function ({
  2810. value,
  2811. done
  2812. }) {
  2813. if (done) {
  2814. sink.close();
  2815. return;
  2816. }
  2817. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
  2818. sink.enqueue(new Uint8Array(value), 1, [value]);
  2819. }).catch(reason => {
  2820. sink.error(reason);
  2821. });
  2822. };
  2823. sink.onCancel = reason => {
  2824. this._fullReader.cancel(reason);
  2825. sink.ready.catch(readyReason => {
  2826. if (this.destroyed) {
  2827. return;
  2828. }
  2829. throw readyReason;
  2830. });
  2831. };
  2832. });
  2833. messageHandler.on("ReaderHeadersReady", data => {
  2834. const headersCapability = (0, _util.createPromiseCapability)();
  2835. const fullReader = this._fullReader;
  2836. fullReader.headersReady.then(() => {
  2837. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2838. if (this._lastProgress) {
  2839. loadingTask.onProgress?.(this._lastProgress);
  2840. }
  2841. fullReader.onProgress = evt => {
  2842. loadingTask.onProgress?.({
  2843. loaded: evt.loaded,
  2844. total: evt.total
  2845. });
  2846. };
  2847. }
  2848. headersCapability.resolve({
  2849. isStreamingSupported: fullReader.isStreamingSupported,
  2850. isRangeSupported: fullReader.isRangeSupported,
  2851. contentLength: fullReader.contentLength
  2852. });
  2853. }, headersCapability.reject);
  2854. return headersCapability.promise;
  2855. });
  2856. messageHandler.on("GetRangeReader", (data, sink) => {
  2857. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2858. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2859. if (!rangeReader) {
  2860. sink.close();
  2861. return;
  2862. }
  2863. sink.onPull = () => {
  2864. rangeReader.read().then(function ({
  2865. value,
  2866. done
  2867. }) {
  2868. if (done) {
  2869. sink.close();
  2870. return;
  2871. }
  2872. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
  2873. sink.enqueue(new Uint8Array(value), 1, [value]);
  2874. }).catch(reason => {
  2875. sink.error(reason);
  2876. });
  2877. };
  2878. sink.onCancel = reason => {
  2879. rangeReader.cancel(reason);
  2880. sink.ready.catch(readyReason => {
  2881. if (this.destroyed) {
  2882. return;
  2883. }
  2884. throw readyReason;
  2885. });
  2886. };
  2887. });
  2888. messageHandler.on("GetDoc", ({
  2889. pdfInfo
  2890. }) => {
  2891. this._numPages = pdfInfo.numPages;
  2892. this._htmlForXfa = pdfInfo.htmlForXfa;
  2893. delete pdfInfo.htmlForXfa;
  2894. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2895. });
  2896. messageHandler.on("DocException", function (ex) {
  2897. let reason;
  2898. switch (ex.name) {
  2899. case "PasswordException":
  2900. reason = new _util.PasswordException(ex.message, ex.code);
  2901. break;
  2902. case "InvalidPDFException":
  2903. reason = new _util.InvalidPDFException(ex.message);
  2904. break;
  2905. case "MissingPDFException":
  2906. reason = new _util.MissingPDFException(ex.message);
  2907. break;
  2908. case "UnexpectedResponseException":
  2909. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2910. break;
  2911. case "UnknownErrorException":
  2912. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2913. break;
  2914. default:
  2915. (0, _util.unreachable)("DocException - expected a valid Error.");
  2916. }
  2917. loadingTask._capability.reject(reason);
  2918. });
  2919. messageHandler.on("PasswordRequest", exception => {
  2920. this._passwordCapability = (0, _util.createPromiseCapability)();
  2921. if (loadingTask.onPassword) {
  2922. const updatePassword = password => {
  2923. if (password instanceof Error) {
  2924. this._passwordCapability.reject(password);
  2925. } else {
  2926. this._passwordCapability.resolve({
  2927. password
  2928. });
  2929. }
  2930. };
  2931. try {
  2932. loadingTask.onPassword(updatePassword, exception.code);
  2933. } catch (ex) {
  2934. this._passwordCapability.reject(ex);
  2935. }
  2936. } else {
  2937. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2938. }
  2939. return this._passwordCapability.promise;
  2940. });
  2941. messageHandler.on("DataLoaded", data => {
  2942. loadingTask.onProgress?.({
  2943. loaded: data.length,
  2944. total: data.length
  2945. });
  2946. this.downloadInfoCapability.resolve(data);
  2947. });
  2948. messageHandler.on("StartRenderPage", data => {
  2949. if (this.destroyed) {
  2950. return;
  2951. }
  2952. const page = this.#pageCache.get(data.pageIndex);
  2953. page._startRenderPage(data.transparency, data.cacheKey);
  2954. });
  2955. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  2956. if (this.destroyed) {
  2957. return;
  2958. }
  2959. if (this.commonObjs.has(id)) {
  2960. return;
  2961. }
  2962. switch (type) {
  2963. case "Font":
  2964. const params = this._params;
  2965. if ("error" in exportedData) {
  2966. const exportedError = exportedData.error;
  2967. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2968. this.commonObjs.resolve(id, exportedError);
  2969. break;
  2970. }
  2971. let fontRegistry = null;
  2972. if (params.pdfBug && globalThis.FontInspector?.enabled) {
  2973. fontRegistry = {
  2974. registerFont(font, url) {
  2975. globalThis.FontInspector.fontAdded(font, url);
  2976. }
  2977. };
  2978. }
  2979. const font = new _font_loader.FontFaceObject(exportedData, {
  2980. isEvalSupported: params.isEvalSupported,
  2981. disableFontFace: params.disableFontFace,
  2982. ignoreErrors: params.ignoreErrors,
  2983. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2984. fontRegistry
  2985. });
  2986. this.fontLoader.bind(font).catch(reason => {
  2987. return messageHandler.sendWithPromise("FontFallback", {
  2988. id
  2989. });
  2990. }).finally(() => {
  2991. if (!params.fontExtraProperties && font.data) {
  2992. font.data = null;
  2993. }
  2994. this.commonObjs.resolve(id, font);
  2995. });
  2996. break;
  2997. case "FontPath":
  2998. case "Image":
  2999. this.commonObjs.resolve(id, exportedData);
  3000. break;
  3001. default:
  3002. throw new Error(`Got unknown common object type ${type}`);
  3003. }
  3004. });
  3005. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  3006. if (this.destroyed) {
  3007. return;
  3008. }
  3009. const pageProxy = this.#pageCache.get(pageIndex);
  3010. if (pageProxy.objs.has(id)) {
  3011. return;
  3012. }
  3013. switch (type) {
  3014. case "Image":
  3015. pageProxy.objs.resolve(id, imageData);
  3016. const MAX_IMAGE_SIZE_TO_STORE = 8000000;
  3017. if (imageData) {
  3018. let length;
  3019. if (imageData.bitmap) {
  3020. const {
  3021. bitmap,
  3022. width,
  3023. height
  3024. } = imageData;
  3025. length = width * height * 4;
  3026. pageProxy._bitmaps.add(bitmap);
  3027. } else {
  3028. length = imageData.data?.length || 0;
  3029. }
  3030. if (length > MAX_IMAGE_SIZE_TO_STORE) {
  3031. pageProxy.cleanupAfterRender = true;
  3032. }
  3033. }
  3034. break;
  3035. case "Pattern":
  3036. pageProxy.objs.resolve(id, imageData);
  3037. break;
  3038. default:
  3039. throw new Error(`Got unknown object type ${type}`);
  3040. }
  3041. });
  3042. messageHandler.on("DocProgress", data => {
  3043. if (this.destroyed) {
  3044. return;
  3045. }
  3046. loadingTask.onProgress?.({
  3047. loaded: data.loaded,
  3048. total: data.total
  3049. });
  3050. });
  3051. messageHandler.on("DocStats", data => {
  3052. if (this.destroyed) {
  3053. return;
  3054. }
  3055. this.#docStats = Object.freeze({
  3056. streamTypes: Object.freeze(data.streamTypes),
  3057. fontTypes: Object.freeze(data.fontTypes)
  3058. });
  3059. });
  3060. messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
  3061. messageHandler.on("FetchBuiltInCMap", data => {
  3062. if (this.destroyed) {
  3063. return Promise.reject(new Error("Worker was destroyed."));
  3064. }
  3065. if (!this.CMapReaderFactory) {
  3066. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  3067. }
  3068. return this.CMapReaderFactory.fetch(data);
  3069. });
  3070. messageHandler.on("FetchStandardFontData", data => {
  3071. if (this.destroyed) {
  3072. return Promise.reject(new Error("Worker was destroyed."));
  3073. }
  3074. if (!this.StandardFontDataFactory) {
  3075. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  3076. }
  3077. return this.StandardFontDataFactory.fetch(data);
  3078. });
  3079. }
  3080. _onUnsupportedFeature({
  3081. featureId
  3082. }) {
  3083. if (this.destroyed) {
  3084. return;
  3085. }
  3086. this.loadingTask.onUnsupportedFeature?.(featureId);
  3087. }
  3088. getData() {
  3089. return this.messageHandler.sendWithPromise("GetData", null);
  3090. }
  3091. getPage(pageNumber) {
  3092. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  3093. return Promise.reject(new Error("Invalid page request."));
  3094. }
  3095. const pageIndex = pageNumber - 1,
  3096. cachedPromise = this.#pagePromises.get(pageIndex);
  3097. if (cachedPromise) {
  3098. return cachedPromise;
  3099. }
  3100. const promise = this.messageHandler.sendWithPromise("GetPage", {
  3101. pageIndex
  3102. }).then(pageInfo => {
  3103. if (this.destroyed) {
  3104. throw new Error("Transport destroyed");
  3105. }
  3106. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
  3107. this.#pageCache.set(pageIndex, page);
  3108. return page;
  3109. });
  3110. this.#pagePromises.set(pageIndex, promise);
  3111. return promise;
  3112. }
  3113. getPageIndex(ref) {
  3114. if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
  3115. return Promise.reject(new Error("Invalid pageIndex request."));
  3116. }
  3117. return this.messageHandler.sendWithPromise("GetPageIndex", {
  3118. num: ref.num,
  3119. gen: ref.gen
  3120. });
  3121. }
  3122. getAnnotations(pageIndex, intent) {
  3123. return this.messageHandler.sendWithPromise("GetAnnotations", {
  3124. pageIndex,
  3125. intent
  3126. });
  3127. }
  3128. saveDocument() {
  3129. return this.messageHandler.sendWithPromise("SaveDocument", {
  3130. isPureXfa: !!this._htmlForXfa,
  3131. numPages: this._numPages,
  3132. annotationStorage: this.annotationStorage.serializable,
  3133. filename: this._fullReader?.filename ?? null
  3134. }).finally(() => {
  3135. this.annotationStorage.resetModified();
  3136. });
  3137. }
  3138. getFieldObjects() {
  3139. return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
  3140. }
  3141. hasJSActions() {
  3142. return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
  3143. }
  3144. getCalculationOrderIds() {
  3145. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  3146. }
  3147. getDestinations() {
  3148. return this.messageHandler.sendWithPromise("GetDestinations", null);
  3149. }
  3150. getDestination(id) {
  3151. if (typeof id !== "string") {
  3152. return Promise.reject(new Error("Invalid destination request."));
  3153. }
  3154. return this.messageHandler.sendWithPromise("GetDestination", {
  3155. id
  3156. });
  3157. }
  3158. getPageLabels() {
  3159. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  3160. }
  3161. getPageLayout() {
  3162. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  3163. }
  3164. getPageMode() {
  3165. return this.messageHandler.sendWithPromise("GetPageMode", null);
  3166. }
  3167. getViewerPreferences() {
  3168. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  3169. }
  3170. getOpenAction() {
  3171. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  3172. }
  3173. getAttachments() {
  3174. return this.messageHandler.sendWithPromise("GetAttachments", null);
  3175. }
  3176. getJavaScript() {
  3177. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  3178. }
  3179. getDocJSActions() {
  3180. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  3181. }
  3182. getPageJSActions(pageIndex) {
  3183. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  3184. pageIndex
  3185. });
  3186. }
  3187. getStructTree(pageIndex) {
  3188. return this.messageHandler.sendWithPromise("GetStructTree", {
  3189. pageIndex
  3190. });
  3191. }
  3192. getOutline() {
  3193. return this.messageHandler.sendWithPromise("GetOutline", null);
  3194. }
  3195. getOptionalContentConfig() {
  3196. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  3197. return new _optional_content_config.OptionalContentConfig(results);
  3198. });
  3199. }
  3200. getPermissions() {
  3201. return this.messageHandler.sendWithPromise("GetPermissions", null);
  3202. }
  3203. getMetadata() {
  3204. return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
  3205. return {
  3206. info: results[0],
  3207. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  3208. contentDispositionFilename: this._fullReader?.filename ?? null,
  3209. contentLength: this._fullReader?.contentLength ?? null
  3210. };
  3211. });
  3212. }
  3213. getMarkInfo() {
  3214. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  3215. }
  3216. async startCleanup(keepLoadedFonts = false) {
  3217. await this.messageHandler.sendWithPromise("Cleanup", null);
  3218. if (this.destroyed) {
  3219. return;
  3220. }
  3221. for (const page of this.#pageCache.values()) {
  3222. const cleanupSuccessful = page.cleanup();
  3223. if (!cleanupSuccessful) {
  3224. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  3225. }
  3226. }
  3227. this.commonObjs.clear();
  3228. if (!keepLoadedFonts) {
  3229. this.fontLoader.clear();
  3230. }
  3231. this.#metadataPromise = null;
  3232. this._getFieldObjectsPromise = null;
  3233. this._hasJSActionsPromise = null;
  3234. }
  3235. get loadingParams() {
  3236. const params = this._params;
  3237. return (0, _util.shadow)(this, "loadingParams", {
  3238. disableAutoFetch: params.disableAutoFetch,
  3239. enableXfa: params.enableXfa
  3240. });
  3241. }
  3242. }
  3243. class PDFObjects {
  3244. #objs = Object.create(null);
  3245. #ensureObj(objId) {
  3246. const obj = this.#objs[objId];
  3247. if (obj) {
  3248. return obj;
  3249. }
  3250. return this.#objs[objId] = {
  3251. capability: (0, _util.createPromiseCapability)(),
  3252. data: null
  3253. };
  3254. }
  3255. get(objId, callback = null) {
  3256. if (callback) {
  3257. const obj = this.#ensureObj(objId);
  3258. obj.capability.promise.then(() => callback(obj.data));
  3259. return null;
  3260. }
  3261. const obj = this.#objs[objId];
  3262. if (!obj?.capability.settled) {
  3263. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  3264. }
  3265. return obj.data;
  3266. }
  3267. has(objId) {
  3268. const obj = this.#objs[objId];
  3269. return obj?.capability.settled || false;
  3270. }
  3271. resolve(objId, data = null) {
  3272. const obj = this.#ensureObj(objId);
  3273. obj.data = data;
  3274. obj.capability.resolve();
  3275. }
  3276. clear() {
  3277. this.#objs = Object.create(null);
  3278. }
  3279. }
  3280. class RenderTask {
  3281. #internalRenderTask = null;
  3282. constructor(internalRenderTask) {
  3283. this.#internalRenderTask = internalRenderTask;
  3284. this.onContinue = null;
  3285. }
  3286. get promise() {
  3287. return this.#internalRenderTask.capability.promise;
  3288. }
  3289. cancel() {
  3290. this.#internalRenderTask.cancel();
  3291. }
  3292. get separateAnnots() {
  3293. const {
  3294. separateAnnots
  3295. } = this.#internalRenderTask.operatorList;
  3296. if (!separateAnnots) {
  3297. return false;
  3298. }
  3299. const {
  3300. annotationCanvasMap
  3301. } = this.#internalRenderTask;
  3302. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  3303. }
  3304. }
  3305. exports.RenderTask = RenderTask;
  3306. class InternalRenderTask {
  3307. static #canvasInUse = new WeakSet();
  3308. constructor({
  3309. callback,
  3310. params,
  3311. objs,
  3312. commonObjs,
  3313. annotationCanvasMap,
  3314. operatorList,
  3315. pageIndex,
  3316. canvasFactory,
  3317. useRequestAnimationFrame = false,
  3318. pdfBug = false,
  3319. pageColors = null
  3320. }) {
  3321. this.callback = callback;
  3322. this.params = params;
  3323. this.objs = objs;
  3324. this.commonObjs = commonObjs;
  3325. this.annotationCanvasMap = annotationCanvasMap;
  3326. this.operatorListIdx = null;
  3327. this.operatorList = operatorList;
  3328. this._pageIndex = pageIndex;
  3329. this.canvasFactory = canvasFactory;
  3330. this._pdfBug = pdfBug;
  3331. this.pageColors = pageColors;
  3332. this.running = false;
  3333. this.graphicsReadyCallback = null;
  3334. this.graphicsReady = false;
  3335. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  3336. this.cancelled = false;
  3337. this.capability = (0, _util.createPromiseCapability)();
  3338. this.task = new RenderTask(this);
  3339. this._cancelBound = this.cancel.bind(this);
  3340. this._continueBound = this._continue.bind(this);
  3341. this._scheduleNextBound = this._scheduleNext.bind(this);
  3342. this._nextBound = this._next.bind(this);
  3343. this._canvas = params.canvasContext.canvas;
  3344. }
  3345. get completed() {
  3346. return this.capability.promise.catch(function () {});
  3347. }
  3348. initializeGraphics({
  3349. transparency = false,
  3350. optionalContentConfig
  3351. }) {
  3352. if (this.cancelled) {
  3353. return;
  3354. }
  3355. if (this._canvas) {
  3356. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  3357. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  3358. }
  3359. InternalRenderTask.#canvasInUse.add(this._canvas);
  3360. }
  3361. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  3362. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  3363. this.stepper.init(this.operatorList);
  3364. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  3365. }
  3366. const {
  3367. canvasContext,
  3368. viewport,
  3369. transform,
  3370. imageLayer,
  3371. background
  3372. } = this.params;
  3373. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig, this.annotationCanvasMap, this.pageColors);
  3374. this.gfx.beginDrawing({
  3375. transform,
  3376. viewport,
  3377. transparency,
  3378. background
  3379. });
  3380. this.operatorListIdx = 0;
  3381. this.graphicsReady = true;
  3382. if (this.graphicsReadyCallback) {
  3383. this.graphicsReadyCallback();
  3384. }
  3385. }
  3386. cancel(error = null) {
  3387. this.running = false;
  3388. this.cancelled = true;
  3389. if (this.gfx) {
  3390. this.gfx.endDrawing();
  3391. }
  3392. if (this._canvas) {
  3393. InternalRenderTask.#canvasInUse.delete(this._canvas);
  3394. }
  3395. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
  3396. }
  3397. operatorListChanged() {
  3398. if (!this.graphicsReady) {
  3399. if (!this.graphicsReadyCallback) {
  3400. this.graphicsReadyCallback = this._continueBound;
  3401. }
  3402. return;
  3403. }
  3404. if (this.stepper) {
  3405. this.stepper.updateOperatorList(this.operatorList);
  3406. }
  3407. if (this.running) {
  3408. return;
  3409. }
  3410. this._continue();
  3411. }
  3412. _continue() {
  3413. this.running = true;
  3414. if (this.cancelled) {
  3415. return;
  3416. }
  3417. if (this.task.onContinue) {
  3418. this.task.onContinue(this._scheduleNextBound);
  3419. } else {
  3420. this._scheduleNext();
  3421. }
  3422. }
  3423. _scheduleNext() {
  3424. if (this._useRequestAnimationFrame) {
  3425. window.requestAnimationFrame(() => {
  3426. this._nextBound().catch(this._cancelBound);
  3427. });
  3428. } else {
  3429. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  3430. }
  3431. }
  3432. async _next() {
  3433. if (this.cancelled) {
  3434. return;
  3435. }
  3436. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  3437. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  3438. this.running = false;
  3439. if (this.operatorList.lastChunk) {
  3440. this.gfx.endDrawing();
  3441. if (this._canvas) {
  3442. InternalRenderTask.#canvasInUse.delete(this._canvas);
  3443. }
  3444. this.callback();
  3445. }
  3446. }
  3447. }
  3448. }
  3449. const version = '2.15.349';
  3450. exports.version = version;
  3451. const build = 'b8aa9c622';
  3452. exports.build = build;
  3453. /***/ }),
  3454. /* 7 */
  3455. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3456. Object.defineProperty(exports, "__esModule", ({
  3457. value: true
  3458. }));
  3459. exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
  3460. var _util = __w_pdfjs_require__(1);
  3461. var _editor = __w_pdfjs_require__(8);
  3462. var _murmurhash = __w_pdfjs_require__(10);
  3463. class AnnotationStorage {
  3464. constructor() {
  3465. this._storage = new Map();
  3466. this._modified = false;
  3467. this.onSetModified = null;
  3468. this.onResetModified = null;
  3469. }
  3470. getValue(key, defaultValue) {
  3471. const value = this._storage.get(key);
  3472. if (value === undefined) {
  3473. return defaultValue;
  3474. }
  3475. return Object.assign(defaultValue, value);
  3476. }
  3477. getRawValue(key) {
  3478. return this._storage.get(key);
  3479. }
  3480. removeKey(key) {
  3481. this._storage.delete(key);
  3482. if (this._storage.size === 0) {
  3483. this.resetModified();
  3484. }
  3485. }
  3486. setValue(key, value) {
  3487. const obj = this._storage.get(key);
  3488. let modified = false;
  3489. if (obj !== undefined) {
  3490. for (const [entry, val] of Object.entries(value)) {
  3491. if (obj[entry] !== val) {
  3492. modified = true;
  3493. obj[entry] = val;
  3494. }
  3495. }
  3496. } else {
  3497. modified = true;
  3498. this._storage.set(key, value);
  3499. }
  3500. if (modified) {
  3501. this.#setModified();
  3502. }
  3503. }
  3504. has(key) {
  3505. return this._storage.has(key);
  3506. }
  3507. getAll() {
  3508. return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
  3509. }
  3510. get size() {
  3511. return this._storage.size;
  3512. }
  3513. #setModified() {
  3514. if (!this._modified) {
  3515. this._modified = true;
  3516. if (typeof this.onSetModified === "function") {
  3517. this.onSetModified();
  3518. }
  3519. }
  3520. }
  3521. resetModified() {
  3522. if (this._modified) {
  3523. this._modified = false;
  3524. if (typeof this.onResetModified === "function") {
  3525. this.onResetModified();
  3526. }
  3527. }
  3528. }
  3529. get print() {
  3530. return new PrintAnnotationStorage(this);
  3531. }
  3532. get serializable() {
  3533. if (this._storage.size === 0) {
  3534. return null;
  3535. }
  3536. const clone = new Map();
  3537. for (const [key, val] of this._storage) {
  3538. const serialized = val instanceof _editor.AnnotationEditor ? val.serialize() : val;
  3539. if (serialized) {
  3540. clone.set(key, serialized);
  3541. }
  3542. }
  3543. return clone;
  3544. }
  3545. static getHash(map) {
  3546. if (!map) {
  3547. return "";
  3548. }
  3549. const hash = new _murmurhash.MurmurHash3_64();
  3550. for (const [key, val] of map) {
  3551. hash.update(`${key}:${JSON.stringify(val)}`);
  3552. }
  3553. return hash.hexdigest();
  3554. }
  3555. }
  3556. exports.AnnotationStorage = AnnotationStorage;
  3557. class PrintAnnotationStorage extends AnnotationStorage {
  3558. #serializable = null;
  3559. constructor(parent) {
  3560. super();
  3561. this.#serializable = structuredClone(parent.serializable);
  3562. }
  3563. get print() {
  3564. (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
  3565. }
  3566. get serializable() {
  3567. return this.#serializable;
  3568. }
  3569. }
  3570. exports.PrintAnnotationStorage = PrintAnnotationStorage;
  3571. /***/ }),
  3572. /* 8 */
  3573. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3574. Object.defineProperty(exports, "__esModule", ({
  3575. value: true
  3576. }));
  3577. exports.AnnotationEditor = void 0;
  3578. var _tools = __w_pdfjs_require__(9);
  3579. var _util = __w_pdfjs_require__(1);
  3580. class AnnotationEditor {
  3581. #boundFocusin = this.focusin.bind(this);
  3582. #boundFocusout = this.focusout.bind(this);
  3583. #hasBeenSelected = false;
  3584. #isEditing = false;
  3585. #isInEditMode = false;
  3586. #zIndex = AnnotationEditor._zIndex++;
  3587. static _colorManager = new _tools.ColorManager();
  3588. static _zIndex = 1;
  3589. constructor(parameters) {
  3590. if (this.constructor === AnnotationEditor) {
  3591. (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
  3592. }
  3593. this.parent = parameters.parent;
  3594. this.id = parameters.id;
  3595. this.width = this.height = null;
  3596. this.pageIndex = parameters.parent.pageIndex;
  3597. this.name = parameters.name;
  3598. this.div = null;
  3599. const [width, height] = this.parent.viewportBaseDimensions;
  3600. this.x = parameters.x / width;
  3601. this.y = parameters.y / height;
  3602. this.rotation = this.parent.viewport.rotation;
  3603. this.isAttachedToDOM = false;
  3604. }
  3605. static get _defaultLineColor() {
  3606. return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  3607. }
  3608. setInBackground() {
  3609. this.div.style.zIndex = 0;
  3610. }
  3611. setInForeground() {
  3612. this.div.style.zIndex = this.#zIndex;
  3613. }
  3614. focusin(event) {
  3615. if (!this.#hasBeenSelected) {
  3616. this.parent.setSelected(this);
  3617. } else {
  3618. this.#hasBeenSelected = false;
  3619. }
  3620. }
  3621. focusout(event) {
  3622. if (!this.isAttachedToDOM) {
  3623. return;
  3624. }
  3625. const target = event.relatedTarget;
  3626. if (target?.closest(`#${this.id}`)) {
  3627. return;
  3628. }
  3629. event.preventDefault();
  3630. if (!this.parent.isMultipleSelection) {
  3631. this.commitOrRemove();
  3632. }
  3633. }
  3634. commitOrRemove() {
  3635. if (this.isEmpty()) {
  3636. this.remove();
  3637. } else {
  3638. this.commit();
  3639. }
  3640. }
  3641. commit() {
  3642. this.parent.addToAnnotationStorage(this);
  3643. }
  3644. dragstart(event) {
  3645. const rect = this.parent.div.getBoundingClientRect();
  3646. this.startX = event.clientX - rect.x;
  3647. this.startY = event.clientY - rect.y;
  3648. event.dataTransfer.setData("text/plain", this.id);
  3649. event.dataTransfer.effectAllowed = "move";
  3650. }
  3651. setAt(x, y, tx, ty) {
  3652. const [width, height] = this.parent.viewportBaseDimensions;
  3653. [tx, ty] = this.screenToPageTranslation(tx, ty);
  3654. this.x = (x + tx) / width;
  3655. this.y = (y + ty) / height;
  3656. this.div.style.left = `${100 * this.x}%`;
  3657. this.div.style.top = `${100 * this.y}%`;
  3658. }
  3659. translate(x, y) {
  3660. const [width, height] = this.parent.viewportBaseDimensions;
  3661. [x, y] = this.screenToPageTranslation(x, y);
  3662. this.x += x / width;
  3663. this.y += y / height;
  3664. this.div.style.left = `${100 * this.x}%`;
  3665. this.div.style.top = `${100 * this.y}%`;
  3666. }
  3667. screenToPageTranslation(x, y) {
  3668. const {
  3669. rotation
  3670. } = this.parent.viewport;
  3671. switch (rotation) {
  3672. case 90:
  3673. return [y, -x];
  3674. case 180:
  3675. return [-x, -y];
  3676. case 270:
  3677. return [-y, x];
  3678. default:
  3679. return [x, y];
  3680. }
  3681. }
  3682. setDims(width, height) {
  3683. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3684. this.div.style.width = `${100 * width / parentWidth}%`;
  3685. this.div.style.height = `${100 * height / parentHeight}%`;
  3686. }
  3687. getInitialTranslation() {
  3688. return [0, 0];
  3689. }
  3690. render() {
  3691. this.div = document.createElement("div");
  3692. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  3693. this.div.className = this.name;
  3694. this.div.setAttribute("id", this.id);
  3695. this.div.setAttribute("tabIndex", 0);
  3696. this.setInForeground();
  3697. this.div.addEventListener("focusin", this.#boundFocusin);
  3698. this.div.addEventListener("focusout", this.#boundFocusout);
  3699. const [tx, ty] = this.getInitialTranslation();
  3700. this.translate(tx, ty);
  3701. (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
  3702. return this.div;
  3703. }
  3704. pointerdown(event) {
  3705. const isMac = _tools.KeyboardManager.platform.isMac;
  3706. if (event.button !== 0 || event.ctrlKey && isMac) {
  3707. event.preventDefault();
  3708. return;
  3709. }
  3710. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  3711. this.parent.toggleSelected(this);
  3712. } else {
  3713. this.parent.setSelected(this);
  3714. }
  3715. this.#hasBeenSelected = true;
  3716. }
  3717. getRect(tx, ty) {
  3718. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3719. const [pageWidth, pageHeight] = this.parent.pageDimensions;
  3720. const shiftX = pageWidth * tx / parentWidth;
  3721. const shiftY = pageHeight * ty / parentHeight;
  3722. const x = this.x * pageWidth;
  3723. const y = this.y * pageHeight;
  3724. const width = this.width * pageWidth;
  3725. const height = this.height * pageHeight;
  3726. switch (this.rotation) {
  3727. case 0:
  3728. return [x + shiftX, pageHeight - y - shiftY - height, x + shiftX + width, pageHeight - y - shiftY];
  3729. case 90:
  3730. return [x + shiftY, pageHeight - y + shiftX, x + shiftY + height, pageHeight - y + shiftX + width];
  3731. case 180:
  3732. return [x - shiftX - width, pageHeight - y + shiftY, x - shiftX, pageHeight - y + shiftY + height];
  3733. case 270:
  3734. return [x - shiftY - height, pageHeight - y - shiftX - width, x - shiftY, pageHeight - y - shiftX];
  3735. default:
  3736. throw new Error("Invalid rotation");
  3737. }
  3738. }
  3739. getRectInCurrentCoords(rect, pageHeight) {
  3740. const [x1, y1, x2, y2] = rect;
  3741. const width = x2 - x1;
  3742. const height = y2 - y1;
  3743. switch (this.rotation) {
  3744. case 0:
  3745. return [x1, pageHeight - y2, width, height];
  3746. case 90:
  3747. return [x1, pageHeight - y1, height, width];
  3748. case 180:
  3749. return [x2, pageHeight - y1, width, height];
  3750. case 270:
  3751. return [x2, pageHeight - y2, height, width];
  3752. default:
  3753. throw new Error("Invalid rotation");
  3754. }
  3755. }
  3756. onceAdded() {}
  3757. isEmpty() {
  3758. return false;
  3759. }
  3760. enableEditMode() {
  3761. this.#isInEditMode = true;
  3762. }
  3763. disableEditMode() {
  3764. this.#isInEditMode = false;
  3765. }
  3766. isInEditMode() {
  3767. return this.#isInEditMode;
  3768. }
  3769. shouldGetKeyboardEvents() {
  3770. return false;
  3771. }
  3772. needsToBeRebuilt() {
  3773. return this.div && !this.isAttachedToDOM;
  3774. }
  3775. rebuild() {
  3776. this.div?.addEventListener("focusin", this.#boundFocusin);
  3777. }
  3778. serialize() {
  3779. (0, _util.unreachable)("An editor must be serializable");
  3780. }
  3781. static deserialize(data, parent) {
  3782. const editor = new this.prototype.constructor({
  3783. parent,
  3784. id: parent.getNextId()
  3785. });
  3786. editor.rotation = data.rotation;
  3787. const [pageWidth, pageHeight] = parent.pageDimensions;
  3788. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  3789. editor.x = x / pageWidth;
  3790. editor.y = y / pageHeight;
  3791. editor.width = width / pageWidth;
  3792. editor.height = height / pageHeight;
  3793. return editor;
  3794. }
  3795. remove() {
  3796. this.div.removeEventListener("focusin", this.#boundFocusin);
  3797. this.div.removeEventListener("focusout", this.#boundFocusout);
  3798. if (!this.isEmpty()) {
  3799. this.commit();
  3800. }
  3801. this.parent.remove(this);
  3802. }
  3803. select() {
  3804. this.div?.classList.add("selectedEditor");
  3805. }
  3806. unselect() {
  3807. this.div?.classList.remove("selectedEditor");
  3808. }
  3809. updateParams(type, value) {}
  3810. disableEditing() {}
  3811. enableEditing() {}
  3812. getIdForTextLayer() {
  3813. return this.id;
  3814. }
  3815. get propertiesToUpdate() {
  3816. return {};
  3817. }
  3818. get contentDiv() {
  3819. return this.div;
  3820. }
  3821. get isEditing() {
  3822. return this.#isEditing;
  3823. }
  3824. set isEditing(value) {
  3825. this.#isEditing = value;
  3826. if (value) {
  3827. this.parent.setSelected(this);
  3828. this.parent.setActiveEditor(this);
  3829. } else {
  3830. this.parent.setActiveEditor(null);
  3831. }
  3832. }
  3833. }
  3834. exports.AnnotationEditor = AnnotationEditor;
  3835. /***/ }),
  3836. /* 9 */
  3837. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3838. Object.defineProperty(exports, "__esModule", ({
  3839. value: true
  3840. }));
  3841. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  3842. exports.bindEvents = bindEvents;
  3843. exports.opacityToHex = opacityToHex;
  3844. var _util = __w_pdfjs_require__(1);
  3845. var _display_utils = __w_pdfjs_require__(4);
  3846. function bindEvents(obj, element, names) {
  3847. for (const name of names) {
  3848. element.addEventListener(name, obj[name].bind(obj));
  3849. }
  3850. }
  3851. function opacityToHex(opacity) {
  3852. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  3853. }
  3854. class IdManager {
  3855. #id = 0;
  3856. getId() {
  3857. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  3858. }
  3859. }
  3860. class CommandManager {
  3861. #commands = [];
  3862. #locked = false;
  3863. #maxSize;
  3864. #position = -1;
  3865. constructor(maxSize = 128) {
  3866. this.#maxSize = maxSize;
  3867. }
  3868. add({
  3869. cmd,
  3870. undo,
  3871. mustExec,
  3872. type = NaN,
  3873. overwriteIfSameType = false,
  3874. keepUndo = false
  3875. }) {
  3876. if (mustExec) {
  3877. cmd();
  3878. }
  3879. if (this.#locked) {
  3880. return;
  3881. }
  3882. const save = {
  3883. cmd,
  3884. undo,
  3885. type
  3886. };
  3887. if (this.#position === -1) {
  3888. if (this.#commands.length > 0) {
  3889. this.#commands.length = 0;
  3890. }
  3891. this.#position = 0;
  3892. this.#commands.push(save);
  3893. return;
  3894. }
  3895. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  3896. if (keepUndo) {
  3897. save.undo = this.#commands[this.#position].undo;
  3898. }
  3899. this.#commands[this.#position] = save;
  3900. return;
  3901. }
  3902. const next = this.#position + 1;
  3903. if (next === this.#maxSize) {
  3904. this.#commands.splice(0, 1);
  3905. } else {
  3906. this.#position = next;
  3907. if (next < this.#commands.length) {
  3908. this.#commands.splice(next);
  3909. }
  3910. }
  3911. this.#commands.push(save);
  3912. }
  3913. undo() {
  3914. if (this.#position === -1) {
  3915. return;
  3916. }
  3917. this.#locked = true;
  3918. this.#commands[this.#position].undo();
  3919. this.#locked = false;
  3920. this.#position -= 1;
  3921. }
  3922. redo() {
  3923. if (this.#position < this.#commands.length - 1) {
  3924. this.#position += 1;
  3925. this.#locked = true;
  3926. this.#commands[this.#position].cmd();
  3927. this.#locked = false;
  3928. }
  3929. }
  3930. hasSomethingToUndo() {
  3931. return this.#position !== -1;
  3932. }
  3933. hasSomethingToRedo() {
  3934. return this.#position < this.#commands.length - 1;
  3935. }
  3936. destroy() {
  3937. this.#commands = null;
  3938. }
  3939. }
  3940. exports.CommandManager = CommandManager;
  3941. class KeyboardManager {
  3942. constructor(callbacks) {
  3943. this.buffer = [];
  3944. this.callbacks = new Map();
  3945. this.allKeys = new Set();
  3946. const isMac = KeyboardManager.platform.isMac;
  3947. for (const [keys, callback] of callbacks) {
  3948. for (const key of keys) {
  3949. const isMacKey = key.startsWith("mac+");
  3950. if (isMac && isMacKey) {
  3951. this.callbacks.set(key.slice(4), callback);
  3952. this.allKeys.add(key.split("+").at(-1));
  3953. } else if (!isMac && !isMacKey) {
  3954. this.callbacks.set(key, callback);
  3955. this.allKeys.add(key.split("+").at(-1));
  3956. }
  3957. }
  3958. }
  3959. }
  3960. static get platform() {
  3961. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  3962. return (0, _util.shadow)(this, "platform", {
  3963. isWin: platform.includes("Win"),
  3964. isMac: platform.includes("Mac")
  3965. });
  3966. }
  3967. #serialize(event) {
  3968. if (event.altKey) {
  3969. this.buffer.push("alt");
  3970. }
  3971. if (event.ctrlKey) {
  3972. this.buffer.push("ctrl");
  3973. }
  3974. if (event.metaKey) {
  3975. this.buffer.push("meta");
  3976. }
  3977. if (event.shiftKey) {
  3978. this.buffer.push("shift");
  3979. }
  3980. this.buffer.push(event.key);
  3981. const str = this.buffer.join("+");
  3982. this.buffer.length = 0;
  3983. return str;
  3984. }
  3985. exec(self, event) {
  3986. if (!this.allKeys.has(event.key)) {
  3987. return;
  3988. }
  3989. const callback = this.callbacks.get(this.#serialize(event));
  3990. if (!callback) {
  3991. return;
  3992. }
  3993. callback.bind(self)();
  3994. event.stopPropagation();
  3995. event.preventDefault();
  3996. }
  3997. }
  3998. exports.KeyboardManager = KeyboardManager;
  3999. class ClipboardManager {
  4000. #elements = null;
  4001. copy(element) {
  4002. if (!element) {
  4003. return;
  4004. }
  4005. if (Array.isArray(element)) {
  4006. this.#elements = element.map(el => el.serialize());
  4007. } else {
  4008. this.#elements = [element.serialize()];
  4009. }
  4010. this.#elements = this.#elements.filter(el => !!el);
  4011. if (this.#elements.length === 0) {
  4012. this.#elements = null;
  4013. }
  4014. }
  4015. paste() {
  4016. return this.#elements;
  4017. }
  4018. isEmpty() {
  4019. return this.#elements === null;
  4020. }
  4021. destroy() {
  4022. this.#elements = null;
  4023. }
  4024. }
  4025. class ColorManager {
  4026. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  4027. get _colors() {
  4028. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  4029. (0, _display_utils.getColorValues)(colors);
  4030. return (0, _util.shadow)(this, "_colors", colors);
  4031. }
  4032. convert(color) {
  4033. const rgb = (0, _display_utils.getRGB)(color);
  4034. if (!window.matchMedia("(forced-colors: active)").matches) {
  4035. return rgb;
  4036. }
  4037. for (const [name, RGB] of this._colors) {
  4038. if (RGB.every((x, i) => x === rgb[i])) {
  4039. return ColorManager._colorsMapping.get(name);
  4040. }
  4041. }
  4042. return rgb;
  4043. }
  4044. getHexCode(name) {
  4045. const rgb = this._colors.get(name);
  4046. if (!rgb) {
  4047. return name;
  4048. }
  4049. return _util.Util.makeHexColor(...rgb);
  4050. }
  4051. }
  4052. exports.ColorManager = ColorManager;
  4053. class AnnotationEditorUIManager {
  4054. #activeEditor = null;
  4055. #allEditors = new Map();
  4056. #allLayers = new Map();
  4057. #clipboardManager = new ClipboardManager();
  4058. #commandManager = new CommandManager();
  4059. #currentPageIndex = 0;
  4060. #editorTypes = null;
  4061. #eventBus = null;
  4062. #idManager = new IdManager();
  4063. #isEnabled = false;
  4064. #mode = _util.AnnotationEditorType.NONE;
  4065. #selectedEditors = new Set();
  4066. #boundKeydown = this.keydown.bind(this);
  4067. #boundOnEditingAction = this.onEditingAction.bind(this);
  4068. #boundOnPageChanging = this.onPageChanging.bind(this);
  4069. #boundOnTextLayerRendered = this.onTextLayerRendered.bind(this);
  4070. #previousStates = {
  4071. isEditing: false,
  4072. isEmpty: true,
  4073. hasEmptyClipboard: true,
  4074. hasSomethingToUndo: false,
  4075. hasSomethingToRedo: false,
  4076. hasSelectedEditor: false
  4077. };
  4078. #container = null;
  4079. static _keyboardManager = new KeyboardManager([[["ctrl+a", "mac+meta+a"], AnnotationEditorUIManager.prototype.selectAll], [["ctrl+c", "mac+meta+c"], AnnotationEditorUIManager.prototype.copy], [["ctrl+v", "mac+meta+v"], AnnotationEditorUIManager.prototype.paste], [["ctrl+x", "mac+meta+x"], AnnotationEditorUIManager.prototype.cut], [["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]]);
  4080. constructor(container, eventBus) {
  4081. this.#container = container;
  4082. this.#eventBus = eventBus;
  4083. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  4084. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  4085. this.#eventBus._on("textlayerrendered", this.#boundOnTextLayerRendered);
  4086. }
  4087. destroy() {
  4088. this.#removeKeyboardManager();
  4089. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  4090. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  4091. this.#eventBus._off("textlayerrendered", this.#boundOnTextLayerRendered);
  4092. for (const layer of this.#allLayers.values()) {
  4093. layer.destroy();
  4094. }
  4095. this.#allLayers.clear();
  4096. this.#allEditors.clear();
  4097. this.#activeEditor = null;
  4098. this.#selectedEditors.clear();
  4099. this.#clipboardManager.destroy();
  4100. this.#commandManager.destroy();
  4101. }
  4102. onPageChanging({
  4103. pageNumber
  4104. }) {
  4105. this.#currentPageIndex = pageNumber - 1;
  4106. }
  4107. onTextLayerRendered({
  4108. pageNumber
  4109. }) {
  4110. const pageIndex = pageNumber - 1;
  4111. const layer = this.#allLayers.get(pageIndex);
  4112. layer?.onTextLayerRendered();
  4113. }
  4114. focusMainContainer() {
  4115. this.#container.focus();
  4116. }
  4117. #addKeyboardManager() {
  4118. this.#container.addEventListener("keydown", this.#boundKeydown);
  4119. }
  4120. #removeKeyboardManager() {
  4121. this.#container.removeEventListener("keydown", this.#boundKeydown);
  4122. }
  4123. keydown(event) {
  4124. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  4125. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  4126. }
  4127. }
  4128. onEditingAction(details) {
  4129. if (["undo", "redo", "cut", "copy", "paste", "delete", "selectAll"].includes(details.name)) {
  4130. this[details.name]();
  4131. }
  4132. }
  4133. #dispatchUpdateStates(details) {
  4134. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  4135. if (hasChanged) {
  4136. this.#eventBus.dispatch("annotationeditorstateschanged", {
  4137. source: this,
  4138. details: Object.assign(this.#previousStates, details)
  4139. });
  4140. }
  4141. }
  4142. #dispatchUpdateUI(details) {
  4143. this.#eventBus.dispatch("annotationeditorparamschanged", {
  4144. source: this,
  4145. details
  4146. });
  4147. }
  4148. setEditingState(isEditing) {
  4149. if (isEditing) {
  4150. this.#addKeyboardManager();
  4151. this.#dispatchUpdateStates({
  4152. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  4153. isEmpty: this.#isEmpty(),
  4154. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  4155. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  4156. hasSelectedEditor: false,
  4157. hasEmptyClipboard: this.#clipboardManager.isEmpty()
  4158. });
  4159. } else {
  4160. this.#removeKeyboardManager();
  4161. this.#dispatchUpdateStates({
  4162. isEditing: false
  4163. });
  4164. }
  4165. }
  4166. registerEditorTypes(types) {
  4167. this.#editorTypes = types;
  4168. for (const editorType of this.#editorTypes) {
  4169. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  4170. }
  4171. }
  4172. getId() {
  4173. return this.#idManager.getId();
  4174. }
  4175. addLayer(layer) {
  4176. this.#allLayers.set(layer.pageIndex, layer);
  4177. if (this.#isEnabled) {
  4178. layer.enable();
  4179. } else {
  4180. layer.disable();
  4181. }
  4182. }
  4183. removeLayer(layer) {
  4184. this.#allLayers.delete(layer.pageIndex);
  4185. }
  4186. updateMode(mode) {
  4187. this.#mode = mode;
  4188. if (mode === _util.AnnotationEditorType.NONE) {
  4189. this.setEditingState(false);
  4190. this.#disableAll();
  4191. } else {
  4192. this.setEditingState(true);
  4193. this.#enableAll();
  4194. for (const layer of this.#allLayers.values()) {
  4195. layer.updateMode(mode);
  4196. }
  4197. }
  4198. }
  4199. updateToolbar(mode) {
  4200. if (mode === this.#mode) {
  4201. return;
  4202. }
  4203. this.#eventBus.dispatch("switchannotationeditormode", {
  4204. source: this,
  4205. mode
  4206. });
  4207. }
  4208. updateParams(type, value) {
  4209. for (const editor of this.#selectedEditors) {
  4210. editor.updateParams(type, value);
  4211. }
  4212. for (const editorType of this.#editorTypes) {
  4213. editorType.updateDefaultParams(type, value);
  4214. }
  4215. }
  4216. #enableAll() {
  4217. if (!this.#isEnabled) {
  4218. this.#isEnabled = true;
  4219. for (const layer of this.#allLayers.values()) {
  4220. layer.enable();
  4221. }
  4222. }
  4223. }
  4224. #disableAll() {
  4225. this.unselectAll();
  4226. if (this.#isEnabled) {
  4227. this.#isEnabled = false;
  4228. for (const layer of this.#allLayers.values()) {
  4229. layer.disable();
  4230. }
  4231. }
  4232. }
  4233. getEditors(pageIndex) {
  4234. const editors = [];
  4235. for (const editor of this.#allEditors.values()) {
  4236. if (editor.pageIndex === pageIndex) {
  4237. editors.push(editor);
  4238. }
  4239. }
  4240. return editors;
  4241. }
  4242. getEditor(id) {
  4243. return this.#allEditors.get(id);
  4244. }
  4245. addEditor(editor) {
  4246. this.#allEditors.set(editor.id, editor);
  4247. }
  4248. removeEditor(editor) {
  4249. this.#allEditors.delete(editor.id);
  4250. this.unselect(editor);
  4251. }
  4252. #addEditorToLayer(editor) {
  4253. const layer = this.#allLayers.get(editor.pageIndex);
  4254. if (layer) {
  4255. layer.addOrRebuild(editor);
  4256. } else {
  4257. this.addEditor(editor);
  4258. }
  4259. }
  4260. setActiveEditor(editor) {
  4261. if (this.#activeEditor === editor) {
  4262. return;
  4263. }
  4264. this.#activeEditor = editor;
  4265. if (editor) {
  4266. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  4267. }
  4268. }
  4269. toggleSelected(editor) {
  4270. if (this.#selectedEditors.has(editor)) {
  4271. this.#selectedEditors.delete(editor);
  4272. editor.unselect();
  4273. this.#dispatchUpdateStates({
  4274. hasSelectedEditor: this.hasSelection
  4275. });
  4276. return;
  4277. }
  4278. this.#selectedEditors.add(editor);
  4279. editor.select();
  4280. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  4281. this.#dispatchUpdateStates({
  4282. hasSelectedEditor: true
  4283. });
  4284. }
  4285. setSelected(editor) {
  4286. for (const ed of this.#selectedEditors) {
  4287. if (ed !== editor) {
  4288. ed.unselect();
  4289. }
  4290. }
  4291. this.#selectedEditors.clear();
  4292. this.#selectedEditors.add(editor);
  4293. editor.select();
  4294. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  4295. this.#dispatchUpdateStates({
  4296. hasSelectedEditor: true
  4297. });
  4298. }
  4299. isSelected(editor) {
  4300. return this.#selectedEditors.has(editor);
  4301. }
  4302. unselect(editor) {
  4303. editor.unselect();
  4304. this.#selectedEditors.delete(editor);
  4305. this.#dispatchUpdateStates({
  4306. hasSelectedEditor: this.hasSelection
  4307. });
  4308. }
  4309. get hasSelection() {
  4310. return this.#selectedEditors.size !== 0;
  4311. }
  4312. undo() {
  4313. this.#commandManager.undo();
  4314. this.#dispatchUpdateStates({
  4315. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  4316. hasSomethingToRedo: true,
  4317. isEmpty: this.#isEmpty()
  4318. });
  4319. }
  4320. redo() {
  4321. this.#commandManager.redo();
  4322. this.#dispatchUpdateStates({
  4323. hasSomethingToUndo: true,
  4324. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  4325. isEmpty: this.#isEmpty()
  4326. });
  4327. }
  4328. addCommands(params) {
  4329. this.#commandManager.add(params);
  4330. this.#dispatchUpdateStates({
  4331. hasSomethingToUndo: true,
  4332. hasSomethingToRedo: false,
  4333. isEmpty: this.#isEmpty()
  4334. });
  4335. }
  4336. #isEmpty() {
  4337. if (this.#allEditors.size === 0) {
  4338. return true;
  4339. }
  4340. if (this.#allEditors.size === 1) {
  4341. for (const editor of this.#allEditors.values()) {
  4342. return editor.isEmpty();
  4343. }
  4344. }
  4345. return false;
  4346. }
  4347. delete() {
  4348. if (this.#activeEditor) {
  4349. this.#activeEditor.commitOrRemove();
  4350. }
  4351. if (!this.hasSelection) {
  4352. return;
  4353. }
  4354. const editors = [...this.#selectedEditors];
  4355. const cmd = () => {
  4356. for (const editor of editors) {
  4357. editor.remove();
  4358. }
  4359. };
  4360. const undo = () => {
  4361. for (const editor of editors) {
  4362. this.#addEditorToLayer(editor);
  4363. }
  4364. };
  4365. this.addCommands({
  4366. cmd,
  4367. undo,
  4368. mustExec: true
  4369. });
  4370. }
  4371. copy() {
  4372. if (this.#activeEditor) {
  4373. this.#activeEditor.commitOrRemove();
  4374. }
  4375. if (this.hasSelection) {
  4376. const editors = [];
  4377. for (const editor of this.#selectedEditors) {
  4378. if (!editor.isEmpty()) {
  4379. editors.push(editor);
  4380. }
  4381. }
  4382. if (editors.length === 0) {
  4383. return;
  4384. }
  4385. this.#clipboardManager.copy(editors);
  4386. this.#dispatchUpdateStates({
  4387. hasEmptyClipboard: false
  4388. });
  4389. }
  4390. }
  4391. cut() {
  4392. this.copy();
  4393. this.delete();
  4394. }
  4395. paste() {
  4396. if (this.#clipboardManager.isEmpty()) {
  4397. return;
  4398. }
  4399. this.unselectAll();
  4400. const layer = this.#allLayers.get(this.#currentPageIndex);
  4401. const newEditors = this.#clipboardManager.paste().map(data => layer.deserialize(data));
  4402. const cmd = () => {
  4403. for (const editor of newEditors) {
  4404. this.#addEditorToLayer(editor);
  4405. }
  4406. this.#selectEditors(newEditors);
  4407. };
  4408. const undo = () => {
  4409. for (const editor of newEditors) {
  4410. editor.remove();
  4411. }
  4412. };
  4413. this.addCommands({
  4414. cmd,
  4415. undo,
  4416. mustExec: true
  4417. });
  4418. }
  4419. #selectEditors(editors) {
  4420. this.#selectedEditors.clear();
  4421. for (const editor of editors) {
  4422. if (editor.isEmpty()) {
  4423. continue;
  4424. }
  4425. this.#selectedEditors.add(editor);
  4426. editor.select();
  4427. }
  4428. this.#dispatchUpdateStates({
  4429. hasSelectedEditor: true
  4430. });
  4431. }
  4432. selectAll() {
  4433. for (const editor of this.#selectedEditors) {
  4434. editor.commit();
  4435. }
  4436. this.#selectEditors(this.#allEditors.values());
  4437. }
  4438. unselectAll() {
  4439. if (this.#activeEditor) {
  4440. this.#activeEditor.commitOrRemove();
  4441. return;
  4442. }
  4443. if (this.#selectEditors.size === 0) {
  4444. return;
  4445. }
  4446. for (const editor of this.#selectedEditors) {
  4447. editor.unselect();
  4448. }
  4449. this.#selectedEditors.clear();
  4450. this.#dispatchUpdateStates({
  4451. hasSelectedEditor: false
  4452. });
  4453. }
  4454. isActive(editor) {
  4455. return this.#activeEditor === editor;
  4456. }
  4457. getActive() {
  4458. return this.#activeEditor;
  4459. }
  4460. getMode() {
  4461. return this.#mode;
  4462. }
  4463. }
  4464. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
  4465. /***/ }),
  4466. /* 10 */
  4467. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4468. Object.defineProperty(exports, "__esModule", ({
  4469. value: true
  4470. }));
  4471. exports.MurmurHash3_64 = void 0;
  4472. var _util = __w_pdfjs_require__(1);
  4473. const SEED = 0xc3d2e1f0;
  4474. const MASK_HIGH = 0xffff0000;
  4475. const MASK_LOW = 0xffff;
  4476. class MurmurHash3_64 {
  4477. constructor(seed) {
  4478. this.h1 = seed ? seed & 0xffffffff : SEED;
  4479. this.h2 = seed ? seed & 0xffffffff : SEED;
  4480. }
  4481. update(input) {
  4482. let data, length;
  4483. if (typeof input === "string") {
  4484. data = new Uint8Array(input.length * 2);
  4485. length = 0;
  4486. for (let i = 0, ii = input.length; i < ii; i++) {
  4487. const code = input.charCodeAt(i);
  4488. if (code <= 0xff) {
  4489. data[length++] = code;
  4490. } else {
  4491. data[length++] = code >>> 8;
  4492. data[length++] = code & 0xff;
  4493. }
  4494. }
  4495. } else if ((0, _util.isArrayBuffer)(input)) {
  4496. data = input.slice();
  4497. length = data.byteLength;
  4498. } else {
  4499. throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
  4500. }
  4501. const blockCounts = length >> 2;
  4502. const tailLength = length - blockCounts * 4;
  4503. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  4504. let k1 = 0,
  4505. k2 = 0;
  4506. let h1 = this.h1,
  4507. h2 = this.h2;
  4508. const C1 = 0xcc9e2d51,
  4509. C2 = 0x1b873593;
  4510. const C1_LOW = C1 & MASK_LOW,
  4511. C2_LOW = C2 & MASK_LOW;
  4512. for (let i = 0; i < blockCounts; i++) {
  4513. if (i & 1) {
  4514. k1 = dataUint32[i];
  4515. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4516. k1 = k1 << 15 | k1 >>> 17;
  4517. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4518. h1 ^= k1;
  4519. h1 = h1 << 13 | h1 >>> 19;
  4520. h1 = h1 * 5 + 0xe6546b64;
  4521. } else {
  4522. k2 = dataUint32[i];
  4523. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  4524. k2 = k2 << 15 | k2 >>> 17;
  4525. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  4526. h2 ^= k2;
  4527. h2 = h2 << 13 | h2 >>> 19;
  4528. h2 = h2 * 5 + 0xe6546b64;
  4529. }
  4530. }
  4531. k1 = 0;
  4532. switch (tailLength) {
  4533. case 3:
  4534. k1 ^= data[blockCounts * 4 + 2] << 16;
  4535. case 2:
  4536. k1 ^= data[blockCounts * 4 + 1] << 8;
  4537. case 1:
  4538. k1 ^= data[blockCounts * 4];
  4539. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4540. k1 = k1 << 15 | k1 >>> 17;
  4541. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4542. if (blockCounts & 1) {
  4543. h1 ^= k1;
  4544. } else {
  4545. h2 ^= k1;
  4546. }
  4547. }
  4548. this.h1 = h1;
  4549. this.h2 = h2;
  4550. }
  4551. hexdigest() {
  4552. let h1 = this.h1,
  4553. h2 = this.h2;
  4554. h1 ^= h2 >>> 1;
  4555. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  4556. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  4557. h1 ^= h2 >>> 1;
  4558. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  4559. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  4560. h1 ^= h2 >>> 1;
  4561. const hex1 = (h1 >>> 0).toString(16),
  4562. hex2 = (h2 >>> 0).toString(16);
  4563. return hex1.padStart(8, "0") + hex2.padStart(8, "0");
  4564. }
  4565. }
  4566. exports.MurmurHash3_64 = MurmurHash3_64;
  4567. /***/ }),
  4568. /* 11 */
  4569. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4570. Object.defineProperty(exports, "__esModule", ({
  4571. value: true
  4572. }));
  4573. exports.FontLoader = exports.FontFaceObject = void 0;
  4574. var _util = __w_pdfjs_require__(1);
  4575. class BaseFontLoader {
  4576. constructor({
  4577. docId,
  4578. onUnsupportedFeature,
  4579. ownerDocument = globalThis.document,
  4580. styleElement = null
  4581. }) {
  4582. if (this.constructor === BaseFontLoader) {
  4583. (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
  4584. }
  4585. this.docId = docId;
  4586. this._onUnsupportedFeature = onUnsupportedFeature;
  4587. this._document = ownerDocument;
  4588. this.nativeFontFaces = [];
  4589. this.styleElement = null;
  4590. }
  4591. addNativeFontFace(nativeFontFace) {
  4592. this.nativeFontFaces.push(nativeFontFace);
  4593. this._document.fonts.add(nativeFontFace);
  4594. }
  4595. insertRule(rule) {
  4596. let styleElement = this.styleElement;
  4597. if (!styleElement) {
  4598. styleElement = this.styleElement = this._document.createElement("style");
  4599. styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
  4600. this._document.documentElement.getElementsByTagName("head")[0].append(styleElement);
  4601. }
  4602. const styleSheet = styleElement.sheet;
  4603. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  4604. }
  4605. clear() {
  4606. for (const nativeFontFace of this.nativeFontFaces) {
  4607. this._document.fonts.delete(nativeFontFace);
  4608. }
  4609. this.nativeFontFaces.length = 0;
  4610. if (this.styleElement) {
  4611. this.styleElement.remove();
  4612. this.styleElement = null;
  4613. }
  4614. }
  4615. async bind(font) {
  4616. if (font.attached || font.missingFile) {
  4617. return;
  4618. }
  4619. font.attached = true;
  4620. if (this.isFontLoadingAPISupported) {
  4621. const nativeFontFace = font.createNativeFontFace();
  4622. if (nativeFontFace) {
  4623. this.addNativeFontFace(nativeFontFace);
  4624. try {
  4625. await nativeFontFace.loaded;
  4626. } catch (ex) {
  4627. this._onUnsupportedFeature({
  4628. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  4629. });
  4630. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  4631. font.disableFontFace = true;
  4632. throw ex;
  4633. }
  4634. }
  4635. return;
  4636. }
  4637. const rule = font.createFontFaceRule();
  4638. if (rule) {
  4639. this.insertRule(rule);
  4640. if (this.isSyncFontLoadingSupported) {
  4641. return;
  4642. }
  4643. await new Promise(resolve => {
  4644. const request = this._queueLoadingCallback(resolve);
  4645. this._prepareFontLoadEvent([rule], [font], request);
  4646. });
  4647. }
  4648. }
  4649. _queueLoadingCallback(callback) {
  4650. (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
  4651. }
  4652. get isFontLoadingAPISupported() {
  4653. const hasFonts = !!this._document?.fonts;
  4654. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  4655. }
  4656. get isSyncFontLoadingSupported() {
  4657. (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
  4658. }
  4659. get _loadTestFont() {
  4660. (0, _util.unreachable)("Abstract method `_loadTestFont`.");
  4661. }
  4662. _prepareFontLoadEvent(rules, fontsToLoad, request) {
  4663. (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
  4664. }
  4665. }
  4666. let FontLoader;
  4667. exports.FontLoader = FontLoader;
  4668. {
  4669. exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
  4670. constructor(params) {
  4671. super(params);
  4672. this.loadingContext = {
  4673. requests: [],
  4674. nextRequestId: 0
  4675. };
  4676. this.loadTestFontId = 0;
  4677. }
  4678. get isSyncFontLoadingSupported() {
  4679. let supported = false;
  4680. if (typeof navigator === "undefined") {
  4681. supported = true;
  4682. } else {
  4683. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  4684. if (m?.[1] >= 14) {
  4685. supported = true;
  4686. }
  4687. }
  4688. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  4689. }
  4690. _queueLoadingCallback(callback) {
  4691. function completeRequest() {
  4692. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  4693. request.done = true;
  4694. while (context.requests.length > 0 && context.requests[0].done) {
  4695. const otherRequest = context.requests.shift();
  4696. setTimeout(otherRequest.callback, 0);
  4697. }
  4698. }
  4699. const context = this.loadingContext;
  4700. const request = {
  4701. id: `pdfjs-font-loading-${context.nextRequestId++}`,
  4702. done: false,
  4703. complete: completeRequest,
  4704. callback
  4705. };
  4706. context.requests.push(request);
  4707. return request;
  4708. }
  4709. get _loadTestFont() {
  4710. const getLoadTestFont = function () {
  4711. return 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==");
  4712. };
  4713. return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
  4714. }
  4715. _prepareFontLoadEvent(rules, fonts, request) {
  4716. function int32(data, offset) {
  4717. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  4718. }
  4719. function spliceString(s, offset, remove, insert) {
  4720. const chunk1 = s.substring(0, offset);
  4721. const chunk2 = s.substring(offset + remove);
  4722. return chunk1 + insert + chunk2;
  4723. }
  4724. let i, ii;
  4725. const canvas = this._document.createElement("canvas");
  4726. canvas.width = 1;
  4727. canvas.height = 1;
  4728. const ctx = canvas.getContext("2d");
  4729. let called = 0;
  4730. function isFontReady(name, callback) {
  4731. called++;
  4732. if (called > 30) {
  4733. (0, _util.warn)("Load test font never loaded.");
  4734. callback();
  4735. return;
  4736. }
  4737. ctx.font = "30px " + name;
  4738. ctx.fillText(".", 0, 20);
  4739. const imageData = ctx.getImageData(0, 0, 1, 1);
  4740. if (imageData.data[3] > 0) {
  4741. callback();
  4742. return;
  4743. }
  4744. setTimeout(isFontReady.bind(null, name, callback));
  4745. }
  4746. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  4747. let data = this._loadTestFont;
  4748. const COMMENT_OFFSET = 976;
  4749. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  4750. const CFF_CHECKSUM_OFFSET = 16;
  4751. const XXXX_VALUE = 0x58585858;
  4752. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  4753. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  4754. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  4755. }
  4756. if (i < loadTestFontId.length) {
  4757. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  4758. }
  4759. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  4760. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  4761. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  4762. this.insertRule(rule);
  4763. const names = [];
  4764. for (const font of fonts) {
  4765. names.push(font.loadedName);
  4766. }
  4767. names.push(loadTestFontId);
  4768. const div = this._document.createElement("div");
  4769. div.style.visibility = "hidden";
  4770. div.style.width = div.style.height = "10px";
  4771. div.style.position = "absolute";
  4772. div.style.top = div.style.left = "0px";
  4773. for (const name of names) {
  4774. const span = this._document.createElement("span");
  4775. span.textContent = "Hi";
  4776. span.style.fontFamily = name;
  4777. div.append(span);
  4778. }
  4779. this._document.body.append(div);
  4780. isFontReady(loadTestFontId, () => {
  4781. div.remove();
  4782. request.complete();
  4783. });
  4784. }
  4785. };
  4786. }
  4787. class FontFaceObject {
  4788. constructor(translatedData, {
  4789. isEvalSupported = true,
  4790. disableFontFace = false,
  4791. ignoreErrors = false,
  4792. onUnsupportedFeature,
  4793. fontRegistry = null
  4794. }) {
  4795. this.compiledGlyphs = Object.create(null);
  4796. for (const i in translatedData) {
  4797. this[i] = translatedData[i];
  4798. }
  4799. this.isEvalSupported = isEvalSupported !== false;
  4800. this.disableFontFace = disableFontFace === true;
  4801. this.ignoreErrors = ignoreErrors === true;
  4802. this._onUnsupportedFeature = onUnsupportedFeature;
  4803. this.fontRegistry = fontRegistry;
  4804. }
  4805. createNativeFontFace() {
  4806. if (!this.data || this.disableFontFace) {
  4807. return null;
  4808. }
  4809. let nativeFontFace;
  4810. if (!this.cssFontInfo) {
  4811. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  4812. } else {
  4813. const css = {
  4814. weight: this.cssFontInfo.fontWeight
  4815. };
  4816. if (this.cssFontInfo.italicAngle) {
  4817. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  4818. }
  4819. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  4820. }
  4821. if (this.fontRegistry) {
  4822. this.fontRegistry.registerFont(this);
  4823. }
  4824. return nativeFontFace;
  4825. }
  4826. createFontFaceRule() {
  4827. if (!this.data || this.disableFontFace) {
  4828. return null;
  4829. }
  4830. const data = (0, _util.bytesToString)(this.data);
  4831. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  4832. let rule;
  4833. if (!this.cssFontInfo) {
  4834. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  4835. } else {
  4836. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  4837. if (this.cssFontInfo.italicAngle) {
  4838. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  4839. }
  4840. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  4841. }
  4842. if (this.fontRegistry) {
  4843. this.fontRegistry.registerFont(this, url);
  4844. }
  4845. return rule;
  4846. }
  4847. getPathGenerator(objs, character) {
  4848. if (this.compiledGlyphs[character] !== undefined) {
  4849. return this.compiledGlyphs[character];
  4850. }
  4851. let cmds;
  4852. try {
  4853. cmds = objs.get(this.loadedName + "_path_" + character);
  4854. } catch (ex) {
  4855. if (!this.ignoreErrors) {
  4856. throw ex;
  4857. }
  4858. this._onUnsupportedFeature({
  4859. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  4860. });
  4861. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  4862. return this.compiledGlyphs[character] = function (c, size) {};
  4863. }
  4864. if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
  4865. const jsBuf = [];
  4866. for (const current of cmds) {
  4867. const args = current.args !== undefined ? current.args.join(",") : "";
  4868. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  4869. }
  4870. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  4871. }
  4872. return this.compiledGlyphs[character] = function (c, size) {
  4873. for (const current of cmds) {
  4874. if (current.cmd === "scale") {
  4875. current.args = [size, -size];
  4876. }
  4877. c[current.cmd].apply(c, current.args);
  4878. }
  4879. };
  4880. }
  4881. }
  4882. exports.FontFaceObject = FontFaceObject;
  4883. /***/ }),
  4884. /* 12 */
  4885. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4886. Object.defineProperty(exports, "__esModule", ({
  4887. value: true
  4888. }));
  4889. exports.CanvasGraphics = void 0;
  4890. var _util = __w_pdfjs_require__(1);
  4891. var _display_utils = __w_pdfjs_require__(4);
  4892. var _pattern_helper = __w_pdfjs_require__(13);
  4893. var _image_utils = __w_pdfjs_require__(14);
  4894. var _is_node = __w_pdfjs_require__(3);
  4895. const MIN_FONT_SIZE = 16;
  4896. const MAX_FONT_SIZE = 100;
  4897. const MAX_GROUP_SIZE = 4096;
  4898. const EXECUTION_TIME = 15;
  4899. const EXECUTION_STEPS = 10;
  4900. const COMPILE_TYPE3_GLYPHS = true;
  4901. const MAX_SIZE_TO_COMPILE = 1000;
  4902. const FULL_CHUNK_HEIGHT = 16;
  4903. const LINEWIDTH_SCALE_FACTOR = 1.000001;
  4904. function mirrorContextOperations(ctx, destCtx) {
  4905. if (ctx._removeMirroring) {
  4906. throw new Error("Context is already forwarding operations.");
  4907. }
  4908. ctx.__originalSave = ctx.save;
  4909. ctx.__originalRestore = ctx.restore;
  4910. ctx.__originalRotate = ctx.rotate;
  4911. ctx.__originalScale = ctx.scale;
  4912. ctx.__originalTranslate = ctx.translate;
  4913. ctx.__originalTransform = ctx.transform;
  4914. ctx.__originalSetTransform = ctx.setTransform;
  4915. ctx.__originalResetTransform = ctx.resetTransform;
  4916. ctx.__originalClip = ctx.clip;
  4917. ctx.__originalMoveTo = ctx.moveTo;
  4918. ctx.__originalLineTo = ctx.lineTo;
  4919. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  4920. ctx.__originalRect = ctx.rect;
  4921. ctx.__originalClosePath = ctx.closePath;
  4922. ctx.__originalBeginPath = ctx.beginPath;
  4923. ctx._removeMirroring = () => {
  4924. ctx.save = ctx.__originalSave;
  4925. ctx.restore = ctx.__originalRestore;
  4926. ctx.rotate = ctx.__originalRotate;
  4927. ctx.scale = ctx.__originalScale;
  4928. ctx.translate = ctx.__originalTranslate;
  4929. ctx.transform = ctx.__originalTransform;
  4930. ctx.setTransform = ctx.__originalSetTransform;
  4931. ctx.resetTransform = ctx.__originalResetTransform;
  4932. ctx.clip = ctx.__originalClip;
  4933. ctx.moveTo = ctx.__originalMoveTo;
  4934. ctx.lineTo = ctx.__originalLineTo;
  4935. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  4936. ctx.rect = ctx.__originalRect;
  4937. ctx.closePath = ctx.__originalClosePath;
  4938. ctx.beginPath = ctx.__originalBeginPath;
  4939. delete ctx._removeMirroring;
  4940. };
  4941. ctx.save = function ctxSave() {
  4942. destCtx.save();
  4943. this.__originalSave();
  4944. };
  4945. ctx.restore = function ctxRestore() {
  4946. destCtx.restore();
  4947. this.__originalRestore();
  4948. };
  4949. ctx.translate = function ctxTranslate(x, y) {
  4950. destCtx.translate(x, y);
  4951. this.__originalTranslate(x, y);
  4952. };
  4953. ctx.scale = function ctxScale(x, y) {
  4954. destCtx.scale(x, y);
  4955. this.__originalScale(x, y);
  4956. };
  4957. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  4958. destCtx.transform(a, b, c, d, e, f);
  4959. this.__originalTransform(a, b, c, d, e, f);
  4960. };
  4961. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  4962. destCtx.setTransform(a, b, c, d, e, f);
  4963. this.__originalSetTransform(a, b, c, d, e, f);
  4964. };
  4965. ctx.resetTransform = function ctxResetTransform() {
  4966. destCtx.resetTransform();
  4967. this.__originalResetTransform();
  4968. };
  4969. ctx.rotate = function ctxRotate(angle) {
  4970. destCtx.rotate(angle);
  4971. this.__originalRotate(angle);
  4972. };
  4973. ctx.clip = function ctxRotate(rule) {
  4974. destCtx.clip(rule);
  4975. this.__originalClip(rule);
  4976. };
  4977. ctx.moveTo = function (x, y) {
  4978. destCtx.moveTo(x, y);
  4979. this.__originalMoveTo(x, y);
  4980. };
  4981. ctx.lineTo = function (x, y) {
  4982. destCtx.lineTo(x, y);
  4983. this.__originalLineTo(x, y);
  4984. };
  4985. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  4986. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  4987. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  4988. };
  4989. ctx.rect = function (x, y, width, height) {
  4990. destCtx.rect(x, y, width, height);
  4991. this.__originalRect(x, y, width, height);
  4992. };
  4993. ctx.closePath = function () {
  4994. destCtx.closePath();
  4995. this.__originalClosePath();
  4996. };
  4997. ctx.beginPath = function () {
  4998. destCtx.beginPath();
  4999. this.__originalBeginPath();
  5000. };
  5001. }
  5002. function addContextCurrentTransform(ctx) {
  5003. if (ctx._transformStack) {
  5004. ctx._transformStack = [];
  5005. }
  5006. if (ctx.mozCurrentTransform) {
  5007. return;
  5008. }
  5009. ctx._originalSave = ctx.save;
  5010. ctx._originalRestore = ctx.restore;
  5011. ctx._originalRotate = ctx.rotate;
  5012. ctx._originalScale = ctx.scale;
  5013. ctx._originalTranslate = ctx.translate;
  5014. ctx._originalTransform = ctx.transform;
  5015. ctx._originalSetTransform = ctx.setTransform;
  5016. ctx._originalResetTransform = ctx.resetTransform;
  5017. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  5018. ctx._transformStack = [];
  5019. try {
  5020. const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth");
  5021. ctx._setLineWidth = desc.set;
  5022. ctx._getLineWidth = desc.get;
  5023. Object.defineProperty(ctx, "lineWidth", {
  5024. set: function setLineWidth(width) {
  5025. this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR);
  5026. },
  5027. get: function getLineWidth() {
  5028. return this._getLineWidth();
  5029. }
  5030. });
  5031. } catch (_) {}
  5032. Object.defineProperty(ctx, "mozCurrentTransform", {
  5033. get: function getCurrentTransform() {
  5034. return this._transformMatrix;
  5035. }
  5036. });
  5037. Object.defineProperty(ctx, "mozCurrentTransformInverse", {
  5038. get: function getCurrentTransformInverse() {
  5039. const [a, b, c, d, e, f] = this._transformMatrix;
  5040. const ad_bc = a * d - b * c;
  5041. const bc_ad = b * c - a * d;
  5042. return [d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc];
  5043. }
  5044. });
  5045. ctx.save = function ctxSave() {
  5046. const old = this._transformMatrix;
  5047. this._transformStack.push(old);
  5048. this._transformMatrix = old.slice(0, 6);
  5049. this._originalSave();
  5050. };
  5051. ctx.restore = function ctxRestore() {
  5052. if (this._transformStack.length === 0) {
  5053. (0, _util.warn)("Tried to restore a ctx when the stack was already empty.");
  5054. }
  5055. const prev = this._transformStack.pop();
  5056. if (prev) {
  5057. this._transformMatrix = prev;
  5058. this._originalRestore();
  5059. }
  5060. };
  5061. ctx.translate = function ctxTranslate(x, y) {
  5062. const m = this._transformMatrix;
  5063. m[4] = m[0] * x + m[2] * y + m[4];
  5064. m[5] = m[1] * x + m[3] * y + m[5];
  5065. this._originalTranslate(x, y);
  5066. };
  5067. ctx.scale = function ctxScale(x, y) {
  5068. const m = this._transformMatrix;
  5069. m[0] *= x;
  5070. m[1] *= x;
  5071. m[2] *= y;
  5072. m[3] *= y;
  5073. this._originalScale(x, y);
  5074. };
  5075. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  5076. const m = this._transformMatrix;
  5077. this._transformMatrix = [m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5]];
  5078. ctx._originalTransform(a, b, c, d, e, f);
  5079. };
  5080. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  5081. this._transformMatrix = [a, b, c, d, e, f];
  5082. ctx._originalSetTransform(a, b, c, d, e, f);
  5083. };
  5084. ctx.resetTransform = function ctxResetTransform() {
  5085. this._transformMatrix = [1, 0, 0, 1, 0, 0];
  5086. ctx._originalResetTransform();
  5087. };
  5088. ctx.rotate = function ctxRotate(angle) {
  5089. const cosValue = Math.cos(angle);
  5090. const sinValue = Math.sin(angle);
  5091. const m = this._transformMatrix;
  5092. this._transformMatrix = [m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * -sinValue + m[2] * cosValue, m[1] * -sinValue + m[3] * cosValue, m[4], m[5]];
  5093. this._originalRotate(angle);
  5094. };
  5095. }
  5096. class CachedCanvases {
  5097. constructor(canvasFactory) {
  5098. this.canvasFactory = canvasFactory;
  5099. this.cache = Object.create(null);
  5100. }
  5101. getCanvas(id, width, height, trackTransform) {
  5102. let canvasEntry;
  5103. if (this.cache[id] !== undefined) {
  5104. canvasEntry = this.cache[id];
  5105. this.canvasFactory.reset(canvasEntry, width, height);
  5106. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  5107. } else {
  5108. canvasEntry = this.canvasFactory.create(width, height);
  5109. this.cache[id] = canvasEntry;
  5110. }
  5111. if (trackTransform) {
  5112. addContextCurrentTransform(canvasEntry.context);
  5113. }
  5114. return canvasEntry;
  5115. }
  5116. delete(id) {
  5117. delete this.cache[id];
  5118. }
  5119. clear() {
  5120. for (const id in this.cache) {
  5121. const canvasEntry = this.cache[id];
  5122. this.canvasFactory.destroy(canvasEntry);
  5123. delete this.cache[id];
  5124. }
  5125. }
  5126. }
  5127. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  5128. const [a, b, c, d, tx, ty] = ctx.mozCurrentTransform;
  5129. if (b === 0 && c === 0) {
  5130. const tlX = destX * a + tx;
  5131. const rTlX = Math.round(tlX);
  5132. const tlY = destY * d + ty;
  5133. const rTlY = Math.round(tlY);
  5134. const brX = (destX + destW) * a + tx;
  5135. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  5136. const brY = (destY + destH) * d + ty;
  5137. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  5138. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  5139. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  5140. ctx.setTransform(a, b, c, d, tx, ty);
  5141. return [rWidth, rHeight];
  5142. }
  5143. if (a === 0 && d === 0) {
  5144. const tlX = destY * c + tx;
  5145. const rTlX = Math.round(tlX);
  5146. const tlY = destX * b + ty;
  5147. const rTlY = Math.round(tlY);
  5148. const brX = (destY + destH) * c + tx;
  5149. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  5150. const brY = (destX + destW) * b + ty;
  5151. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  5152. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  5153. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  5154. ctx.setTransform(a, b, c, d, tx, ty);
  5155. return [rHeight, rWidth];
  5156. }
  5157. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  5158. const scaleX = Math.hypot(a, b);
  5159. const scaleY = Math.hypot(c, d);
  5160. return [scaleX * destW, scaleY * destH];
  5161. }
  5162. function compileType3Glyph(imgData) {
  5163. const {
  5164. width,
  5165. height
  5166. } = imgData;
  5167. if (!COMPILE_TYPE3_GLYPHS || width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  5168. return null;
  5169. }
  5170. const POINT_TO_PROCESS_LIMIT = 1000;
  5171. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  5172. const width1 = width + 1;
  5173. let points = new Uint8Array(width1 * (height + 1));
  5174. let i, j, j0;
  5175. const lineSize = width + 7 & ~7;
  5176. let data = new Uint8Array(lineSize * height),
  5177. pos = 0;
  5178. for (const elem of imgData.data) {
  5179. let mask = 128;
  5180. while (mask > 0) {
  5181. data[pos++] = elem & mask ? 0 : 255;
  5182. mask >>= 1;
  5183. }
  5184. }
  5185. let count = 0;
  5186. pos = 0;
  5187. if (data[pos] !== 0) {
  5188. points[0] = 1;
  5189. ++count;
  5190. }
  5191. for (j = 1; j < width; j++) {
  5192. if (data[pos] !== data[pos + 1]) {
  5193. points[j] = data[pos] ? 2 : 1;
  5194. ++count;
  5195. }
  5196. pos++;
  5197. }
  5198. if (data[pos] !== 0) {
  5199. points[j] = 2;
  5200. ++count;
  5201. }
  5202. for (i = 1; i < height; i++) {
  5203. pos = i * lineSize;
  5204. j0 = i * width1;
  5205. if (data[pos - lineSize] !== data[pos]) {
  5206. points[j0] = data[pos] ? 1 : 8;
  5207. ++count;
  5208. }
  5209. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  5210. for (j = 1; j < width; j++) {
  5211. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  5212. if (POINT_TYPES[sum]) {
  5213. points[j0 + j] = POINT_TYPES[sum];
  5214. ++count;
  5215. }
  5216. pos++;
  5217. }
  5218. if (data[pos - lineSize] !== data[pos]) {
  5219. points[j0 + j] = data[pos] ? 2 : 4;
  5220. ++count;
  5221. }
  5222. if (count > POINT_TO_PROCESS_LIMIT) {
  5223. return null;
  5224. }
  5225. }
  5226. pos = lineSize * (height - 1);
  5227. j0 = i * width1;
  5228. if (data[pos] !== 0) {
  5229. points[j0] = 8;
  5230. ++count;
  5231. }
  5232. for (j = 1; j < width; j++) {
  5233. if (data[pos] !== data[pos + 1]) {
  5234. points[j0 + j] = data[pos] ? 4 : 8;
  5235. ++count;
  5236. }
  5237. pos++;
  5238. }
  5239. if (data[pos] !== 0) {
  5240. points[j0 + j] = 4;
  5241. ++count;
  5242. }
  5243. if (count > POINT_TO_PROCESS_LIMIT) {
  5244. return null;
  5245. }
  5246. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5247. let path, outlines, coords;
  5248. if (!_is_node.isNodeJS) {
  5249. path = new Path2D();
  5250. } else {
  5251. outlines = [];
  5252. }
  5253. for (i = 0; count && i <= height; i++) {
  5254. let p = i * width1;
  5255. const end = p + width;
  5256. while (p < end && !points[p]) {
  5257. p++;
  5258. }
  5259. if (p === end) {
  5260. continue;
  5261. }
  5262. if (path) {
  5263. path.moveTo(p % width1, i);
  5264. } else {
  5265. coords = [p % width1, i];
  5266. }
  5267. const p0 = p;
  5268. let type = points[p];
  5269. do {
  5270. const step = steps[type];
  5271. do {
  5272. p += step;
  5273. } while (!points[p]);
  5274. const pp = points[p];
  5275. if (pp !== 5 && pp !== 10) {
  5276. type = pp;
  5277. points[p] = 0;
  5278. } else {
  5279. type = pp & 0x33 * type >> 4;
  5280. points[p] &= type >> 2 | type << 2;
  5281. }
  5282. if (path) {
  5283. path.lineTo(p % width1, p / width1 | 0);
  5284. } else {
  5285. coords.push(p % width1, p / width1 | 0);
  5286. }
  5287. if (!points[p]) {
  5288. --count;
  5289. }
  5290. } while (p0 !== p);
  5291. if (!path) {
  5292. outlines.push(coords);
  5293. }
  5294. --i;
  5295. }
  5296. data = null;
  5297. points = null;
  5298. const drawOutline = function (c) {
  5299. c.save();
  5300. c.scale(1 / width, -1 / height);
  5301. c.translate(0, -height);
  5302. if (path) {
  5303. c.fill(path);
  5304. } else {
  5305. c.beginPath();
  5306. for (const o of outlines) {
  5307. c.moveTo(o[0], o[1]);
  5308. for (let l = 2, ll = o.length; l < ll; l += 2) {
  5309. c.lineTo(o[l], o[l + 1]);
  5310. }
  5311. }
  5312. c.fill();
  5313. }
  5314. c.beginPath();
  5315. c.restore();
  5316. };
  5317. return drawOutline;
  5318. }
  5319. class CanvasExtraState {
  5320. constructor(width, height) {
  5321. this.alphaIsShape = false;
  5322. this.fontSize = 0;
  5323. this.fontSizeScale = 1;
  5324. this.textMatrix = _util.IDENTITY_MATRIX;
  5325. this.textMatrixScale = 1;
  5326. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  5327. this.leading = 0;
  5328. this.x = 0;
  5329. this.y = 0;
  5330. this.lineX = 0;
  5331. this.lineY = 0;
  5332. this.charSpacing = 0;
  5333. this.wordSpacing = 0;
  5334. this.textHScale = 1;
  5335. this.textRenderingMode = _util.TextRenderingMode.FILL;
  5336. this.textRise = 0;
  5337. this.fillColor = "#000000";
  5338. this.strokeColor = "#000000";
  5339. this.patternFill = false;
  5340. this.fillAlpha = 1;
  5341. this.strokeAlpha = 1;
  5342. this.lineWidth = 1;
  5343. this.activeSMask = null;
  5344. this.transferMaps = null;
  5345. this.startNewPathAndClipBox([0, 0, width, height]);
  5346. }
  5347. clone() {
  5348. const clone = Object.create(this);
  5349. clone.clipBox = this.clipBox.slice();
  5350. return clone;
  5351. }
  5352. setCurrentPoint(x, y) {
  5353. this.x = x;
  5354. this.y = y;
  5355. }
  5356. updatePathMinMax(transform, x, y) {
  5357. [x, y] = _util.Util.applyTransform([x, y], transform);
  5358. this.minX = Math.min(this.minX, x);
  5359. this.minY = Math.min(this.minY, y);
  5360. this.maxX = Math.max(this.maxX, x);
  5361. this.maxY = Math.max(this.maxY, y);
  5362. }
  5363. updateRectMinMax(transform, rect) {
  5364. const p1 = _util.Util.applyTransform(rect, transform);
  5365. const p2 = _util.Util.applyTransform(rect.slice(2), transform);
  5366. this.minX = Math.min(this.minX, p1[0], p2[0]);
  5367. this.minY = Math.min(this.minY, p1[1], p2[1]);
  5368. this.maxX = Math.max(this.maxX, p1[0], p2[0]);
  5369. this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  5370. }
  5371. updateScalingPathMinMax(transform, minMax) {
  5372. _util.Util.scaleMinMax(transform, minMax);
  5373. this.minX = Math.min(this.minX, minMax[0]);
  5374. this.maxX = Math.max(this.maxX, minMax[1]);
  5375. this.minY = Math.min(this.minY, minMax[2]);
  5376. this.maxY = Math.max(this.maxY, minMax[3]);
  5377. }
  5378. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  5379. const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
  5380. if (minMax) {
  5381. minMax[0] = Math.min(minMax[0], box[0], box[2]);
  5382. minMax[1] = Math.max(minMax[1], box[0], box[2]);
  5383. minMax[2] = Math.min(minMax[2], box[1], box[3]);
  5384. minMax[3] = Math.max(minMax[3], box[1], box[3]);
  5385. return;
  5386. }
  5387. this.updateRectMinMax(transform, box);
  5388. }
  5389. getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5390. const box = [this.minX, this.minY, this.maxX, this.maxY];
  5391. if (pathType === _pattern_helper.PathType.STROKE) {
  5392. if (!transform) {
  5393. (0, _util.unreachable)("Stroke bounding box must include transform.");
  5394. }
  5395. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5396. const xStrokePad = scale[0] * this.lineWidth / 2;
  5397. const yStrokePad = scale[1] * this.lineWidth / 2;
  5398. box[0] -= xStrokePad;
  5399. box[1] -= yStrokePad;
  5400. box[2] += xStrokePad;
  5401. box[3] += yStrokePad;
  5402. }
  5403. return box;
  5404. }
  5405. updateClipFromPath() {
  5406. const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
  5407. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  5408. }
  5409. isEmptyClip() {
  5410. return this.minX === Infinity;
  5411. }
  5412. startNewPathAndClipBox(box) {
  5413. this.clipBox = box;
  5414. this.minX = Infinity;
  5415. this.minY = Infinity;
  5416. this.maxX = 0;
  5417. this.maxY = 0;
  5418. }
  5419. getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5420. return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  5421. }
  5422. }
  5423. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  5424. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  5425. ctx.putImageData(imgData, 0, 0);
  5426. return;
  5427. }
  5428. const height = imgData.height,
  5429. width = imgData.width;
  5430. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5431. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5432. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5433. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5434. let srcPos = 0,
  5435. destPos;
  5436. const src = imgData.data;
  5437. const dest = chunkImgData.data;
  5438. let i, j, thisChunkHeight, elemsInThisChunk;
  5439. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  5440. if (transferMaps) {
  5441. switch (transferMaps.length) {
  5442. case 1:
  5443. transferMapRed = transferMaps[0];
  5444. transferMapGreen = transferMaps[0];
  5445. transferMapBlue = transferMaps[0];
  5446. transferMapGray = transferMaps[0];
  5447. break;
  5448. case 4:
  5449. transferMapRed = transferMaps[0];
  5450. transferMapGreen = transferMaps[1];
  5451. transferMapBlue = transferMaps[2];
  5452. transferMapGray = transferMaps[3];
  5453. break;
  5454. }
  5455. }
  5456. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  5457. const srcLength = src.byteLength;
  5458. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  5459. const dest32DataLength = dest32.length;
  5460. const fullSrcDiff = width + 7 >> 3;
  5461. let white = 0xffffffff;
  5462. let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  5463. if (transferMapGray) {
  5464. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  5465. [white, black] = [black, white];
  5466. }
  5467. }
  5468. for (i = 0; i < totalChunks; i++) {
  5469. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5470. destPos = 0;
  5471. for (j = 0; j < thisChunkHeight; j++) {
  5472. const srcDiff = srcLength - srcPos;
  5473. let k = 0;
  5474. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  5475. const kEndUnrolled = kEnd & ~7;
  5476. let mask = 0;
  5477. let srcByte = 0;
  5478. for (; k < kEndUnrolled; k += 8) {
  5479. srcByte = src[srcPos++];
  5480. dest32[destPos++] = srcByte & 128 ? white : black;
  5481. dest32[destPos++] = srcByte & 64 ? white : black;
  5482. dest32[destPos++] = srcByte & 32 ? white : black;
  5483. dest32[destPos++] = srcByte & 16 ? white : black;
  5484. dest32[destPos++] = srcByte & 8 ? white : black;
  5485. dest32[destPos++] = srcByte & 4 ? white : black;
  5486. dest32[destPos++] = srcByte & 2 ? white : black;
  5487. dest32[destPos++] = srcByte & 1 ? white : black;
  5488. }
  5489. for (; k < kEnd; k++) {
  5490. if (mask === 0) {
  5491. srcByte = src[srcPos++];
  5492. mask = 128;
  5493. }
  5494. dest32[destPos++] = srcByte & mask ? white : black;
  5495. mask >>= 1;
  5496. }
  5497. }
  5498. while (destPos < dest32DataLength) {
  5499. dest32[destPos++] = 0;
  5500. }
  5501. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5502. }
  5503. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  5504. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5505. j = 0;
  5506. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  5507. for (i = 0; i < fullChunks; i++) {
  5508. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5509. srcPos += elemsInThisChunk;
  5510. if (hasTransferMaps) {
  5511. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5512. if (transferMapRed) {
  5513. dest[k + 0] = transferMapRed[dest[k + 0]];
  5514. }
  5515. if (transferMapGreen) {
  5516. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5517. }
  5518. if (transferMapBlue) {
  5519. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5520. }
  5521. }
  5522. }
  5523. ctx.putImageData(chunkImgData, 0, j);
  5524. j += FULL_CHUNK_HEIGHT;
  5525. }
  5526. if (i < totalChunks) {
  5527. elemsInThisChunk = width * partialChunkHeight * 4;
  5528. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5529. if (hasTransferMaps) {
  5530. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5531. if (transferMapRed) {
  5532. dest[k + 0] = transferMapRed[dest[k + 0]];
  5533. }
  5534. if (transferMapGreen) {
  5535. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5536. }
  5537. if (transferMapBlue) {
  5538. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5539. }
  5540. }
  5541. }
  5542. ctx.putImageData(chunkImgData, 0, j);
  5543. }
  5544. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  5545. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5546. thisChunkHeight = FULL_CHUNK_HEIGHT;
  5547. elemsInThisChunk = width * thisChunkHeight;
  5548. for (i = 0; i < totalChunks; i++) {
  5549. if (i >= fullChunks) {
  5550. thisChunkHeight = partialChunkHeight;
  5551. elemsInThisChunk = width * thisChunkHeight;
  5552. }
  5553. destPos = 0;
  5554. for (j = elemsInThisChunk; j--;) {
  5555. dest[destPos++] = src[srcPos++];
  5556. dest[destPos++] = src[srcPos++];
  5557. dest[destPos++] = src[srcPos++];
  5558. dest[destPos++] = 255;
  5559. }
  5560. if (hasTransferMaps) {
  5561. for (let k = 0; k < destPos; k += 4) {
  5562. if (transferMapRed) {
  5563. dest[k + 0] = transferMapRed[dest[k + 0]];
  5564. }
  5565. if (transferMapGreen) {
  5566. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5567. }
  5568. if (transferMapBlue) {
  5569. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5570. }
  5571. }
  5572. }
  5573. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5574. }
  5575. } else {
  5576. throw new Error(`bad image kind: ${imgData.kind}`);
  5577. }
  5578. }
  5579. function putBinaryImageMask(ctx, imgData) {
  5580. if (imgData.bitmap) {
  5581. ctx.drawImage(imgData.bitmap, 0, 0);
  5582. return;
  5583. }
  5584. const height = imgData.height,
  5585. width = imgData.width;
  5586. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5587. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5588. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5589. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5590. let srcPos = 0;
  5591. const src = imgData.data;
  5592. const dest = chunkImgData.data;
  5593. for (let i = 0; i < totalChunks; i++) {
  5594. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5595. ({
  5596. srcPos
  5597. } = (0, _image_utils.applyMaskImageData)({
  5598. src,
  5599. srcPos,
  5600. dest,
  5601. width,
  5602. height: thisChunkHeight
  5603. }));
  5604. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5605. }
  5606. }
  5607. function copyCtxState(sourceCtx, destCtx) {
  5608. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  5609. for (let i = 0, ii = properties.length; i < ii; i++) {
  5610. const property = properties[i];
  5611. if (sourceCtx[property] !== undefined) {
  5612. destCtx[property] = sourceCtx[property];
  5613. }
  5614. }
  5615. if (sourceCtx.setLineDash !== undefined) {
  5616. destCtx.setLineDash(sourceCtx.getLineDash());
  5617. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5618. }
  5619. }
  5620. function resetCtxToDefault(ctx, foregroundColor) {
  5621. ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
  5622. ctx.fillRule = "nonzero";
  5623. ctx.globalAlpha = 1;
  5624. ctx.lineWidth = 1;
  5625. ctx.lineCap = "butt";
  5626. ctx.lineJoin = "miter";
  5627. ctx.miterLimit = 10;
  5628. ctx.globalCompositeOperation = "source-over";
  5629. ctx.font = "10px sans-serif";
  5630. if (ctx.setLineDash !== undefined) {
  5631. ctx.setLineDash([]);
  5632. ctx.lineDashOffset = 0;
  5633. }
  5634. }
  5635. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  5636. const length = bytes.length;
  5637. for (let i = 3; i < length; i += 4) {
  5638. const alpha = bytes[i];
  5639. if (alpha === 0) {
  5640. bytes[i - 3] = r0;
  5641. bytes[i - 2] = g0;
  5642. bytes[i - 1] = b0;
  5643. } else if (alpha < 255) {
  5644. const alpha_ = 255 - alpha;
  5645. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  5646. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  5647. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  5648. }
  5649. }
  5650. }
  5651. function composeSMaskAlpha(maskData, layerData, transferMap) {
  5652. const length = maskData.length;
  5653. const scale = 1 / 255;
  5654. for (let i = 3; i < length; i += 4) {
  5655. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  5656. layerData[i] = layerData[i] * alpha * scale | 0;
  5657. }
  5658. }
  5659. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  5660. const length = maskData.length;
  5661. for (let i = 3; i < length; i += 4) {
  5662. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  5663. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  5664. }
  5665. }
  5666. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  5667. const hasBackdrop = !!backdrop;
  5668. const r0 = hasBackdrop ? backdrop[0] : 0;
  5669. const g0 = hasBackdrop ? backdrop[1] : 0;
  5670. const b0 = hasBackdrop ? backdrop[2] : 0;
  5671. let composeFn;
  5672. if (subtype === "Luminosity") {
  5673. composeFn = composeSMaskLuminosity;
  5674. } else {
  5675. composeFn = composeSMaskAlpha;
  5676. }
  5677. const PIXELS_TO_PROCESS = 1048576;
  5678. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5679. for (let row = 0; row < height; row += chunkSize) {
  5680. const chunkHeight = Math.min(chunkSize, height - row);
  5681. const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
  5682. const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
  5683. if (hasBackdrop) {
  5684. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  5685. }
  5686. composeFn(maskData.data, layerData.data, transferMap);
  5687. layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  5688. }
  5689. }
  5690. function composeSMask(ctx, smask, layerCtx, layerBox) {
  5691. const layerOffsetX = layerBox[0];
  5692. const layerOffsetY = layerBox[1];
  5693. const layerWidth = layerBox[2] - layerOffsetX;
  5694. const layerHeight = layerBox[3] - layerOffsetY;
  5695. if (layerWidth === 0 || layerHeight === 0) {
  5696. return;
  5697. }
  5698. genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  5699. ctx.save();
  5700. ctx.globalAlpha = 1;
  5701. ctx.globalCompositeOperation = "source-over";
  5702. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5703. ctx.drawImage(layerCtx.canvas, 0, 0);
  5704. ctx.restore();
  5705. }
  5706. function getImageSmoothingEnabled(transform, interpolate) {
  5707. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5708. scale[0] = Math.fround(scale[0]);
  5709. scale[1] = Math.fround(scale[1]);
  5710. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  5711. if (interpolate !== undefined) {
  5712. return interpolate;
  5713. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  5714. return true;
  5715. }
  5716. return false;
  5717. }
  5718. const LINE_CAP_STYLES = ["butt", "round", "square"];
  5719. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  5720. const NORMAL_CLIP = {};
  5721. const EO_CLIP = {};
  5722. class CanvasGraphics {
  5723. constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig, annotationCanvasMap, pageColors) {
  5724. this.ctx = canvasCtx;
  5725. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  5726. this.stateStack = [];
  5727. this.pendingClip = null;
  5728. this.pendingEOFill = false;
  5729. this.res = null;
  5730. this.xobjs = null;
  5731. this.commonObjs = commonObjs;
  5732. this.objs = objs;
  5733. this.canvasFactory = canvasFactory;
  5734. this.imageLayer = imageLayer;
  5735. this.groupStack = [];
  5736. this.processingType3 = null;
  5737. this.baseTransform = null;
  5738. this.baseTransformStack = [];
  5739. this.groupLevel = 0;
  5740. this.smaskStack = [];
  5741. this.smaskCounter = 0;
  5742. this.tempSMask = null;
  5743. this.suspendedCtx = null;
  5744. this.contentVisible = true;
  5745. this.markedContentStack = [];
  5746. this.optionalContentConfig = optionalContentConfig;
  5747. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  5748. this.cachedPatterns = new Map();
  5749. this.annotationCanvasMap = annotationCanvasMap;
  5750. this.viewportScale = 1;
  5751. this.outputScaleX = 1;
  5752. this.outputScaleY = 1;
  5753. this.backgroundColor = pageColors?.background || null;
  5754. this.foregroundColor = pageColors?.foreground || null;
  5755. if (canvasCtx) {
  5756. addContextCurrentTransform(canvasCtx);
  5757. }
  5758. this._cachedScaleForStroking = null;
  5759. this._cachedGetSinglePixelWidth = null;
  5760. this._cachedBitmapsMap = new Map();
  5761. }
  5762. getObject(data, fallback = null) {
  5763. if (typeof data === "string") {
  5764. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  5765. }
  5766. return fallback;
  5767. }
  5768. beginDrawing({
  5769. transform,
  5770. viewport,
  5771. transparency = false,
  5772. background = null
  5773. }) {
  5774. const width = this.ctx.canvas.width;
  5775. const height = this.ctx.canvas.height;
  5776. const defaultBackgroundColor = background || "#ffffff";
  5777. this.ctx.save();
  5778. if (this.foregroundColor && this.backgroundColor) {
  5779. this.ctx.fillStyle = this.foregroundColor;
  5780. const fg = this.foregroundColor = this.ctx.fillStyle;
  5781. this.ctx.fillStyle = this.backgroundColor;
  5782. const bg = this.backgroundColor = this.ctx.fillStyle;
  5783. let isValidDefaultBg = true;
  5784. let defaultBg = defaultBackgroundColor;
  5785. this.ctx.fillStyle = defaultBackgroundColor;
  5786. defaultBg = this.ctx.fillStyle;
  5787. isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
  5788. if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
  5789. this.foregroundColor = this.backgroundColor = null;
  5790. } else {
  5791. const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
  5792. const newComp = x => {
  5793. x /= 255;
  5794. return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  5795. };
  5796. const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
  5797. this.selectColor = (r, g, b) => {
  5798. const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
  5799. return Math.round(lumC) === lumB ? bg : fg;
  5800. };
  5801. }
  5802. }
  5803. this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
  5804. this.ctx.fillRect(0, 0, width, height);
  5805. this.ctx.restore();
  5806. if (transparency) {
  5807. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
  5808. this.compositeCtx = this.ctx;
  5809. this.transparentCanvas = transparentCanvas.canvas;
  5810. this.ctx = transparentCanvas.context;
  5811. this.ctx.save();
  5812. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  5813. }
  5814. this.ctx.save();
  5815. resetCtxToDefault(this.ctx, this.foregroundColor);
  5816. if (transform) {
  5817. this.ctx.transform.apply(this.ctx, transform);
  5818. this.outputScaleX = transform[0];
  5819. this.outputScaleY = transform[0];
  5820. }
  5821. this.ctx.transform.apply(this.ctx, viewport.transform);
  5822. this.viewportScale = viewport.scale;
  5823. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  5824. if (this.imageLayer) {
  5825. this.imageLayer.beginLayout();
  5826. }
  5827. }
  5828. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  5829. const argsArray = operatorList.argsArray;
  5830. const fnArray = operatorList.fnArray;
  5831. let i = executionStartIdx || 0;
  5832. const argsArrayLen = argsArray.length;
  5833. if (argsArrayLen === i) {
  5834. return i;
  5835. }
  5836. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  5837. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  5838. let steps = 0;
  5839. const commonObjs = this.commonObjs;
  5840. const objs = this.objs;
  5841. let fnId;
  5842. while (true) {
  5843. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  5844. stepper.breakIt(i, continueCallback);
  5845. return i;
  5846. }
  5847. fnId = fnArray[i];
  5848. if (fnId !== _util.OPS.dependency) {
  5849. this[fnId].apply(this, argsArray[i]);
  5850. } else {
  5851. for (const depObjId of argsArray[i]) {
  5852. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  5853. if (!objsPool.has(depObjId)) {
  5854. objsPool.get(depObjId, continueCallback);
  5855. return i;
  5856. }
  5857. }
  5858. }
  5859. i++;
  5860. if (i === argsArrayLen) {
  5861. return i;
  5862. }
  5863. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  5864. if (Date.now() > endTime) {
  5865. continueCallback();
  5866. return i;
  5867. }
  5868. steps = 0;
  5869. }
  5870. }
  5871. }
  5872. #restoreInitialState() {
  5873. while (this.stateStack.length || this.inSMaskMode) {
  5874. this.restore();
  5875. }
  5876. this.ctx.restore();
  5877. if (this.transparentCanvas) {
  5878. this.ctx = this.compositeCtx;
  5879. this.ctx.save();
  5880. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  5881. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  5882. this.ctx.restore();
  5883. this.transparentCanvas = null;
  5884. }
  5885. }
  5886. endDrawing() {
  5887. this.#restoreInitialState();
  5888. this.cachedCanvases.clear();
  5889. this.cachedPatterns.clear();
  5890. for (const cache of this._cachedBitmapsMap.values()) {
  5891. for (const canvas of cache.values()) {
  5892. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  5893. canvas.width = canvas.height = 0;
  5894. }
  5895. }
  5896. cache.clear();
  5897. }
  5898. this._cachedBitmapsMap.clear();
  5899. if (this.imageLayer) {
  5900. this.imageLayer.endLayout();
  5901. }
  5902. }
  5903. _scaleImage(img, inverseTransform) {
  5904. const width = img.width;
  5905. const height = img.height;
  5906. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  5907. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  5908. let paintWidth = width,
  5909. paintHeight = height;
  5910. let tmpCanvasId = "prescale1";
  5911. let tmpCanvas, tmpCtx;
  5912. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  5913. let newWidth = paintWidth,
  5914. newHeight = paintHeight;
  5915. if (widthScale > 2 && paintWidth > 1) {
  5916. newWidth = Math.ceil(paintWidth / 2);
  5917. widthScale /= paintWidth / newWidth;
  5918. }
  5919. if (heightScale > 2 && paintHeight > 1) {
  5920. newHeight = Math.ceil(paintHeight / 2);
  5921. heightScale /= paintHeight / newHeight;
  5922. }
  5923. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight, false);
  5924. tmpCtx = tmpCanvas.context;
  5925. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5926. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  5927. img = tmpCanvas.canvas;
  5928. paintWidth = newWidth;
  5929. paintHeight = newHeight;
  5930. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  5931. }
  5932. return {
  5933. img,
  5934. paintWidth,
  5935. paintHeight
  5936. };
  5937. }
  5938. _createMaskCanvas(img) {
  5939. const ctx = this.ctx;
  5940. const {
  5941. width,
  5942. height
  5943. } = img;
  5944. const fillColor = this.current.fillColor;
  5945. const isPatternFill = this.current.patternFill;
  5946. const currentTransform = ctx.mozCurrentTransform;
  5947. let cache, cacheKey, scaled, maskCanvas;
  5948. if ((img.bitmap || img.data) && img.count > 1) {
  5949. const mainKey = img.bitmap || img.data.buffer;
  5950. const withoutTranslation = currentTransform.slice(0, 4);
  5951. cacheKey = JSON.stringify(isPatternFill ? withoutTranslation : [withoutTranslation, fillColor]);
  5952. cache = this._cachedBitmapsMap.get(mainKey);
  5953. if (!cache) {
  5954. cache = new Map();
  5955. this._cachedBitmapsMap.set(mainKey, cache);
  5956. }
  5957. const cachedImage = cache.get(cacheKey);
  5958. if (cachedImage && !isPatternFill) {
  5959. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  5960. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  5961. return {
  5962. canvas: cachedImage,
  5963. offsetX,
  5964. offsetY
  5965. };
  5966. }
  5967. scaled = cachedImage;
  5968. }
  5969. if (!scaled) {
  5970. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height, false);
  5971. putBinaryImageMask(maskCanvas.context, img);
  5972. }
  5973. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  5974. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  5975. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  5976. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  5977. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  5978. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  5979. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  5980. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight, true);
  5981. const fillCtx = fillCanvas.context;
  5982. const offsetX = Math.min(cord1[0], cord2[0]);
  5983. const offsetY = Math.min(cord1[1], cord2[1]);
  5984. fillCtx.translate(-offsetX, -offsetY);
  5985. fillCtx.transform.apply(fillCtx, maskToCanvas);
  5986. if (!scaled) {
  5987. scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse);
  5988. scaled = scaled.img;
  5989. if (cache && isPatternFill) {
  5990. cache.set(cacheKey, scaled);
  5991. }
  5992. }
  5993. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(fillCtx.mozCurrentTransform, img.interpolate);
  5994. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  5995. fillCtx.globalCompositeOperation = "source-in";
  5996. const inverse = _util.Util.transform(fillCtx.mozCurrentTransformInverse, [1, 0, 0, 1, -offsetX, -offsetY]);
  5997. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  5998. fillCtx.fillRect(0, 0, width, height);
  5999. if (cache && !isPatternFill) {
  6000. this.cachedCanvases.delete("fillCanvas");
  6001. cache.set(cacheKey, fillCanvas.canvas);
  6002. }
  6003. return {
  6004. canvas: fillCanvas.canvas,
  6005. offsetX: Math.round(offsetX),
  6006. offsetY: Math.round(offsetY)
  6007. };
  6008. }
  6009. setLineWidth(width) {
  6010. if (width !== this.current.lineWidth) {
  6011. this._cachedScaleForStroking = null;
  6012. }
  6013. this.current.lineWidth = width;
  6014. this.ctx.lineWidth = width;
  6015. }
  6016. setLineCap(style) {
  6017. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6018. }
  6019. setLineJoin(style) {
  6020. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6021. }
  6022. setMiterLimit(limit) {
  6023. this.ctx.miterLimit = limit;
  6024. }
  6025. setDash(dashArray, dashPhase) {
  6026. const ctx = this.ctx;
  6027. if (ctx.setLineDash !== undefined) {
  6028. ctx.setLineDash(dashArray);
  6029. ctx.lineDashOffset = dashPhase;
  6030. }
  6031. }
  6032. setRenderingIntent(intent) {}
  6033. setFlatness(flatness) {}
  6034. setGState(states) {
  6035. for (let i = 0, ii = states.length; i < ii; i++) {
  6036. const state = states[i];
  6037. const key = state[0];
  6038. const value = state[1];
  6039. switch (key) {
  6040. case "LW":
  6041. this.setLineWidth(value);
  6042. break;
  6043. case "LC":
  6044. this.setLineCap(value);
  6045. break;
  6046. case "LJ":
  6047. this.setLineJoin(value);
  6048. break;
  6049. case "ML":
  6050. this.setMiterLimit(value);
  6051. break;
  6052. case "D":
  6053. this.setDash(value[0], value[1]);
  6054. break;
  6055. case "RI":
  6056. this.setRenderingIntent(value);
  6057. break;
  6058. case "FL":
  6059. this.setFlatness(value);
  6060. break;
  6061. case "Font":
  6062. this.setFont(value[0], value[1]);
  6063. break;
  6064. case "CA":
  6065. this.current.strokeAlpha = state[1];
  6066. break;
  6067. case "ca":
  6068. this.current.fillAlpha = state[1];
  6069. this.ctx.globalAlpha = state[1];
  6070. break;
  6071. case "BM":
  6072. this.ctx.globalCompositeOperation = value;
  6073. break;
  6074. case "SMask":
  6075. this.current.activeSMask = value ? this.tempSMask : null;
  6076. this.tempSMask = null;
  6077. this.checkSMaskState();
  6078. break;
  6079. case "TR":
  6080. this.current.transferMaps = value;
  6081. }
  6082. }
  6083. }
  6084. get inSMaskMode() {
  6085. return !!this.suspendedCtx;
  6086. }
  6087. checkSMaskState() {
  6088. const inSMaskMode = this.inSMaskMode;
  6089. if (this.current.activeSMask && !inSMaskMode) {
  6090. this.beginSMaskMode();
  6091. } else if (!this.current.activeSMask && inSMaskMode) {
  6092. this.endSMaskMode();
  6093. }
  6094. }
  6095. beginSMaskMode() {
  6096. if (this.inSMaskMode) {
  6097. throw new Error("beginSMaskMode called while already in smask mode");
  6098. }
  6099. const drawnWidth = this.ctx.canvas.width;
  6100. const drawnHeight = this.ctx.canvas.height;
  6101. const cacheId = "smaskGroupAt" + this.groupLevel;
  6102. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  6103. this.suspendedCtx = this.ctx;
  6104. this.ctx = scratchCanvas.context;
  6105. const ctx = this.ctx;
  6106. ctx.setTransform.apply(ctx, this.suspendedCtx.mozCurrentTransform);
  6107. copyCtxState(this.suspendedCtx, ctx);
  6108. mirrorContextOperations(ctx, this.suspendedCtx);
  6109. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  6110. }
  6111. endSMaskMode() {
  6112. if (!this.inSMaskMode) {
  6113. throw new Error("endSMaskMode called while not in smask mode");
  6114. }
  6115. this.ctx._removeMirroring();
  6116. copyCtxState(this.ctx, this.suspendedCtx);
  6117. this.ctx = this.suspendedCtx;
  6118. this.suspendedCtx = null;
  6119. }
  6120. compose(dirtyBox) {
  6121. if (!this.current.activeSMask) {
  6122. return;
  6123. }
  6124. if (!dirtyBox) {
  6125. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  6126. } else {
  6127. dirtyBox[0] = Math.floor(dirtyBox[0]);
  6128. dirtyBox[1] = Math.floor(dirtyBox[1]);
  6129. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  6130. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  6131. }
  6132. const smask = this.current.activeSMask;
  6133. const suspendedCtx = this.suspendedCtx;
  6134. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  6135. this.ctx.save();
  6136. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  6137. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  6138. this.ctx.restore();
  6139. }
  6140. save() {
  6141. if (this.inSMaskMode) {
  6142. copyCtxState(this.ctx, this.suspendedCtx);
  6143. this.suspendedCtx.save();
  6144. } else {
  6145. this.ctx.save();
  6146. }
  6147. const old = this.current;
  6148. this.stateStack.push(old);
  6149. this.current = old.clone();
  6150. }
  6151. restore() {
  6152. if (this.stateStack.length === 0 && this.inSMaskMode) {
  6153. this.endSMaskMode();
  6154. }
  6155. if (this.stateStack.length !== 0) {
  6156. this.current = this.stateStack.pop();
  6157. if (this.inSMaskMode) {
  6158. this.suspendedCtx.restore();
  6159. copyCtxState(this.suspendedCtx, this.ctx);
  6160. } else {
  6161. this.ctx.restore();
  6162. }
  6163. this.checkSMaskState();
  6164. this.pendingClip = null;
  6165. this._cachedScaleForStroking = null;
  6166. this._cachedGetSinglePixelWidth = null;
  6167. }
  6168. }
  6169. transform(a, b, c, d, e, f) {
  6170. this.ctx.transform(a, b, c, d, e, f);
  6171. this._cachedScaleForStroking = null;
  6172. this._cachedGetSinglePixelWidth = null;
  6173. }
  6174. constructPath(ops, args, minMax) {
  6175. const ctx = this.ctx;
  6176. const current = this.current;
  6177. let x = current.x,
  6178. y = current.y;
  6179. let startX, startY;
  6180. const currentTransform = ctx.mozCurrentTransform;
  6181. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  6182. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  6183. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6184. switch (ops[i] | 0) {
  6185. case _util.OPS.rectangle:
  6186. x = args[j++];
  6187. y = args[j++];
  6188. const width = args[j++];
  6189. const height = args[j++];
  6190. const xw = x + width;
  6191. const yh = y + height;
  6192. ctx.moveTo(x, y);
  6193. if (width === 0 || height === 0) {
  6194. ctx.lineTo(xw, yh);
  6195. } else {
  6196. ctx.lineTo(xw, y);
  6197. ctx.lineTo(xw, yh);
  6198. ctx.lineTo(x, yh);
  6199. }
  6200. if (!isScalingMatrix) {
  6201. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  6202. }
  6203. ctx.closePath();
  6204. break;
  6205. case _util.OPS.moveTo:
  6206. x = args[j++];
  6207. y = args[j++];
  6208. ctx.moveTo(x, y);
  6209. if (!isScalingMatrix) {
  6210. current.updatePathMinMax(currentTransform, x, y);
  6211. }
  6212. break;
  6213. case _util.OPS.lineTo:
  6214. x = args[j++];
  6215. y = args[j++];
  6216. ctx.lineTo(x, y);
  6217. if (!isScalingMatrix) {
  6218. current.updatePathMinMax(currentTransform, x, y);
  6219. }
  6220. break;
  6221. case _util.OPS.curveTo:
  6222. startX = x;
  6223. startY = y;
  6224. x = args[j + 4];
  6225. y = args[j + 5];
  6226. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  6227. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  6228. j += 6;
  6229. break;
  6230. case _util.OPS.curveTo2:
  6231. startX = x;
  6232. startY = y;
  6233. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  6234. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  6235. x = args[j + 2];
  6236. y = args[j + 3];
  6237. j += 4;
  6238. break;
  6239. case _util.OPS.curveTo3:
  6240. startX = x;
  6241. startY = y;
  6242. x = args[j + 2];
  6243. y = args[j + 3];
  6244. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6245. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  6246. j += 4;
  6247. break;
  6248. case _util.OPS.closePath:
  6249. ctx.closePath();
  6250. break;
  6251. }
  6252. }
  6253. if (isScalingMatrix) {
  6254. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  6255. }
  6256. current.setCurrentPoint(x, y);
  6257. }
  6258. closePath() {
  6259. this.ctx.closePath();
  6260. }
  6261. stroke(consumePath) {
  6262. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  6263. const ctx = this.ctx;
  6264. const strokeColor = this.current.strokeColor;
  6265. ctx.globalAlpha = this.current.strokeAlpha;
  6266. if (this.contentVisible) {
  6267. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  6268. ctx.save();
  6269. ctx.strokeStyle = strokeColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.STROKE);
  6270. this.rescaleAndStroke(false);
  6271. ctx.restore();
  6272. } else {
  6273. this.rescaleAndStroke(true);
  6274. }
  6275. }
  6276. if (consumePath) {
  6277. this.consumePath(this.current.getClippedPathBoundingBox());
  6278. }
  6279. ctx.globalAlpha = this.current.fillAlpha;
  6280. }
  6281. closeStroke() {
  6282. this.closePath();
  6283. this.stroke();
  6284. }
  6285. fill(consumePath) {
  6286. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  6287. const ctx = this.ctx;
  6288. const fillColor = this.current.fillColor;
  6289. const isPatternFill = this.current.patternFill;
  6290. let needRestore = false;
  6291. if (isPatternFill) {
  6292. ctx.save();
  6293. ctx.fillStyle = fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL);
  6294. needRestore = true;
  6295. }
  6296. const intersect = this.current.getClippedPathBoundingBox();
  6297. if (this.contentVisible && intersect !== null) {
  6298. if (this.pendingEOFill) {
  6299. ctx.fill("evenodd");
  6300. this.pendingEOFill = false;
  6301. } else {
  6302. ctx.fill();
  6303. }
  6304. }
  6305. if (needRestore) {
  6306. ctx.restore();
  6307. }
  6308. if (consumePath) {
  6309. this.consumePath(intersect);
  6310. }
  6311. }
  6312. eoFill() {
  6313. this.pendingEOFill = true;
  6314. this.fill();
  6315. }
  6316. fillStroke() {
  6317. this.fill(false);
  6318. this.stroke(false);
  6319. this.consumePath();
  6320. }
  6321. eoFillStroke() {
  6322. this.pendingEOFill = true;
  6323. this.fillStroke();
  6324. }
  6325. closeFillStroke() {
  6326. this.closePath();
  6327. this.fillStroke();
  6328. }
  6329. closeEOFillStroke() {
  6330. this.pendingEOFill = true;
  6331. this.closePath();
  6332. this.fillStroke();
  6333. }
  6334. endPath() {
  6335. this.consumePath();
  6336. }
  6337. clip() {
  6338. this.pendingClip = NORMAL_CLIP;
  6339. }
  6340. eoClip() {
  6341. this.pendingClip = EO_CLIP;
  6342. }
  6343. beginText() {
  6344. this.current.textMatrix = _util.IDENTITY_MATRIX;
  6345. this.current.textMatrixScale = 1;
  6346. this.current.x = this.current.lineX = 0;
  6347. this.current.y = this.current.lineY = 0;
  6348. }
  6349. endText() {
  6350. const paths = this.pendingTextPaths;
  6351. const ctx = this.ctx;
  6352. if (paths === undefined) {
  6353. ctx.beginPath();
  6354. return;
  6355. }
  6356. ctx.save();
  6357. ctx.beginPath();
  6358. for (const path of paths) {
  6359. ctx.setTransform.apply(ctx, path.transform);
  6360. ctx.translate(path.x, path.y);
  6361. path.addToPath(ctx, path.fontSize);
  6362. }
  6363. ctx.restore();
  6364. ctx.clip();
  6365. ctx.beginPath();
  6366. delete this.pendingTextPaths;
  6367. }
  6368. setCharSpacing(spacing) {
  6369. this.current.charSpacing = spacing;
  6370. }
  6371. setWordSpacing(spacing) {
  6372. this.current.wordSpacing = spacing;
  6373. }
  6374. setHScale(scale) {
  6375. this.current.textHScale = scale / 100;
  6376. }
  6377. setLeading(leading) {
  6378. this.current.leading = -leading;
  6379. }
  6380. setFont(fontRefName, size) {
  6381. const fontObj = this.commonObjs.get(fontRefName);
  6382. const current = this.current;
  6383. if (!fontObj) {
  6384. throw new Error(`Can't find font for ${fontRefName}`);
  6385. }
  6386. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6387. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  6388. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  6389. }
  6390. if (size < 0) {
  6391. size = -size;
  6392. current.fontDirection = -1;
  6393. } else {
  6394. current.fontDirection = 1;
  6395. }
  6396. this.current.font = fontObj;
  6397. this.current.fontSize = size;
  6398. if (fontObj.isType3Font) {
  6399. return;
  6400. }
  6401. const name = fontObj.loadedName || "sans-serif";
  6402. let bold = "normal";
  6403. if (fontObj.black) {
  6404. bold = "900";
  6405. } else if (fontObj.bold) {
  6406. bold = "bold";
  6407. }
  6408. const italic = fontObj.italic ? "italic" : "normal";
  6409. const typeface = `"${name}", ${fontObj.fallbackName}`;
  6410. let browserFontSize = size;
  6411. if (size < MIN_FONT_SIZE) {
  6412. browserFontSize = MIN_FONT_SIZE;
  6413. } else if (size > MAX_FONT_SIZE) {
  6414. browserFontSize = MAX_FONT_SIZE;
  6415. }
  6416. this.current.fontSizeScale = size / browserFontSize;
  6417. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  6418. }
  6419. setTextRenderingMode(mode) {
  6420. this.current.textRenderingMode = mode;
  6421. }
  6422. setTextRise(rise) {
  6423. this.current.textRise = rise;
  6424. }
  6425. moveText(x, y) {
  6426. this.current.x = this.current.lineX += x;
  6427. this.current.y = this.current.lineY += y;
  6428. }
  6429. setLeadingMoveText(x, y) {
  6430. this.setLeading(-y);
  6431. this.moveText(x, y);
  6432. }
  6433. setTextMatrix(a, b, c, d, e, f) {
  6434. this.current.textMatrix = [a, b, c, d, e, f];
  6435. this.current.textMatrixScale = Math.hypot(a, b);
  6436. this.current.x = this.current.lineX = 0;
  6437. this.current.y = this.current.lineY = 0;
  6438. }
  6439. nextLine() {
  6440. this.moveText(0, this.current.leading);
  6441. }
  6442. paintChar(character, x, y, patternTransform) {
  6443. const ctx = this.ctx;
  6444. const current = this.current;
  6445. const font = current.font;
  6446. const textRenderingMode = current.textRenderingMode;
  6447. const fontSize = current.fontSize / current.fontSizeScale;
  6448. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6449. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  6450. const patternFill = current.patternFill && !font.missingFile;
  6451. let addToPath;
  6452. if (font.disableFontFace || isAddToPathSet || patternFill) {
  6453. addToPath = font.getPathGenerator(this.commonObjs, character);
  6454. }
  6455. if (font.disableFontFace || patternFill) {
  6456. ctx.save();
  6457. ctx.translate(x, y);
  6458. ctx.beginPath();
  6459. addToPath(ctx, fontSize);
  6460. if (patternTransform) {
  6461. ctx.setTransform.apply(ctx, patternTransform);
  6462. }
  6463. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6464. ctx.fill();
  6465. }
  6466. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6467. ctx.stroke();
  6468. }
  6469. ctx.restore();
  6470. } else {
  6471. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6472. ctx.fillText(character, x, y);
  6473. }
  6474. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6475. ctx.strokeText(character, x, y);
  6476. }
  6477. }
  6478. if (isAddToPathSet) {
  6479. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6480. paths.push({
  6481. transform: ctx.mozCurrentTransform,
  6482. x,
  6483. y,
  6484. fontSize,
  6485. addToPath
  6486. });
  6487. }
  6488. }
  6489. get isFontSubpixelAAEnabled() {
  6490. const {
  6491. context: ctx
  6492. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10, false);
  6493. ctx.scale(1.5, 1);
  6494. ctx.fillText("I", 0, 10);
  6495. const data = ctx.getImageData(0, 0, 10, 10).data;
  6496. let enabled = false;
  6497. for (let i = 3; i < data.length; i += 4) {
  6498. if (data[i] > 0 && data[i] < 255) {
  6499. enabled = true;
  6500. break;
  6501. }
  6502. }
  6503. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  6504. }
  6505. showText(glyphs) {
  6506. const current = this.current;
  6507. const font = current.font;
  6508. if (font.isType3Font) {
  6509. return this.showType3Text(glyphs);
  6510. }
  6511. const fontSize = current.fontSize;
  6512. if (fontSize === 0) {
  6513. return undefined;
  6514. }
  6515. const ctx = this.ctx;
  6516. const fontSizeScale = current.fontSizeScale;
  6517. const charSpacing = current.charSpacing;
  6518. const wordSpacing = current.wordSpacing;
  6519. const fontDirection = current.fontDirection;
  6520. const textHScale = current.textHScale * fontDirection;
  6521. const glyphsLength = glyphs.length;
  6522. const vertical = font.vertical;
  6523. const spacingDir = vertical ? 1 : -1;
  6524. const defaultVMetrics = font.defaultVMetrics;
  6525. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  6526. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  6527. ctx.save();
  6528. ctx.transform.apply(ctx, current.textMatrix);
  6529. ctx.translate(current.x, current.y + current.textRise);
  6530. if (fontDirection > 0) {
  6531. ctx.scale(textHScale, -1);
  6532. } else {
  6533. ctx.scale(textHScale, 1);
  6534. }
  6535. let patternTransform;
  6536. if (current.patternFill) {
  6537. ctx.save();
  6538. const pattern = current.fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL);
  6539. patternTransform = ctx.mozCurrentTransform;
  6540. ctx.restore();
  6541. ctx.fillStyle = pattern;
  6542. }
  6543. let lineWidth = current.lineWidth;
  6544. const scale = current.textMatrixScale;
  6545. if (scale === 0 || lineWidth === 0) {
  6546. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6547. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6548. lineWidth = this.getSinglePixelWidth();
  6549. }
  6550. } else {
  6551. lineWidth /= scale;
  6552. }
  6553. if (fontSizeScale !== 1.0) {
  6554. ctx.scale(fontSizeScale, fontSizeScale);
  6555. lineWidth /= fontSizeScale;
  6556. }
  6557. ctx.lineWidth = lineWidth;
  6558. let x = 0,
  6559. i;
  6560. for (i = 0; i < glyphsLength; ++i) {
  6561. const glyph = glyphs[i];
  6562. if (typeof glyph === "number") {
  6563. x += spacingDir * glyph * fontSize / 1000;
  6564. continue;
  6565. }
  6566. let restoreNeeded = false;
  6567. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6568. const character = glyph.fontChar;
  6569. const accent = glyph.accent;
  6570. let scaledX, scaledY;
  6571. let width = glyph.width;
  6572. if (vertical) {
  6573. const vmetric = glyph.vmetric || defaultVMetrics;
  6574. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  6575. const vy = vmetric[2] * widthAdvanceScale;
  6576. width = vmetric ? -vmetric[0] : width;
  6577. scaledX = vx / fontSizeScale;
  6578. scaledY = (x + vy) / fontSizeScale;
  6579. } else {
  6580. scaledX = x / fontSizeScale;
  6581. scaledY = 0;
  6582. }
  6583. if (font.remeasure && width > 0) {
  6584. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  6585. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6586. const characterScaleX = width / measuredWidth;
  6587. restoreNeeded = true;
  6588. ctx.save();
  6589. ctx.scale(characterScaleX, 1);
  6590. scaledX /= characterScaleX;
  6591. } else if (width !== measuredWidth) {
  6592. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  6593. }
  6594. }
  6595. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  6596. if (simpleFillText && !accent) {
  6597. ctx.fillText(character, scaledX, scaledY);
  6598. } else {
  6599. this.paintChar(character, scaledX, scaledY, patternTransform);
  6600. if (accent) {
  6601. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  6602. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  6603. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  6604. }
  6605. }
  6606. }
  6607. let charWidth;
  6608. if (vertical) {
  6609. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  6610. } else {
  6611. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6612. }
  6613. x += charWidth;
  6614. if (restoreNeeded) {
  6615. ctx.restore();
  6616. }
  6617. }
  6618. if (vertical) {
  6619. current.y -= x;
  6620. } else {
  6621. current.x += x * textHScale;
  6622. }
  6623. ctx.restore();
  6624. this.compose();
  6625. return undefined;
  6626. }
  6627. showType3Text(glyphs) {
  6628. const ctx = this.ctx;
  6629. const current = this.current;
  6630. const font = current.font;
  6631. const fontSize = current.fontSize;
  6632. const fontDirection = current.fontDirection;
  6633. const spacingDir = font.vertical ? 1 : -1;
  6634. const charSpacing = current.charSpacing;
  6635. const wordSpacing = current.wordSpacing;
  6636. const textHScale = current.textHScale * fontDirection;
  6637. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6638. const glyphsLength = glyphs.length;
  6639. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  6640. let i, glyph, width, spacingLength;
  6641. if (isTextInvisible || fontSize === 0) {
  6642. return;
  6643. }
  6644. this._cachedScaleForStroking = null;
  6645. this._cachedGetSinglePixelWidth = null;
  6646. ctx.save();
  6647. ctx.transform.apply(ctx, current.textMatrix);
  6648. ctx.translate(current.x, current.y);
  6649. ctx.scale(textHScale, fontDirection);
  6650. for (i = 0; i < glyphsLength; ++i) {
  6651. glyph = glyphs[i];
  6652. if (typeof glyph === "number") {
  6653. spacingLength = spacingDir * glyph * fontSize / 1000;
  6654. this.ctx.translate(spacingLength, 0);
  6655. current.x += spacingLength * textHScale;
  6656. continue;
  6657. }
  6658. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6659. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  6660. if (!operatorList) {
  6661. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  6662. continue;
  6663. }
  6664. if (this.contentVisible) {
  6665. this.processingType3 = glyph;
  6666. this.save();
  6667. ctx.scale(fontSize, fontSize);
  6668. ctx.transform.apply(ctx, fontMatrix);
  6669. this.executeOperatorList(operatorList);
  6670. this.restore();
  6671. }
  6672. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  6673. width = transformed[0] * fontSize + spacing;
  6674. ctx.translate(width, 0);
  6675. current.x += width * textHScale;
  6676. }
  6677. ctx.restore();
  6678. this.processingType3 = null;
  6679. }
  6680. setCharWidth(xWidth, yWidth) {}
  6681. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  6682. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  6683. this.ctx.clip();
  6684. this.endPath();
  6685. }
  6686. getColorN_Pattern(IR) {
  6687. let pattern;
  6688. if (IR[0] === "TilingPattern") {
  6689. const color = IR[1];
  6690. const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  6691. const canvasGraphicsFactory = {
  6692. createCanvasGraphics: ctx => {
  6693. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
  6694. }
  6695. };
  6696. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  6697. } else {
  6698. pattern = this._getPattern(IR[1], IR[2]);
  6699. }
  6700. return pattern;
  6701. }
  6702. setStrokeColorN() {
  6703. this.current.strokeColor = this.getColorN_Pattern(arguments);
  6704. }
  6705. setFillColorN() {
  6706. this.current.fillColor = this.getColorN_Pattern(arguments);
  6707. this.current.patternFill = true;
  6708. }
  6709. setStrokeRGBColor(r, g, b) {
  6710. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6711. this.ctx.strokeStyle = color;
  6712. this.current.strokeColor = color;
  6713. }
  6714. setFillRGBColor(r, g, b) {
  6715. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6716. this.ctx.fillStyle = color;
  6717. this.current.fillColor = color;
  6718. this.current.patternFill = false;
  6719. }
  6720. _getPattern(objId, matrix = null) {
  6721. let pattern;
  6722. if (this.cachedPatterns.has(objId)) {
  6723. pattern = this.cachedPatterns.get(objId);
  6724. } else {
  6725. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  6726. this.cachedPatterns.set(objId, pattern);
  6727. }
  6728. if (matrix) {
  6729. pattern.matrix = matrix;
  6730. }
  6731. return pattern;
  6732. }
  6733. shadingFill(objId) {
  6734. if (!this.contentVisible) {
  6735. return;
  6736. }
  6737. const ctx = this.ctx;
  6738. this.save();
  6739. const pattern = this._getPattern(objId);
  6740. ctx.fillStyle = pattern.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.SHADING);
  6741. const inv = ctx.mozCurrentTransformInverse;
  6742. if (inv) {
  6743. const canvas = ctx.canvas;
  6744. const width = canvas.width;
  6745. const height = canvas.height;
  6746. const bl = _util.Util.applyTransform([0, 0], inv);
  6747. const br = _util.Util.applyTransform([0, height], inv);
  6748. const ul = _util.Util.applyTransform([width, 0], inv);
  6749. const ur = _util.Util.applyTransform([width, height], inv);
  6750. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6751. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6752. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6753. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6754. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6755. } else {
  6756. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6757. }
  6758. this.compose(this.current.getClippedPathBoundingBox());
  6759. this.restore();
  6760. }
  6761. beginInlineImage() {
  6762. (0, _util.unreachable)("Should not call beginInlineImage");
  6763. }
  6764. beginImageData() {
  6765. (0, _util.unreachable)("Should not call beginImageData");
  6766. }
  6767. paintFormXObjectBegin(matrix, bbox) {
  6768. if (!this.contentVisible) {
  6769. return;
  6770. }
  6771. this.save();
  6772. this.baseTransformStack.push(this.baseTransform);
  6773. if (Array.isArray(matrix) && matrix.length === 6) {
  6774. this.transform.apply(this, matrix);
  6775. }
  6776. this.baseTransform = this.ctx.mozCurrentTransform;
  6777. if (bbox) {
  6778. const width = bbox[2] - bbox[0];
  6779. const height = bbox[3] - bbox[1];
  6780. this.ctx.rect(bbox[0], bbox[1], width, height);
  6781. this.current.updateRectMinMax(this.ctx.mozCurrentTransform, bbox);
  6782. this.clip();
  6783. this.endPath();
  6784. }
  6785. }
  6786. paintFormXObjectEnd() {
  6787. if (!this.contentVisible) {
  6788. return;
  6789. }
  6790. this.restore();
  6791. this.baseTransform = this.baseTransformStack.pop();
  6792. }
  6793. beginGroup(group) {
  6794. if (!this.contentVisible) {
  6795. return;
  6796. }
  6797. this.save();
  6798. if (this.inSMaskMode) {
  6799. this.endSMaskMode();
  6800. this.current.activeSMask = null;
  6801. }
  6802. const currentCtx = this.ctx;
  6803. if (!group.isolated) {
  6804. (0, _util.info)("TODO: Support non-isolated groups.");
  6805. }
  6806. if (group.knockout) {
  6807. (0, _util.warn)("Knockout groups not supported.");
  6808. }
  6809. const currentTransform = currentCtx.mozCurrentTransform;
  6810. if (group.matrix) {
  6811. currentCtx.transform.apply(currentCtx, group.matrix);
  6812. }
  6813. if (!group.bbox) {
  6814. throw new Error("Bounding box is required.");
  6815. }
  6816. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  6817. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  6818. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6819. const offsetX = Math.floor(bounds[0]);
  6820. const offsetY = Math.floor(bounds[1]);
  6821. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6822. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6823. let scaleX = 1,
  6824. scaleY = 1;
  6825. if (drawnWidth > MAX_GROUP_SIZE) {
  6826. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6827. drawnWidth = MAX_GROUP_SIZE;
  6828. }
  6829. if (drawnHeight > MAX_GROUP_SIZE) {
  6830. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6831. drawnHeight = MAX_GROUP_SIZE;
  6832. }
  6833. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  6834. let cacheId = "groupAt" + this.groupLevel;
  6835. if (group.smask) {
  6836. cacheId += "_smask_" + this.smaskCounter++ % 2;
  6837. }
  6838. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  6839. const groupCtx = scratchCanvas.context;
  6840. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6841. groupCtx.translate(-offsetX, -offsetY);
  6842. groupCtx.transform.apply(groupCtx, currentTransform);
  6843. if (group.smask) {
  6844. this.smaskStack.push({
  6845. canvas: scratchCanvas.canvas,
  6846. context: groupCtx,
  6847. offsetX,
  6848. offsetY,
  6849. scaleX,
  6850. scaleY,
  6851. subtype: group.smask.subtype,
  6852. backdrop: group.smask.backdrop,
  6853. transferMap: group.smask.transferMap || null,
  6854. startTransformInverse: null
  6855. });
  6856. } else {
  6857. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6858. currentCtx.translate(offsetX, offsetY);
  6859. currentCtx.scale(scaleX, scaleY);
  6860. currentCtx.save();
  6861. }
  6862. copyCtxState(currentCtx, groupCtx);
  6863. this.ctx = groupCtx;
  6864. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  6865. this.groupStack.push(currentCtx);
  6866. this.groupLevel++;
  6867. }
  6868. endGroup(group) {
  6869. if (!this.contentVisible) {
  6870. return;
  6871. }
  6872. this.groupLevel--;
  6873. const groupCtx = this.ctx;
  6874. const ctx = this.groupStack.pop();
  6875. this.ctx = ctx;
  6876. this.ctx.imageSmoothingEnabled = false;
  6877. if (group.smask) {
  6878. this.tempSMask = this.smaskStack.pop();
  6879. this.restore();
  6880. } else {
  6881. this.ctx.restore();
  6882. const currentMtx = this.ctx.mozCurrentTransform;
  6883. this.restore();
  6884. this.ctx.save();
  6885. this.ctx.setTransform.apply(this.ctx, currentMtx);
  6886. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  6887. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6888. this.ctx.restore();
  6889. this.compose(dirtyBox);
  6890. }
  6891. }
  6892. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  6893. this.#restoreInitialState();
  6894. resetCtxToDefault(this.ctx, this.foregroundColor);
  6895. this.ctx.save();
  6896. this.save();
  6897. if (this.baseTransform) {
  6898. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  6899. }
  6900. if (Array.isArray(rect) && rect.length === 4) {
  6901. const width = rect[2] - rect[0];
  6902. const height = rect[3] - rect[1];
  6903. if (hasOwnCanvas && this.annotationCanvasMap) {
  6904. transform = transform.slice();
  6905. transform[4] -= rect[0];
  6906. transform[5] -= rect[1];
  6907. rect = rect.slice();
  6908. rect[0] = rect[1] = 0;
  6909. rect[2] = width;
  6910. rect[3] = height;
  6911. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale(this.ctx.mozCurrentTransform);
  6912. const {
  6913. viewportScale
  6914. } = this;
  6915. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  6916. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  6917. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  6918. const {
  6919. canvas,
  6920. context
  6921. } = this.annotationCanvas;
  6922. this.annotationCanvasMap.set(id, canvas);
  6923. this.annotationCanvas.savedCtx = this.ctx;
  6924. this.ctx = context;
  6925. addContextCurrentTransform(this.ctx);
  6926. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  6927. resetCtxToDefault(this.ctx, this.foregroundColor);
  6928. } else {
  6929. resetCtxToDefault(this.ctx, this.foregroundColor);
  6930. this.ctx.rect(rect[0], rect[1], width, height);
  6931. this.ctx.clip();
  6932. this.endPath();
  6933. }
  6934. }
  6935. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  6936. this.transform.apply(this, transform);
  6937. this.transform.apply(this, matrix);
  6938. }
  6939. endAnnotation() {
  6940. if (this.annotationCanvas) {
  6941. this.ctx = this.annotationCanvas.savedCtx;
  6942. delete this.annotationCanvas.savedCtx;
  6943. delete this.annotationCanvas;
  6944. }
  6945. }
  6946. paintImageMaskXObject(img) {
  6947. if (!this.contentVisible) {
  6948. return;
  6949. }
  6950. const count = img.count;
  6951. img = this.getObject(img.data, img);
  6952. img.count = count;
  6953. const ctx = this.ctx;
  6954. const glyph = this.processingType3;
  6955. if (glyph) {
  6956. if (glyph.compiled === undefined) {
  6957. glyph.compiled = compileType3Glyph(img);
  6958. }
  6959. if (glyph.compiled) {
  6960. glyph.compiled(ctx);
  6961. return;
  6962. }
  6963. }
  6964. const mask = this._createMaskCanvas(img);
  6965. const maskCanvas = mask.canvas;
  6966. ctx.save();
  6967. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6968. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  6969. ctx.restore();
  6970. this.compose();
  6971. }
  6972. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  6973. if (!this.contentVisible) {
  6974. return;
  6975. }
  6976. img = this.getObject(img.data, img);
  6977. const ctx = this.ctx;
  6978. ctx.save();
  6979. const currentTransform = ctx.mozCurrentTransform;
  6980. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  6981. const mask = this._createMaskCanvas(img);
  6982. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6983. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6984. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  6985. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  6986. ctx.drawImage(mask.canvas, x, y);
  6987. }
  6988. ctx.restore();
  6989. this.compose();
  6990. }
  6991. paintImageMaskXObjectGroup(images) {
  6992. if (!this.contentVisible) {
  6993. return;
  6994. }
  6995. const ctx = this.ctx;
  6996. const fillColor = this.current.fillColor;
  6997. const isPatternFill = this.current.patternFill;
  6998. for (const image of images) {
  6999. const {
  7000. data,
  7001. width,
  7002. height,
  7003. transform
  7004. } = image;
  7005. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height, false);
  7006. const maskCtx = maskCanvas.context;
  7007. maskCtx.save();
  7008. const img = this.getObject(data, image);
  7009. putBinaryImageMask(maskCtx, img);
  7010. maskCtx.globalCompositeOperation = "source-in";
  7011. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL) : fillColor;
  7012. maskCtx.fillRect(0, 0, width, height);
  7013. maskCtx.restore();
  7014. ctx.save();
  7015. ctx.transform.apply(ctx, transform);
  7016. ctx.scale(1, -1);
  7017. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  7018. ctx.restore();
  7019. }
  7020. this.compose();
  7021. }
  7022. paintImageXObject(objId) {
  7023. if (!this.contentVisible) {
  7024. return;
  7025. }
  7026. const imgData = this.getObject(objId);
  7027. if (!imgData) {
  7028. (0, _util.warn)("Dependent image isn't ready yet");
  7029. return;
  7030. }
  7031. this.paintInlineImageXObject(imgData);
  7032. }
  7033. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  7034. if (!this.contentVisible) {
  7035. return;
  7036. }
  7037. const imgData = this.getObject(objId);
  7038. if (!imgData) {
  7039. (0, _util.warn)("Dependent image isn't ready yet");
  7040. return;
  7041. }
  7042. const width = imgData.width;
  7043. const height = imgData.height;
  7044. const map = [];
  7045. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  7046. map.push({
  7047. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  7048. x: 0,
  7049. y: 0,
  7050. w: width,
  7051. h: height
  7052. });
  7053. }
  7054. this.paintInlineImageXObjectGroup(imgData, map);
  7055. }
  7056. paintInlineImageXObject(imgData) {
  7057. if (!this.contentVisible) {
  7058. return;
  7059. }
  7060. const width = imgData.width;
  7061. const height = imgData.height;
  7062. const ctx = this.ctx;
  7063. this.save();
  7064. ctx.scale(1 / width, -1 / height);
  7065. let imgToPaint;
  7066. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  7067. imgToPaint = imgData;
  7068. } else {
  7069. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height, false);
  7070. const tmpCtx = tmpCanvas.context;
  7071. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  7072. imgToPaint = tmpCanvas.canvas;
  7073. }
  7074. const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse);
  7075. ctx.imageSmoothingEnabled = getImageSmoothingEnabled(ctx.mozCurrentTransform, imgData.interpolate);
  7076. const [rWidth, rHeight] = drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  7077. if (this.imageLayer) {
  7078. const position = this.getCanvasPosition(0, -height);
  7079. this.imageLayer.appendImage({
  7080. imgData,
  7081. left: position[0],
  7082. top: position[1],
  7083. width: rWidth,
  7084. height: rHeight
  7085. });
  7086. }
  7087. this.compose();
  7088. this.restore();
  7089. }
  7090. paintInlineImageXObjectGroup(imgData, map) {
  7091. if (!this.contentVisible) {
  7092. return;
  7093. }
  7094. const ctx = this.ctx;
  7095. const w = imgData.width;
  7096. const h = imgData.height;
  7097. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h, false);
  7098. const tmpCtx = tmpCanvas.context;
  7099. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  7100. for (let i = 0, ii = map.length; i < ii; i++) {
  7101. const entry = map[i];
  7102. ctx.save();
  7103. ctx.transform.apply(ctx, entry.transform);
  7104. ctx.scale(1, -1);
  7105. drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  7106. if (this.imageLayer) {
  7107. const position = this.getCanvasPosition(entry.x, entry.y);
  7108. this.imageLayer.appendImage({
  7109. imgData,
  7110. left: position[0],
  7111. top: position[1],
  7112. width: w,
  7113. height: h
  7114. });
  7115. }
  7116. ctx.restore();
  7117. }
  7118. this.compose();
  7119. }
  7120. paintSolidColorImageMask() {
  7121. if (!this.contentVisible) {
  7122. return;
  7123. }
  7124. this.ctx.fillRect(0, 0, 1, 1);
  7125. this.compose();
  7126. }
  7127. markPoint(tag) {}
  7128. markPointProps(tag, properties) {}
  7129. beginMarkedContent(tag) {
  7130. this.markedContentStack.push({
  7131. visible: true
  7132. });
  7133. }
  7134. beginMarkedContentProps(tag, properties) {
  7135. if (tag === "OC") {
  7136. this.markedContentStack.push({
  7137. visible: this.optionalContentConfig.isVisible(properties)
  7138. });
  7139. } else {
  7140. this.markedContentStack.push({
  7141. visible: true
  7142. });
  7143. }
  7144. this.contentVisible = this.isContentVisible();
  7145. }
  7146. endMarkedContent() {
  7147. this.markedContentStack.pop();
  7148. this.contentVisible = this.isContentVisible();
  7149. }
  7150. beginCompat() {}
  7151. endCompat() {}
  7152. consumePath(clipBox) {
  7153. const isEmpty = this.current.isEmptyClip();
  7154. if (this.pendingClip) {
  7155. this.current.updateClipFromPath();
  7156. }
  7157. if (!this.pendingClip) {
  7158. this.compose(clipBox);
  7159. }
  7160. const ctx = this.ctx;
  7161. if (this.pendingClip) {
  7162. if (!isEmpty) {
  7163. if (this.pendingClip === EO_CLIP) {
  7164. ctx.clip("evenodd");
  7165. } else {
  7166. ctx.clip();
  7167. }
  7168. }
  7169. this.pendingClip = null;
  7170. }
  7171. this.current.startNewPathAndClipBox(this.current.clipBox);
  7172. ctx.beginPath();
  7173. }
  7174. getSinglePixelWidth() {
  7175. if (!this._cachedGetSinglePixelWidth) {
  7176. const m = this.ctx.mozCurrentTransform;
  7177. if (m[1] === 0 && m[2] === 0) {
  7178. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  7179. } else {
  7180. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  7181. const normX = Math.hypot(m[0], m[2]);
  7182. const normY = Math.hypot(m[1], m[3]);
  7183. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  7184. }
  7185. }
  7186. return this._cachedGetSinglePixelWidth;
  7187. }
  7188. getScaleForStroking() {
  7189. if (!this._cachedScaleForStroking) {
  7190. const {
  7191. lineWidth
  7192. } = this.current;
  7193. const m = this.ctx.mozCurrentTransform;
  7194. let scaleX, scaleY;
  7195. if (m[1] === 0 && m[2] === 0) {
  7196. const normX = Math.abs(m[0]);
  7197. const normY = Math.abs(m[3]);
  7198. if (lineWidth === 0) {
  7199. scaleX = 1 / normX;
  7200. scaleY = 1 / normY;
  7201. } else {
  7202. const scaledXLineWidth = normX * lineWidth;
  7203. const scaledYLineWidth = normY * lineWidth;
  7204. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  7205. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  7206. }
  7207. } else {
  7208. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  7209. const normX = Math.hypot(m[0], m[1]);
  7210. const normY = Math.hypot(m[2], m[3]);
  7211. if (lineWidth === 0) {
  7212. scaleX = normY / absDet;
  7213. scaleY = normX / absDet;
  7214. } else {
  7215. const baseArea = lineWidth * absDet;
  7216. scaleX = normY > baseArea ? normY / baseArea : 1;
  7217. scaleY = normX > baseArea ? normX / baseArea : 1;
  7218. }
  7219. }
  7220. this._cachedScaleForStroking = [scaleX, scaleY];
  7221. }
  7222. return this._cachedScaleForStroking;
  7223. }
  7224. rescaleAndStroke(saveRestore) {
  7225. const {
  7226. ctx
  7227. } = this;
  7228. const {
  7229. lineWidth
  7230. } = this.current;
  7231. const [scaleX, scaleY] = this.getScaleForStroking();
  7232. ctx.lineWidth = lineWidth || 1;
  7233. if (scaleX === 1 && scaleY === 1) {
  7234. ctx.stroke();
  7235. return;
  7236. }
  7237. let savedMatrix, savedDashes, savedDashOffset;
  7238. if (saveRestore) {
  7239. savedMatrix = ctx.mozCurrentTransform.slice();
  7240. savedDashes = ctx.getLineDash().slice();
  7241. savedDashOffset = ctx.lineDashOffset;
  7242. }
  7243. ctx.scale(scaleX, scaleY);
  7244. const scale = Math.max(scaleX, scaleY);
  7245. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  7246. ctx.lineDashOffset /= scale;
  7247. ctx.stroke();
  7248. if (saveRestore) {
  7249. ctx.setTransform(...savedMatrix);
  7250. ctx.setLineDash(savedDashes);
  7251. ctx.lineDashOffset = savedDashOffset;
  7252. }
  7253. }
  7254. getCanvasPosition(x, y) {
  7255. const transform = this.ctx.mozCurrentTransform;
  7256. return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
  7257. }
  7258. isContentVisible() {
  7259. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  7260. if (!this.markedContentStack[i].visible) {
  7261. return false;
  7262. }
  7263. }
  7264. return true;
  7265. }
  7266. }
  7267. exports.CanvasGraphics = CanvasGraphics;
  7268. for (const op in _util.OPS) {
  7269. if (CanvasGraphics.prototype[op] !== undefined) {
  7270. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  7271. }
  7272. }
  7273. /***/ }),
  7274. /* 13 */
  7275. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7276. Object.defineProperty(exports, "__esModule", ({
  7277. value: true
  7278. }));
  7279. exports.TilingPattern = exports.PathType = void 0;
  7280. exports.getShadingPattern = getShadingPattern;
  7281. var _util = __w_pdfjs_require__(1);
  7282. var _is_node = __w_pdfjs_require__(3);
  7283. const PathType = {
  7284. FILL: "Fill",
  7285. STROKE: "Stroke",
  7286. SHADING: "Shading"
  7287. };
  7288. exports.PathType = PathType;
  7289. function applyBoundingBox(ctx, bbox) {
  7290. if (!bbox || _is_node.isNodeJS) {
  7291. return;
  7292. }
  7293. const width = bbox[2] - bbox[0];
  7294. const height = bbox[3] - bbox[1];
  7295. const region = new Path2D();
  7296. region.rect(bbox[0], bbox[1], width, height);
  7297. ctx.clip(region);
  7298. }
  7299. class BaseShadingPattern {
  7300. constructor() {
  7301. if (this.constructor === BaseShadingPattern) {
  7302. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  7303. }
  7304. }
  7305. getPattern() {
  7306. (0, _util.unreachable)("Abstract method `getPattern` called.");
  7307. }
  7308. }
  7309. class RadialAxialShadingPattern extends BaseShadingPattern {
  7310. constructor(IR) {
  7311. super();
  7312. this._type = IR[1];
  7313. this._bbox = IR[2];
  7314. this._colorStops = IR[3];
  7315. this._p0 = IR[4];
  7316. this._p1 = IR[5];
  7317. this._r0 = IR[6];
  7318. this._r1 = IR[7];
  7319. this.matrix = null;
  7320. }
  7321. _createGradient(ctx) {
  7322. let grad;
  7323. if (this._type === "axial") {
  7324. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  7325. } else if (this._type === "radial") {
  7326. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  7327. }
  7328. for (const colorStop of this._colorStops) {
  7329. grad.addColorStop(colorStop[0], colorStop[1]);
  7330. }
  7331. return grad;
  7332. }
  7333. getPattern(ctx, owner, inverse, pathType) {
  7334. let pattern;
  7335. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  7336. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, ctx.mozCurrentTransform) || [0, 0, 0, 0];
  7337. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  7338. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  7339. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  7340. const tmpCtx = tmpCanvas.context;
  7341. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7342. tmpCtx.beginPath();
  7343. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7344. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  7345. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  7346. tmpCtx.transform.apply(tmpCtx, owner.baseTransform);
  7347. if (this.matrix) {
  7348. tmpCtx.transform.apply(tmpCtx, this.matrix);
  7349. }
  7350. applyBoundingBox(tmpCtx, this._bbox);
  7351. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  7352. tmpCtx.fill();
  7353. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  7354. const domMatrix = new DOMMatrix(inverse);
  7355. try {
  7356. pattern.setTransform(domMatrix);
  7357. } catch (ex) {
  7358. (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
  7359. }
  7360. } else {
  7361. applyBoundingBox(ctx, this._bbox);
  7362. pattern = this._createGradient(ctx);
  7363. }
  7364. return pattern;
  7365. }
  7366. }
  7367. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  7368. const coords = context.coords,
  7369. colors = context.colors;
  7370. const bytes = data.data,
  7371. rowSize = data.width * 4;
  7372. let tmp;
  7373. if (coords[p1 + 1] > coords[p2 + 1]) {
  7374. tmp = p1;
  7375. p1 = p2;
  7376. p2 = tmp;
  7377. tmp = c1;
  7378. c1 = c2;
  7379. c2 = tmp;
  7380. }
  7381. if (coords[p2 + 1] > coords[p3 + 1]) {
  7382. tmp = p2;
  7383. p2 = p3;
  7384. p3 = tmp;
  7385. tmp = c2;
  7386. c2 = c3;
  7387. c3 = tmp;
  7388. }
  7389. if (coords[p1 + 1] > coords[p2 + 1]) {
  7390. tmp = p1;
  7391. p1 = p2;
  7392. p2 = tmp;
  7393. tmp = c1;
  7394. c1 = c2;
  7395. c2 = tmp;
  7396. }
  7397. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  7398. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  7399. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  7400. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  7401. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  7402. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  7403. if (y1 >= y3) {
  7404. return;
  7405. }
  7406. const c1r = colors[c1],
  7407. c1g = colors[c1 + 1],
  7408. c1b = colors[c1 + 2];
  7409. const c2r = colors[c2],
  7410. c2g = colors[c2 + 1],
  7411. c2b = colors[c2 + 2];
  7412. const c3r = colors[c3],
  7413. c3g = colors[c3 + 1],
  7414. c3b = colors[c3 + 2];
  7415. const minY = Math.round(y1),
  7416. maxY = Math.round(y3);
  7417. let xa, car, cag, cab;
  7418. let xb, cbr, cbg, cbb;
  7419. for (let y = minY; y <= maxY; y++) {
  7420. if (y < y2) {
  7421. let k;
  7422. if (y < y1) {
  7423. k = 0;
  7424. } else {
  7425. k = (y1 - y) / (y1 - y2);
  7426. }
  7427. xa = x1 - (x1 - x2) * k;
  7428. car = c1r - (c1r - c2r) * k;
  7429. cag = c1g - (c1g - c2g) * k;
  7430. cab = c1b - (c1b - c2b) * k;
  7431. } else {
  7432. let k;
  7433. if (y > y3) {
  7434. k = 1;
  7435. } else if (y2 === y3) {
  7436. k = 0;
  7437. } else {
  7438. k = (y2 - y) / (y2 - y3);
  7439. }
  7440. xa = x2 - (x2 - x3) * k;
  7441. car = c2r - (c2r - c3r) * k;
  7442. cag = c2g - (c2g - c3g) * k;
  7443. cab = c2b - (c2b - c3b) * k;
  7444. }
  7445. let k;
  7446. if (y < y1) {
  7447. k = 0;
  7448. } else if (y > y3) {
  7449. k = 1;
  7450. } else {
  7451. k = (y1 - y) / (y1 - y3);
  7452. }
  7453. xb = x1 - (x1 - x3) * k;
  7454. cbr = c1r - (c1r - c3r) * k;
  7455. cbg = c1g - (c1g - c3g) * k;
  7456. cbb = c1b - (c1b - c3b) * k;
  7457. const x1_ = Math.round(Math.min(xa, xb));
  7458. const x2_ = Math.round(Math.max(xa, xb));
  7459. let j = rowSize * y + x1_ * 4;
  7460. for (let x = x1_; x <= x2_; x++) {
  7461. k = (xa - x) / (xa - xb);
  7462. if (k < 0) {
  7463. k = 0;
  7464. } else if (k > 1) {
  7465. k = 1;
  7466. }
  7467. bytes[j++] = car - (car - cbr) * k | 0;
  7468. bytes[j++] = cag - (cag - cbg) * k | 0;
  7469. bytes[j++] = cab - (cab - cbb) * k | 0;
  7470. bytes[j++] = 255;
  7471. }
  7472. }
  7473. }
  7474. function drawFigure(data, figure, context) {
  7475. const ps = figure.coords;
  7476. const cs = figure.colors;
  7477. let i, ii;
  7478. switch (figure.type) {
  7479. case "lattice":
  7480. const verticesPerRow = figure.verticesPerRow;
  7481. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  7482. const cols = verticesPerRow - 1;
  7483. for (i = 0; i < rows; i++) {
  7484. let q = i * verticesPerRow;
  7485. for (let j = 0; j < cols; j++, q++) {
  7486. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  7487. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  7488. }
  7489. }
  7490. break;
  7491. case "triangles":
  7492. for (i = 0, ii = ps.length; i < ii; i += 3) {
  7493. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  7494. }
  7495. break;
  7496. default:
  7497. throw new Error("illegal figure");
  7498. }
  7499. }
  7500. class MeshShadingPattern extends BaseShadingPattern {
  7501. constructor(IR) {
  7502. super();
  7503. this._coords = IR[2];
  7504. this._colors = IR[3];
  7505. this._figures = IR[4];
  7506. this._bounds = IR[5];
  7507. this._bbox = IR[7];
  7508. this._background = IR[8];
  7509. this.matrix = null;
  7510. }
  7511. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  7512. const EXPECTED_SCALE = 1.1;
  7513. const MAX_PATTERN_SIZE = 3000;
  7514. const BORDER_SIZE = 2;
  7515. const offsetX = Math.floor(this._bounds[0]);
  7516. const offsetY = Math.floor(this._bounds[1]);
  7517. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  7518. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  7519. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7520. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7521. const scaleX = boundsWidth / width;
  7522. const scaleY = boundsHeight / height;
  7523. const context = {
  7524. coords: this._coords,
  7525. colors: this._colors,
  7526. offsetX: -offsetX,
  7527. offsetY: -offsetY,
  7528. scaleX: 1 / scaleX,
  7529. scaleY: 1 / scaleY
  7530. };
  7531. const paddedWidth = width + BORDER_SIZE * 2;
  7532. const paddedHeight = height + BORDER_SIZE * 2;
  7533. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  7534. const tmpCtx = tmpCanvas.context;
  7535. const data = tmpCtx.createImageData(width, height);
  7536. if (backgroundColor) {
  7537. const bytes = data.data;
  7538. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  7539. bytes[i] = backgroundColor[0];
  7540. bytes[i + 1] = backgroundColor[1];
  7541. bytes[i + 2] = backgroundColor[2];
  7542. bytes[i + 3] = 255;
  7543. }
  7544. }
  7545. for (const figure of this._figures) {
  7546. drawFigure(data, figure, context);
  7547. }
  7548. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  7549. const canvas = tmpCanvas.canvas;
  7550. return {
  7551. canvas,
  7552. offsetX: offsetX - BORDER_SIZE * scaleX,
  7553. offsetY: offsetY - BORDER_SIZE * scaleY,
  7554. scaleX,
  7555. scaleY
  7556. };
  7557. }
  7558. getPattern(ctx, owner, inverse, pathType) {
  7559. applyBoundingBox(ctx, this._bbox);
  7560. let scale;
  7561. if (pathType === PathType.SHADING) {
  7562. scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  7563. } else {
  7564. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  7565. if (this.matrix) {
  7566. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7567. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  7568. }
  7569. }
  7570. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  7571. if (pathType !== PathType.SHADING) {
  7572. ctx.setTransform.apply(ctx, owner.baseTransform);
  7573. if (this.matrix) {
  7574. ctx.transform.apply(ctx, this.matrix);
  7575. }
  7576. }
  7577. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7578. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  7579. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  7580. }
  7581. }
  7582. class DummyShadingPattern extends BaseShadingPattern {
  7583. getPattern() {
  7584. return "hotpink";
  7585. }
  7586. }
  7587. function getShadingPattern(IR) {
  7588. switch (IR[0]) {
  7589. case "RadialAxial":
  7590. return new RadialAxialShadingPattern(IR);
  7591. case "Mesh":
  7592. return new MeshShadingPattern(IR);
  7593. case "Dummy":
  7594. return new DummyShadingPattern();
  7595. }
  7596. throw new Error(`Unknown IR type: ${IR[0]}`);
  7597. }
  7598. const PaintType = {
  7599. COLORED: 1,
  7600. UNCOLORED: 2
  7601. };
  7602. class TilingPattern {
  7603. static get MAX_PATTERN_SIZE() {
  7604. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  7605. }
  7606. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  7607. this.operatorList = IR[2];
  7608. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  7609. this.bbox = IR[4];
  7610. this.xstep = IR[5];
  7611. this.ystep = IR[6];
  7612. this.paintType = IR[7];
  7613. this.tilingType = IR[8];
  7614. this.color = color;
  7615. this.ctx = ctx;
  7616. this.canvasGraphicsFactory = canvasGraphicsFactory;
  7617. this.baseTransform = baseTransform;
  7618. }
  7619. createPatternCanvas(owner) {
  7620. const operatorList = this.operatorList;
  7621. const bbox = this.bbox;
  7622. const xstep = this.xstep;
  7623. const ystep = this.ystep;
  7624. const paintType = this.paintType;
  7625. const tilingType = this.tilingType;
  7626. const color = this.color;
  7627. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  7628. (0, _util.info)("TilingType: " + tilingType);
  7629. const x0 = bbox[0],
  7630. y0 = bbox[1],
  7631. x1 = bbox[2],
  7632. y1 = bbox[3];
  7633. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7634. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  7635. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  7636. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  7637. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  7638. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  7639. const tmpCtx = tmpCanvas.context;
  7640. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  7641. graphics.groupLevel = owner.groupLevel;
  7642. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  7643. let adjustedX0 = x0;
  7644. let adjustedY0 = y0;
  7645. let adjustedX1 = x1;
  7646. let adjustedY1 = y1;
  7647. if (x0 < 0) {
  7648. adjustedX0 = 0;
  7649. adjustedX1 += Math.abs(x0);
  7650. }
  7651. if (y0 < 0) {
  7652. adjustedY0 = 0;
  7653. adjustedY1 += Math.abs(y0);
  7654. }
  7655. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  7656. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  7657. tmpCtx.save();
  7658. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  7659. graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
  7660. graphics.executeOperatorList(operatorList);
  7661. graphics.endDrawing();
  7662. return {
  7663. canvas: tmpCanvas.canvas,
  7664. scaleX: dimx.scale,
  7665. scaleY: dimy.scale,
  7666. offsetX: adjustedX0,
  7667. offsetY: adjustedY0
  7668. };
  7669. }
  7670. getSizeAndScale(step, realOutputSize, scale) {
  7671. step = Math.abs(step);
  7672. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  7673. let size = Math.ceil(step * scale);
  7674. if (size >= maxSize) {
  7675. size = maxSize;
  7676. } else {
  7677. scale = size / step;
  7678. }
  7679. return {
  7680. scale,
  7681. size
  7682. };
  7683. }
  7684. clipBbox(graphics, x0, y0, x1, y1) {
  7685. const bboxWidth = x1 - x0;
  7686. const bboxHeight = y1 - y0;
  7687. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  7688. graphics.current.updateRectMinMax(graphics.ctx.mozCurrentTransform, [x0, y0, x1, y1]);
  7689. graphics.clip();
  7690. graphics.endPath();
  7691. }
  7692. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  7693. const context = graphics.ctx,
  7694. current = graphics.current;
  7695. switch (paintType) {
  7696. case PaintType.COLORED:
  7697. const ctx = this.ctx;
  7698. context.fillStyle = ctx.fillStyle;
  7699. context.strokeStyle = ctx.strokeStyle;
  7700. current.fillColor = ctx.fillStyle;
  7701. current.strokeColor = ctx.strokeStyle;
  7702. break;
  7703. case PaintType.UNCOLORED:
  7704. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  7705. context.fillStyle = cssColor;
  7706. context.strokeStyle = cssColor;
  7707. current.fillColor = cssColor;
  7708. current.strokeColor = cssColor;
  7709. break;
  7710. default:
  7711. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  7712. }
  7713. }
  7714. getPattern(ctx, owner, inverse, pathType) {
  7715. let matrix = inverse;
  7716. if (pathType !== PathType.SHADING) {
  7717. matrix = _util.Util.transform(matrix, owner.baseTransform);
  7718. if (this.matrix) {
  7719. matrix = _util.Util.transform(matrix, this.matrix);
  7720. }
  7721. }
  7722. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  7723. let domMatrix = new DOMMatrix(matrix);
  7724. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7725. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  7726. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  7727. try {
  7728. pattern.setTransform(domMatrix);
  7729. } catch (ex) {
  7730. (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
  7731. }
  7732. return pattern;
  7733. }
  7734. }
  7735. exports.TilingPattern = TilingPattern;
  7736. /***/ }),
  7737. /* 14 */
  7738. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7739. Object.defineProperty(exports, "__esModule", ({
  7740. value: true
  7741. }));
  7742. exports.applyMaskImageData = applyMaskImageData;
  7743. var _util = __w_pdfjs_require__(1);
  7744. function applyMaskImageData({
  7745. src,
  7746. srcPos = 0,
  7747. dest,
  7748. destPos = 0,
  7749. width,
  7750. height,
  7751. inverseDecode = false
  7752. }) {
  7753. const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  7754. const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
  7755. const widthInSource = width >> 3;
  7756. const widthRemainder = width & 7;
  7757. const srcLength = src.length;
  7758. dest = new Uint32Array(dest.buffer);
  7759. for (let i = 0; i < height; i++) {
  7760. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  7761. const elem = srcPos < srcLength ? src[srcPos] : 255;
  7762. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  7763. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  7764. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  7765. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  7766. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  7767. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  7768. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  7769. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  7770. }
  7771. if (widthRemainder === 0) {
  7772. continue;
  7773. }
  7774. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  7775. for (let j = 0; j < widthRemainder; j++) {
  7776. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  7777. }
  7778. }
  7779. return {
  7780. srcPos,
  7781. destPos
  7782. };
  7783. }
  7784. /***/ }),
  7785. /* 15 */
  7786. /***/ ((__unused_webpack_module, exports) => {
  7787. Object.defineProperty(exports, "__esModule", ({
  7788. value: true
  7789. }));
  7790. exports.GlobalWorkerOptions = void 0;
  7791. const GlobalWorkerOptions = Object.create(null);
  7792. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  7793. GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
  7794. GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
  7795. /***/ }),
  7796. /* 16 */
  7797. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7798. Object.defineProperty(exports, "__esModule", ({
  7799. value: true
  7800. }));
  7801. exports.MessageHandler = void 0;
  7802. var _util = __w_pdfjs_require__(1);
  7803. const CallbackKind = {
  7804. UNKNOWN: 0,
  7805. DATA: 1,
  7806. ERROR: 2
  7807. };
  7808. const StreamKind = {
  7809. UNKNOWN: 0,
  7810. CANCEL: 1,
  7811. CANCEL_COMPLETE: 2,
  7812. CLOSE: 3,
  7813. ENQUEUE: 4,
  7814. ERROR: 5,
  7815. PULL: 6,
  7816. PULL_COMPLETE: 7,
  7817. START_COMPLETE: 8
  7818. };
  7819. function wrapReason(reason) {
  7820. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  7821. (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  7822. }
  7823. switch (reason.name) {
  7824. case "AbortException":
  7825. return new _util.AbortException(reason.message);
  7826. case "MissingPDFException":
  7827. return new _util.MissingPDFException(reason.message);
  7828. case "PasswordException":
  7829. return new _util.PasswordException(reason.message, reason.code);
  7830. case "UnexpectedResponseException":
  7831. return new _util.UnexpectedResponseException(reason.message, reason.status);
  7832. case "UnknownErrorException":
  7833. return new _util.UnknownErrorException(reason.message, reason.details);
  7834. default:
  7835. return new _util.UnknownErrorException(reason.message, reason.toString());
  7836. }
  7837. }
  7838. class MessageHandler {
  7839. constructor(sourceName, targetName, comObj) {
  7840. this.sourceName = sourceName;
  7841. this.targetName = targetName;
  7842. this.comObj = comObj;
  7843. this.callbackId = 1;
  7844. this.streamId = 1;
  7845. this.streamSinks = Object.create(null);
  7846. this.streamControllers = Object.create(null);
  7847. this.callbackCapabilities = Object.create(null);
  7848. this.actionHandler = Object.create(null);
  7849. this._onComObjOnMessage = event => {
  7850. const data = event.data;
  7851. if (data.targetName !== this.sourceName) {
  7852. return;
  7853. }
  7854. if (data.stream) {
  7855. this._processStreamMessage(data);
  7856. return;
  7857. }
  7858. if (data.callback) {
  7859. const callbackId = data.callbackId;
  7860. const capability = this.callbackCapabilities[callbackId];
  7861. if (!capability) {
  7862. throw new Error(`Cannot resolve callback ${callbackId}`);
  7863. }
  7864. delete this.callbackCapabilities[callbackId];
  7865. if (data.callback === CallbackKind.DATA) {
  7866. capability.resolve(data.data);
  7867. } else if (data.callback === CallbackKind.ERROR) {
  7868. capability.reject(wrapReason(data.reason));
  7869. } else {
  7870. throw new Error("Unexpected callback case");
  7871. }
  7872. return;
  7873. }
  7874. const action = this.actionHandler[data.action];
  7875. if (!action) {
  7876. throw new Error(`Unknown action from worker: ${data.action}`);
  7877. }
  7878. if (data.callbackId) {
  7879. const cbSourceName = this.sourceName;
  7880. const cbTargetName = data.sourceName;
  7881. new Promise(function (resolve) {
  7882. resolve(action(data.data));
  7883. }).then(function (result) {
  7884. comObj.postMessage({
  7885. sourceName: cbSourceName,
  7886. targetName: cbTargetName,
  7887. callback: CallbackKind.DATA,
  7888. callbackId: data.callbackId,
  7889. data: result
  7890. });
  7891. }, function (reason) {
  7892. comObj.postMessage({
  7893. sourceName: cbSourceName,
  7894. targetName: cbTargetName,
  7895. callback: CallbackKind.ERROR,
  7896. callbackId: data.callbackId,
  7897. reason: wrapReason(reason)
  7898. });
  7899. });
  7900. return;
  7901. }
  7902. if (data.streamId) {
  7903. this._createStreamSink(data);
  7904. return;
  7905. }
  7906. action(data.data);
  7907. };
  7908. comObj.addEventListener("message", this._onComObjOnMessage);
  7909. }
  7910. on(actionName, handler) {
  7911. const ah = this.actionHandler;
  7912. if (ah[actionName]) {
  7913. throw new Error(`There is already an actionName called "${actionName}"`);
  7914. }
  7915. ah[actionName] = handler;
  7916. }
  7917. send(actionName, data, transfers) {
  7918. this.comObj.postMessage({
  7919. sourceName: this.sourceName,
  7920. targetName: this.targetName,
  7921. action: actionName,
  7922. data
  7923. }, transfers);
  7924. }
  7925. sendWithPromise(actionName, data, transfers) {
  7926. const callbackId = this.callbackId++;
  7927. const capability = (0, _util.createPromiseCapability)();
  7928. this.callbackCapabilities[callbackId] = capability;
  7929. try {
  7930. this.comObj.postMessage({
  7931. sourceName: this.sourceName,
  7932. targetName: this.targetName,
  7933. action: actionName,
  7934. callbackId,
  7935. data
  7936. }, transfers);
  7937. } catch (ex) {
  7938. capability.reject(ex);
  7939. }
  7940. return capability.promise;
  7941. }
  7942. sendWithStream(actionName, data, queueingStrategy, transfers) {
  7943. const streamId = this.streamId++,
  7944. sourceName = this.sourceName,
  7945. targetName = this.targetName,
  7946. comObj = this.comObj;
  7947. return new ReadableStream({
  7948. start: controller => {
  7949. const startCapability = (0, _util.createPromiseCapability)();
  7950. this.streamControllers[streamId] = {
  7951. controller,
  7952. startCall: startCapability,
  7953. pullCall: null,
  7954. cancelCall: null,
  7955. isClosed: false
  7956. };
  7957. comObj.postMessage({
  7958. sourceName,
  7959. targetName,
  7960. action: actionName,
  7961. streamId,
  7962. data,
  7963. desiredSize: controller.desiredSize
  7964. }, transfers);
  7965. return startCapability.promise;
  7966. },
  7967. pull: controller => {
  7968. const pullCapability = (0, _util.createPromiseCapability)();
  7969. this.streamControllers[streamId].pullCall = pullCapability;
  7970. comObj.postMessage({
  7971. sourceName,
  7972. targetName,
  7973. stream: StreamKind.PULL,
  7974. streamId,
  7975. desiredSize: controller.desiredSize
  7976. });
  7977. return pullCapability.promise;
  7978. },
  7979. cancel: reason => {
  7980. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  7981. const cancelCapability = (0, _util.createPromiseCapability)();
  7982. this.streamControllers[streamId].cancelCall = cancelCapability;
  7983. this.streamControllers[streamId].isClosed = true;
  7984. comObj.postMessage({
  7985. sourceName,
  7986. targetName,
  7987. stream: StreamKind.CANCEL,
  7988. streamId,
  7989. reason: wrapReason(reason)
  7990. });
  7991. return cancelCapability.promise;
  7992. }
  7993. }, queueingStrategy);
  7994. }
  7995. _createStreamSink(data) {
  7996. const streamId = data.streamId,
  7997. sourceName = this.sourceName,
  7998. targetName = data.sourceName,
  7999. comObj = this.comObj;
  8000. const self = this,
  8001. action = this.actionHandler[data.action];
  8002. const streamSink = {
  8003. enqueue(chunk, size = 1, transfers) {
  8004. if (this.isCancelled) {
  8005. return;
  8006. }
  8007. const lastDesiredSize = this.desiredSize;
  8008. this.desiredSize -= size;
  8009. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  8010. this.sinkCapability = (0, _util.createPromiseCapability)();
  8011. this.ready = this.sinkCapability.promise;
  8012. }
  8013. comObj.postMessage({
  8014. sourceName,
  8015. targetName,
  8016. stream: StreamKind.ENQUEUE,
  8017. streamId,
  8018. chunk
  8019. }, transfers);
  8020. },
  8021. close() {
  8022. if (this.isCancelled) {
  8023. return;
  8024. }
  8025. this.isCancelled = true;
  8026. comObj.postMessage({
  8027. sourceName,
  8028. targetName,
  8029. stream: StreamKind.CLOSE,
  8030. streamId
  8031. });
  8032. delete self.streamSinks[streamId];
  8033. },
  8034. error(reason) {
  8035. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  8036. if (this.isCancelled) {
  8037. return;
  8038. }
  8039. this.isCancelled = true;
  8040. comObj.postMessage({
  8041. sourceName,
  8042. targetName,
  8043. stream: StreamKind.ERROR,
  8044. streamId,
  8045. reason: wrapReason(reason)
  8046. });
  8047. },
  8048. sinkCapability: (0, _util.createPromiseCapability)(),
  8049. onPull: null,
  8050. onCancel: null,
  8051. isCancelled: false,
  8052. desiredSize: data.desiredSize,
  8053. ready: null
  8054. };
  8055. streamSink.sinkCapability.resolve();
  8056. streamSink.ready = streamSink.sinkCapability.promise;
  8057. this.streamSinks[streamId] = streamSink;
  8058. new Promise(function (resolve) {
  8059. resolve(action(data.data, streamSink));
  8060. }).then(function () {
  8061. comObj.postMessage({
  8062. sourceName,
  8063. targetName,
  8064. stream: StreamKind.START_COMPLETE,
  8065. streamId,
  8066. success: true
  8067. });
  8068. }, function (reason) {
  8069. comObj.postMessage({
  8070. sourceName,
  8071. targetName,
  8072. stream: StreamKind.START_COMPLETE,
  8073. streamId,
  8074. reason: wrapReason(reason)
  8075. });
  8076. });
  8077. }
  8078. _processStreamMessage(data) {
  8079. const streamId = data.streamId,
  8080. sourceName = this.sourceName,
  8081. targetName = data.sourceName,
  8082. comObj = this.comObj;
  8083. const streamController = this.streamControllers[streamId],
  8084. streamSink = this.streamSinks[streamId];
  8085. switch (data.stream) {
  8086. case StreamKind.START_COMPLETE:
  8087. if (data.success) {
  8088. streamController.startCall.resolve();
  8089. } else {
  8090. streamController.startCall.reject(wrapReason(data.reason));
  8091. }
  8092. break;
  8093. case StreamKind.PULL_COMPLETE:
  8094. if (data.success) {
  8095. streamController.pullCall.resolve();
  8096. } else {
  8097. streamController.pullCall.reject(wrapReason(data.reason));
  8098. }
  8099. break;
  8100. case StreamKind.PULL:
  8101. if (!streamSink) {
  8102. comObj.postMessage({
  8103. sourceName,
  8104. targetName,
  8105. stream: StreamKind.PULL_COMPLETE,
  8106. streamId,
  8107. success: true
  8108. });
  8109. break;
  8110. }
  8111. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  8112. streamSink.sinkCapability.resolve();
  8113. }
  8114. streamSink.desiredSize = data.desiredSize;
  8115. new Promise(function (resolve) {
  8116. resolve(streamSink.onPull && streamSink.onPull());
  8117. }).then(function () {
  8118. comObj.postMessage({
  8119. sourceName,
  8120. targetName,
  8121. stream: StreamKind.PULL_COMPLETE,
  8122. streamId,
  8123. success: true
  8124. });
  8125. }, function (reason) {
  8126. comObj.postMessage({
  8127. sourceName,
  8128. targetName,
  8129. stream: StreamKind.PULL_COMPLETE,
  8130. streamId,
  8131. reason: wrapReason(reason)
  8132. });
  8133. });
  8134. break;
  8135. case StreamKind.ENQUEUE:
  8136. (0, _util.assert)(streamController, "enqueue should have stream controller");
  8137. if (streamController.isClosed) {
  8138. break;
  8139. }
  8140. streamController.controller.enqueue(data.chunk);
  8141. break;
  8142. case StreamKind.CLOSE:
  8143. (0, _util.assert)(streamController, "close should have stream controller");
  8144. if (streamController.isClosed) {
  8145. break;
  8146. }
  8147. streamController.isClosed = true;
  8148. streamController.controller.close();
  8149. this._deleteStreamController(streamController, streamId);
  8150. break;
  8151. case StreamKind.ERROR:
  8152. (0, _util.assert)(streamController, "error should have stream controller");
  8153. streamController.controller.error(wrapReason(data.reason));
  8154. this._deleteStreamController(streamController, streamId);
  8155. break;
  8156. case StreamKind.CANCEL_COMPLETE:
  8157. if (data.success) {
  8158. streamController.cancelCall.resolve();
  8159. } else {
  8160. streamController.cancelCall.reject(wrapReason(data.reason));
  8161. }
  8162. this._deleteStreamController(streamController, streamId);
  8163. break;
  8164. case StreamKind.CANCEL:
  8165. if (!streamSink) {
  8166. break;
  8167. }
  8168. new Promise(function (resolve) {
  8169. resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
  8170. }).then(function () {
  8171. comObj.postMessage({
  8172. sourceName,
  8173. targetName,
  8174. stream: StreamKind.CANCEL_COMPLETE,
  8175. streamId,
  8176. success: true
  8177. });
  8178. }, function (reason) {
  8179. comObj.postMessage({
  8180. sourceName,
  8181. targetName,
  8182. stream: StreamKind.CANCEL_COMPLETE,
  8183. streamId,
  8184. reason: wrapReason(reason)
  8185. });
  8186. });
  8187. streamSink.sinkCapability.reject(wrapReason(data.reason));
  8188. streamSink.isCancelled = true;
  8189. delete this.streamSinks[streamId];
  8190. break;
  8191. default:
  8192. throw new Error("Unexpected stream case");
  8193. }
  8194. }
  8195. async _deleteStreamController(streamController, streamId) {
  8196. await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
  8197. delete this.streamControllers[streamId];
  8198. }
  8199. destroy() {
  8200. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  8201. }
  8202. }
  8203. exports.MessageHandler = MessageHandler;
  8204. /***/ }),
  8205. /* 17 */
  8206. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8207. Object.defineProperty(exports, "__esModule", ({
  8208. value: true
  8209. }));
  8210. exports.Metadata = void 0;
  8211. var _util = __w_pdfjs_require__(1);
  8212. class Metadata {
  8213. #metadataMap;
  8214. #data;
  8215. constructor({
  8216. parsedData,
  8217. rawData
  8218. }) {
  8219. this.#metadataMap = parsedData;
  8220. this.#data = rawData;
  8221. }
  8222. getRaw() {
  8223. return this.#data;
  8224. }
  8225. get(name) {
  8226. return this.#metadataMap.get(name) ?? null;
  8227. }
  8228. getAll() {
  8229. return (0, _util.objectFromMap)(this.#metadataMap);
  8230. }
  8231. has(name) {
  8232. return this.#metadataMap.has(name);
  8233. }
  8234. }
  8235. exports.Metadata = Metadata;
  8236. /***/ }),
  8237. /* 18 */
  8238. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8239. Object.defineProperty(exports, "__esModule", ({
  8240. value: true
  8241. }));
  8242. exports.OptionalContentConfig = void 0;
  8243. var _util = __w_pdfjs_require__(1);
  8244. const INTERNAL = Symbol("INTERNAL");
  8245. class OptionalContentGroup {
  8246. #visible = true;
  8247. constructor(name, intent) {
  8248. this.name = name;
  8249. this.intent = intent;
  8250. }
  8251. get visible() {
  8252. return this.#visible;
  8253. }
  8254. _setVisible(internal, visible) {
  8255. if (internal !== INTERNAL) {
  8256. (0, _util.unreachable)("Internal method `_setVisible` called.");
  8257. }
  8258. this.#visible = visible;
  8259. }
  8260. }
  8261. class OptionalContentConfig {
  8262. #cachedHasInitialVisibility = true;
  8263. #groups = new Map();
  8264. #initialVisibility = null;
  8265. #order = null;
  8266. constructor(data) {
  8267. this.name = null;
  8268. this.creator = null;
  8269. if (data === null) {
  8270. return;
  8271. }
  8272. this.name = data.name;
  8273. this.creator = data.creator;
  8274. this.#order = data.order;
  8275. for (const group of data.groups) {
  8276. this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  8277. }
  8278. if (data.baseState === "OFF") {
  8279. for (const group of this.#groups.values()) {
  8280. group._setVisible(INTERNAL, false);
  8281. }
  8282. }
  8283. for (const on of data.on) {
  8284. this.#groups.get(on)._setVisible(INTERNAL, true);
  8285. }
  8286. for (const off of data.off) {
  8287. this.#groups.get(off)._setVisible(INTERNAL, false);
  8288. }
  8289. this.#initialVisibility = new Map();
  8290. for (const [id, group] of this.#groups) {
  8291. this.#initialVisibility.set(id, group.visible);
  8292. }
  8293. }
  8294. #evaluateVisibilityExpression(array) {
  8295. const length = array.length;
  8296. if (length < 2) {
  8297. return true;
  8298. }
  8299. const operator = array[0];
  8300. for (let i = 1; i < length; i++) {
  8301. const element = array[i];
  8302. let state;
  8303. if (Array.isArray(element)) {
  8304. state = this.#evaluateVisibilityExpression(element);
  8305. } else if (this.#groups.has(element)) {
  8306. state = this.#groups.get(element).visible;
  8307. } else {
  8308. (0, _util.warn)(`Optional content group not found: ${element}`);
  8309. return true;
  8310. }
  8311. switch (operator) {
  8312. case "And":
  8313. if (!state) {
  8314. return false;
  8315. }
  8316. break;
  8317. case "Or":
  8318. if (state) {
  8319. return true;
  8320. }
  8321. break;
  8322. case "Not":
  8323. return !state;
  8324. default:
  8325. return true;
  8326. }
  8327. }
  8328. return operator === "And";
  8329. }
  8330. isVisible(group) {
  8331. if (this.#groups.size === 0) {
  8332. return true;
  8333. }
  8334. if (!group) {
  8335. (0, _util.warn)("Optional content group not defined.");
  8336. return true;
  8337. }
  8338. if (group.type === "OCG") {
  8339. if (!this.#groups.has(group.id)) {
  8340. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  8341. return true;
  8342. }
  8343. return this.#groups.get(group.id).visible;
  8344. } else if (group.type === "OCMD") {
  8345. if (group.expression) {
  8346. return this.#evaluateVisibilityExpression(group.expression);
  8347. }
  8348. if (!group.policy || group.policy === "AnyOn") {
  8349. for (const id of group.ids) {
  8350. if (!this.#groups.has(id)) {
  8351. (0, _util.warn)(`Optional content group not found: ${id}`);
  8352. return true;
  8353. }
  8354. if (this.#groups.get(id).visible) {
  8355. return true;
  8356. }
  8357. }
  8358. return false;
  8359. } else if (group.policy === "AllOn") {
  8360. for (const id of group.ids) {
  8361. if (!this.#groups.has(id)) {
  8362. (0, _util.warn)(`Optional content group not found: ${id}`);
  8363. return true;
  8364. }
  8365. if (!this.#groups.get(id).visible) {
  8366. return false;
  8367. }
  8368. }
  8369. return true;
  8370. } else if (group.policy === "AnyOff") {
  8371. for (const id of group.ids) {
  8372. if (!this.#groups.has(id)) {
  8373. (0, _util.warn)(`Optional content group not found: ${id}`);
  8374. return true;
  8375. }
  8376. if (!this.#groups.get(id).visible) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. } else if (group.policy === "AllOff") {
  8382. for (const id of group.ids) {
  8383. if (!this.#groups.has(id)) {
  8384. (0, _util.warn)(`Optional content group not found: ${id}`);
  8385. return true;
  8386. }
  8387. if (this.#groups.get(id).visible) {
  8388. return false;
  8389. }
  8390. }
  8391. return true;
  8392. }
  8393. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  8394. return true;
  8395. }
  8396. (0, _util.warn)(`Unknown group type ${group.type}.`);
  8397. return true;
  8398. }
  8399. setVisibility(id, visible = true) {
  8400. if (!this.#groups.has(id)) {
  8401. (0, _util.warn)(`Optional content group not found: ${id}`);
  8402. return;
  8403. }
  8404. this.#groups.get(id)._setVisible(INTERNAL, !!visible);
  8405. this.#cachedHasInitialVisibility = null;
  8406. }
  8407. get hasInitialVisibility() {
  8408. if (this.#cachedHasInitialVisibility !== null) {
  8409. return this.#cachedHasInitialVisibility;
  8410. }
  8411. for (const [id, group] of this.#groups) {
  8412. const visible = this.#initialVisibility.get(id);
  8413. if (group.visible !== visible) {
  8414. return this.#cachedHasInitialVisibility = false;
  8415. }
  8416. }
  8417. return this.#cachedHasInitialVisibility = true;
  8418. }
  8419. getOrder() {
  8420. if (!this.#groups.size) {
  8421. return null;
  8422. }
  8423. if (this.#order) {
  8424. return this.#order.slice();
  8425. }
  8426. return [...this.#groups.keys()];
  8427. }
  8428. getGroups() {
  8429. return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
  8430. }
  8431. getGroup(id) {
  8432. return this.#groups.get(id) || null;
  8433. }
  8434. }
  8435. exports.OptionalContentConfig = OptionalContentConfig;
  8436. /***/ }),
  8437. /* 19 */
  8438. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8439. Object.defineProperty(exports, "__esModule", ({
  8440. value: true
  8441. }));
  8442. exports.PDFDataTransportStream = void 0;
  8443. var _util = __w_pdfjs_require__(1);
  8444. var _display_utils = __w_pdfjs_require__(4);
  8445. class PDFDataTransportStream {
  8446. constructor(params, pdfDataRangeTransport) {
  8447. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  8448. this._queuedChunks = [];
  8449. this._progressiveDone = params.progressiveDone || false;
  8450. this._contentDispositionFilename = params.contentDispositionFilename || null;
  8451. const initialData = params.initialData;
  8452. if (initialData?.length > 0) {
  8453. const buffer = new Uint8Array(initialData).buffer;
  8454. this._queuedChunks.push(buffer);
  8455. }
  8456. this._pdfDataRangeTransport = pdfDataRangeTransport;
  8457. this._isStreamingSupported = !params.disableStream;
  8458. this._isRangeSupported = !params.disableRange;
  8459. this._contentLength = params.length;
  8460. this._fullRequestReader = null;
  8461. this._rangeReaders = [];
  8462. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  8463. this._onReceiveData({
  8464. begin,
  8465. chunk
  8466. });
  8467. });
  8468. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  8469. this._onProgress({
  8470. loaded,
  8471. total
  8472. });
  8473. });
  8474. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  8475. this._onReceiveData({
  8476. chunk
  8477. });
  8478. });
  8479. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  8480. this._onProgressiveDone();
  8481. });
  8482. this._pdfDataRangeTransport.transportReady();
  8483. }
  8484. _onReceiveData(args) {
  8485. const buffer = new Uint8Array(args.chunk).buffer;
  8486. if (args.begin === undefined) {
  8487. if (this._fullRequestReader) {
  8488. this._fullRequestReader._enqueue(buffer);
  8489. } else {
  8490. this._queuedChunks.push(buffer);
  8491. }
  8492. } else {
  8493. const found = this._rangeReaders.some(function (rangeReader) {
  8494. if (rangeReader._begin !== args.begin) {
  8495. return false;
  8496. }
  8497. rangeReader._enqueue(buffer);
  8498. return true;
  8499. });
  8500. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  8501. }
  8502. }
  8503. get _progressiveDataLength() {
  8504. return this._fullRequestReader?._loaded ?? 0;
  8505. }
  8506. _onProgress(evt) {
  8507. if (evt.total === undefined) {
  8508. const firstReader = this._rangeReaders[0];
  8509. if (firstReader?.onProgress) {
  8510. firstReader.onProgress({
  8511. loaded: evt.loaded
  8512. });
  8513. }
  8514. } else {
  8515. const fullReader = this._fullRequestReader;
  8516. if (fullReader?.onProgress) {
  8517. fullReader.onProgress({
  8518. loaded: evt.loaded,
  8519. total: evt.total
  8520. });
  8521. }
  8522. }
  8523. }
  8524. _onProgressiveDone() {
  8525. if (this._fullRequestReader) {
  8526. this._fullRequestReader.progressiveDone();
  8527. }
  8528. this._progressiveDone = true;
  8529. }
  8530. _removeRangeReader(reader) {
  8531. const i = this._rangeReaders.indexOf(reader);
  8532. if (i >= 0) {
  8533. this._rangeReaders.splice(i, 1);
  8534. }
  8535. }
  8536. getFullReader() {
  8537. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  8538. const queuedChunks = this._queuedChunks;
  8539. this._queuedChunks = null;
  8540. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  8541. }
  8542. getRangeReader(begin, end) {
  8543. if (end <= this._progressiveDataLength) {
  8544. return null;
  8545. }
  8546. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  8547. this._pdfDataRangeTransport.requestDataRange(begin, end);
  8548. this._rangeReaders.push(reader);
  8549. return reader;
  8550. }
  8551. cancelAllRequests(reason) {
  8552. if (this._fullRequestReader) {
  8553. this._fullRequestReader.cancel(reason);
  8554. }
  8555. for (const reader of this._rangeReaders.slice(0)) {
  8556. reader.cancel(reason);
  8557. }
  8558. this._pdfDataRangeTransport.abort();
  8559. }
  8560. }
  8561. exports.PDFDataTransportStream = PDFDataTransportStream;
  8562. class PDFDataTransportStreamReader {
  8563. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  8564. this._stream = stream;
  8565. this._done = progressiveDone || false;
  8566. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  8567. this._queuedChunks = queuedChunks || [];
  8568. this._loaded = 0;
  8569. for (const chunk of this._queuedChunks) {
  8570. this._loaded += chunk.byteLength;
  8571. }
  8572. this._requests = [];
  8573. this._headersReady = Promise.resolve();
  8574. stream._fullRequestReader = this;
  8575. this.onProgress = null;
  8576. }
  8577. _enqueue(chunk) {
  8578. if (this._done) {
  8579. return;
  8580. }
  8581. if (this._requests.length > 0) {
  8582. const requestCapability = this._requests.shift();
  8583. requestCapability.resolve({
  8584. value: chunk,
  8585. done: false
  8586. });
  8587. } else {
  8588. this._queuedChunks.push(chunk);
  8589. }
  8590. this._loaded += chunk.byteLength;
  8591. }
  8592. get headersReady() {
  8593. return this._headersReady;
  8594. }
  8595. get filename() {
  8596. return this._filename;
  8597. }
  8598. get isRangeSupported() {
  8599. return this._stream._isRangeSupported;
  8600. }
  8601. get isStreamingSupported() {
  8602. return this._stream._isStreamingSupported;
  8603. }
  8604. get contentLength() {
  8605. return this._stream._contentLength;
  8606. }
  8607. async read() {
  8608. if (this._queuedChunks.length > 0) {
  8609. const chunk = this._queuedChunks.shift();
  8610. return {
  8611. value: chunk,
  8612. done: false
  8613. };
  8614. }
  8615. if (this._done) {
  8616. return {
  8617. value: undefined,
  8618. done: true
  8619. };
  8620. }
  8621. const requestCapability = (0, _util.createPromiseCapability)();
  8622. this._requests.push(requestCapability);
  8623. return requestCapability.promise;
  8624. }
  8625. cancel(reason) {
  8626. this._done = true;
  8627. for (const requestCapability of this._requests) {
  8628. requestCapability.resolve({
  8629. value: undefined,
  8630. done: true
  8631. });
  8632. }
  8633. this._requests.length = 0;
  8634. }
  8635. progressiveDone() {
  8636. if (this._done) {
  8637. return;
  8638. }
  8639. this._done = true;
  8640. }
  8641. }
  8642. class PDFDataTransportStreamRangeReader {
  8643. constructor(stream, begin, end) {
  8644. this._stream = stream;
  8645. this._begin = begin;
  8646. this._end = end;
  8647. this._queuedChunk = null;
  8648. this._requests = [];
  8649. this._done = false;
  8650. this.onProgress = null;
  8651. }
  8652. _enqueue(chunk) {
  8653. if (this._done) {
  8654. return;
  8655. }
  8656. if (this._requests.length === 0) {
  8657. this._queuedChunk = chunk;
  8658. } else {
  8659. const requestsCapability = this._requests.shift();
  8660. requestsCapability.resolve({
  8661. value: chunk,
  8662. done: false
  8663. });
  8664. for (const requestCapability of this._requests) {
  8665. requestCapability.resolve({
  8666. value: undefined,
  8667. done: true
  8668. });
  8669. }
  8670. this._requests.length = 0;
  8671. }
  8672. this._done = true;
  8673. this._stream._removeRangeReader(this);
  8674. }
  8675. get isStreamingSupported() {
  8676. return false;
  8677. }
  8678. async read() {
  8679. if (this._queuedChunk) {
  8680. const chunk = this._queuedChunk;
  8681. this._queuedChunk = null;
  8682. return {
  8683. value: chunk,
  8684. done: false
  8685. };
  8686. }
  8687. if (this._done) {
  8688. return {
  8689. value: undefined,
  8690. done: true
  8691. };
  8692. }
  8693. const requestCapability = (0, _util.createPromiseCapability)();
  8694. this._requests.push(requestCapability);
  8695. return requestCapability.promise;
  8696. }
  8697. cancel(reason) {
  8698. this._done = true;
  8699. for (const requestCapability of this._requests) {
  8700. requestCapability.resolve({
  8701. value: undefined,
  8702. done: true
  8703. });
  8704. }
  8705. this._requests.length = 0;
  8706. this._stream._removeRangeReader(this);
  8707. }
  8708. }
  8709. /***/ }),
  8710. /* 20 */
  8711. /***/ ((__unused_webpack_module, exports) => {
  8712. Object.defineProperty(exports, "__esModule", ({
  8713. value: true
  8714. }));
  8715. exports.XfaText = void 0;
  8716. class XfaText {
  8717. static textContent(xfa) {
  8718. const items = [];
  8719. const output = {
  8720. items,
  8721. styles: Object.create(null)
  8722. };
  8723. function walk(node) {
  8724. if (!node) {
  8725. return;
  8726. }
  8727. let str = null;
  8728. const name = node.name;
  8729. if (name === "#text") {
  8730. str = node.value;
  8731. } else if (!XfaText.shouldBuildText(name)) {
  8732. return;
  8733. } else if (node?.attributes?.textContent) {
  8734. str = node.attributes.textContent;
  8735. } else if (node.value) {
  8736. str = node.value;
  8737. }
  8738. if (str !== null) {
  8739. items.push({
  8740. str
  8741. });
  8742. }
  8743. if (!node.children) {
  8744. return;
  8745. }
  8746. for (const child of node.children) {
  8747. walk(child);
  8748. }
  8749. }
  8750. walk(xfa);
  8751. return output;
  8752. }
  8753. static shouldBuildText(name) {
  8754. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  8755. }
  8756. }
  8757. exports.XfaText = XfaText;
  8758. /***/ }),
  8759. /* 21 */
  8760. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8761. Object.defineProperty(exports, "__esModule", ({
  8762. value: true
  8763. }));
  8764. exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
  8765. var _base_factory = __w_pdfjs_require__(5);
  8766. ;
  8767. const fetchData = function (url) {
  8768. return new Promise((resolve, reject) => {
  8769. const fs = require("fs");
  8770. fs.readFile(url, (error, data) => {
  8771. if (error || !data) {
  8772. reject(new Error(error));
  8773. return;
  8774. }
  8775. resolve(new Uint8Array(data));
  8776. });
  8777. });
  8778. };
  8779. class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
  8780. _createCanvas(width, height) {
  8781. const Canvas = require("canvas");
  8782. return Canvas.createCanvas(width, height);
  8783. }
  8784. }
  8785. exports.NodeCanvasFactory = NodeCanvasFactory;
  8786. class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  8787. _fetchData(url, compressionType) {
  8788. return fetchData(url).then(data => {
  8789. return {
  8790. cMapData: data,
  8791. compressionType
  8792. };
  8793. });
  8794. }
  8795. }
  8796. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  8797. class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  8798. _fetchData(url) {
  8799. return fetchData(url);
  8800. }
  8801. }
  8802. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  8803. /***/ }),
  8804. /* 22 */
  8805. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8806. Object.defineProperty(exports, "__esModule", ({
  8807. value: true
  8808. }));
  8809. exports.AnnotationEditorLayer = void 0;
  8810. var _util = __w_pdfjs_require__(1);
  8811. var _tools = __w_pdfjs_require__(9);
  8812. var _display_utils = __w_pdfjs_require__(4);
  8813. var _freetext = __w_pdfjs_require__(23);
  8814. var _ink = __w_pdfjs_require__(24);
  8815. class AnnotationEditorLayer {
  8816. #allowClick = false;
  8817. #boundPointerup = this.pointerup.bind(this);
  8818. #boundPointerdown = this.pointerdown.bind(this);
  8819. #editors = new Map();
  8820. #isCleaningUp = false;
  8821. #textLayerMap = new WeakMap();
  8822. #textNodes = new Map();
  8823. #uiManager;
  8824. #waitingEditors = new Set();
  8825. static _initialized = false;
  8826. constructor(options) {
  8827. if (!AnnotationEditorLayer._initialized) {
  8828. AnnotationEditorLayer._initialized = true;
  8829. _freetext.FreeTextEditor.initialize(options.l10n);
  8830. _ink.InkEditor.initialize(options.l10n);
  8831. options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
  8832. }
  8833. this.#uiManager = options.uiManager;
  8834. this.annotationStorage = options.annotationStorage;
  8835. this.pageIndex = options.pageIndex;
  8836. this.div = options.div;
  8837. this.#uiManager.addLayer(this);
  8838. }
  8839. get textLayerElements() {
  8840. const textLayer = this.div.parentNode.getElementsByClassName("textLayer").item(0);
  8841. if (!textLayer) {
  8842. return (0, _util.shadow)(this, "textLayerElements", null);
  8843. }
  8844. let textChildren = this.#textLayerMap.get(textLayer);
  8845. if (textChildren) {
  8846. return textChildren;
  8847. }
  8848. textChildren = textLayer.querySelectorAll(`span[role="presentation"]`);
  8849. if (textChildren.length === 0) {
  8850. return (0, _util.shadow)(this, "textLayerElements", null);
  8851. }
  8852. textChildren = Array.from(textChildren);
  8853. textChildren.sort(AnnotationEditorLayer.#compareElementPositions);
  8854. this.#textLayerMap.set(textLayer, textChildren);
  8855. return textChildren;
  8856. }
  8857. get #hasTextLayer() {
  8858. return !!this.div.parentNode.querySelector(".textLayer .endOfContent");
  8859. }
  8860. updateToolbar(mode) {
  8861. this.#uiManager.updateToolbar(mode);
  8862. }
  8863. updateMode(mode = this.#uiManager.getMode()) {
  8864. this.#cleanup();
  8865. if (mode === _util.AnnotationEditorType.INK) {
  8866. this.addInkEditorIfNeeded(false);
  8867. this.disableClick();
  8868. } else {
  8869. this.enableClick();
  8870. }
  8871. this.#uiManager.unselectAll();
  8872. }
  8873. addInkEditorIfNeeded(isCommitting) {
  8874. if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
  8875. return;
  8876. }
  8877. if (!isCommitting) {
  8878. for (const editor of this.#editors.values()) {
  8879. if (editor.isEmpty()) {
  8880. editor.setInBackground();
  8881. return;
  8882. }
  8883. }
  8884. }
  8885. const editor = this.#createAndAddNewEditor({
  8886. offsetX: 0,
  8887. offsetY: 0
  8888. });
  8889. editor.setInBackground();
  8890. }
  8891. setEditingState(isEditing) {
  8892. this.#uiManager.setEditingState(isEditing);
  8893. }
  8894. addCommands(params) {
  8895. this.#uiManager.addCommands(params);
  8896. }
  8897. enable() {
  8898. this.div.style.pointerEvents = "auto";
  8899. for (const editor of this.#editors.values()) {
  8900. editor.enableEditing();
  8901. }
  8902. }
  8903. disable() {
  8904. this.div.style.pointerEvents = "none";
  8905. for (const editor of this.#editors.values()) {
  8906. editor.disableEditing();
  8907. }
  8908. }
  8909. setActiveEditor(editor) {
  8910. const currentActive = this.#uiManager.getActive();
  8911. if (currentActive === editor) {
  8912. return;
  8913. }
  8914. this.#uiManager.setActiveEditor(editor);
  8915. }
  8916. enableClick() {
  8917. this.div.addEventListener("pointerdown", this.#boundPointerdown);
  8918. this.div.addEventListener("pointerup", this.#boundPointerup);
  8919. }
  8920. disableClick() {
  8921. this.div.removeEventListener("pointerdown", this.#boundPointerdown);
  8922. this.div.removeEventListener("pointerup", this.#boundPointerup);
  8923. }
  8924. attach(editor) {
  8925. this.#editors.set(editor.id, editor);
  8926. }
  8927. detach(editor) {
  8928. this.#editors.delete(editor.id);
  8929. this.removePointerInTextLayer(editor);
  8930. }
  8931. remove(editor) {
  8932. this.#uiManager.removeEditor(editor);
  8933. this.detach(editor);
  8934. this.annotationStorage.removeKey(editor.id);
  8935. editor.div.style.display = "none";
  8936. setTimeout(() => {
  8937. editor.div.style.display = "";
  8938. editor.div.remove();
  8939. editor.isAttachedToDOM = false;
  8940. if (document.activeElement === document.body) {
  8941. this.#uiManager.focusMainContainer();
  8942. }
  8943. }, 0);
  8944. if (!this.#isCleaningUp) {
  8945. this.addInkEditorIfNeeded(false);
  8946. }
  8947. }
  8948. #changeParent(editor) {
  8949. if (editor.parent === this) {
  8950. return;
  8951. }
  8952. this.attach(editor);
  8953. editor.pageIndex = this.pageIndex;
  8954. editor.parent?.detach(editor);
  8955. editor.parent = this;
  8956. if (editor.div && editor.isAttachedToDOM) {
  8957. editor.div.remove();
  8958. this.div.append(editor.div);
  8959. }
  8960. }
  8961. static #compareElementPositions(e1, e2) {
  8962. const rect1 = e1.getBoundingClientRect();
  8963. const rect2 = e2.getBoundingClientRect();
  8964. if (rect1.y + rect1.height <= rect2.y) {
  8965. return -1;
  8966. }
  8967. if (rect2.y + rect2.height <= rect1.y) {
  8968. return +1;
  8969. }
  8970. const centerX1 = rect1.x + rect1.width / 2;
  8971. const centerX2 = rect2.x + rect2.width / 2;
  8972. return centerX1 - centerX2;
  8973. }
  8974. onTextLayerRendered() {
  8975. this.#textNodes.clear();
  8976. for (const editor of this.#waitingEditors) {
  8977. if (editor.isAttachedToDOM) {
  8978. this.addPointerInTextLayer(editor);
  8979. }
  8980. }
  8981. this.#waitingEditors.clear();
  8982. }
  8983. removePointerInTextLayer(editor) {
  8984. if (!this.#hasTextLayer) {
  8985. this.#waitingEditors.delete(editor);
  8986. return;
  8987. }
  8988. const {
  8989. id
  8990. } = editor;
  8991. const node = this.#textNodes.get(id);
  8992. if (!node) {
  8993. return;
  8994. }
  8995. this.#textNodes.delete(id);
  8996. let owns = node.getAttribute("aria-owns");
  8997. if (owns?.includes(id)) {
  8998. owns = owns.split(" ").filter(x => x !== id).join(" ");
  8999. if (owns) {
  9000. node.setAttribute("aria-owns", owns);
  9001. } else {
  9002. node.removeAttribute("aria-owns");
  9003. node.setAttribute("role", "presentation");
  9004. }
  9005. }
  9006. }
  9007. addPointerInTextLayer(editor) {
  9008. if (!this.#hasTextLayer) {
  9009. this.#waitingEditors.add(editor);
  9010. return;
  9011. }
  9012. this.removePointerInTextLayer(editor);
  9013. const children = this.textLayerElements;
  9014. if (!children) {
  9015. return;
  9016. }
  9017. const {
  9018. contentDiv
  9019. } = editor;
  9020. const id = editor.getIdForTextLayer();
  9021. const index = (0, _display_utils.binarySearchFirstItem)(children, node => AnnotationEditorLayer.#compareElementPositions(contentDiv, node) < 0);
  9022. const node = children[Math.max(0, index - 1)];
  9023. const owns = node.getAttribute("aria-owns");
  9024. if (!owns?.includes(id)) {
  9025. node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id);
  9026. }
  9027. node.removeAttribute("role");
  9028. this.#textNodes.set(id, node);
  9029. }
  9030. moveDivInDOM(editor) {
  9031. this.addPointerInTextLayer(editor);
  9032. const {
  9033. div,
  9034. contentDiv
  9035. } = editor;
  9036. if (!this.div.hasChildNodes()) {
  9037. this.div.append(div);
  9038. return;
  9039. }
  9040. const children = Array.from(this.div.childNodes).filter(node => node !== div);
  9041. if (children.length === 0) {
  9042. return;
  9043. }
  9044. const index = (0, _display_utils.binarySearchFirstItem)(children, node => AnnotationEditorLayer.#compareElementPositions(contentDiv, node) < 0);
  9045. if (index === 0) {
  9046. children[0].before(div);
  9047. } else {
  9048. children[index - 1].after(div);
  9049. }
  9050. }
  9051. add(editor) {
  9052. this.#changeParent(editor);
  9053. this.addToAnnotationStorage(editor);
  9054. this.#uiManager.addEditor(editor);
  9055. this.attach(editor);
  9056. if (!editor.isAttachedToDOM) {
  9057. const div = editor.render();
  9058. this.div.append(div);
  9059. editor.isAttachedToDOM = true;
  9060. }
  9061. this.moveDivInDOM(editor);
  9062. editor.onceAdded();
  9063. }
  9064. addToAnnotationStorage(editor) {
  9065. if (!editor.isEmpty() && !this.annotationStorage.has(editor.id)) {
  9066. this.annotationStorage.setValue(editor.id, editor);
  9067. }
  9068. }
  9069. addOrRebuild(editor) {
  9070. if (editor.needsToBeRebuilt()) {
  9071. editor.rebuild();
  9072. } else {
  9073. this.add(editor);
  9074. }
  9075. }
  9076. addANewEditor(editor) {
  9077. const cmd = () => {
  9078. this.addOrRebuild(editor);
  9079. };
  9080. const undo = () => {
  9081. editor.remove();
  9082. };
  9083. this.addCommands({
  9084. cmd,
  9085. undo,
  9086. mustExec: true
  9087. });
  9088. }
  9089. addUndoableEditor(editor) {
  9090. const cmd = () => {
  9091. this.addOrRebuild(editor);
  9092. };
  9093. const undo = () => {
  9094. editor.remove();
  9095. };
  9096. this.addCommands({
  9097. cmd,
  9098. undo,
  9099. mustExec: false
  9100. });
  9101. }
  9102. getNextId() {
  9103. return this.#uiManager.getId();
  9104. }
  9105. #createNewEditor(params) {
  9106. switch (this.#uiManager.getMode()) {
  9107. case _util.AnnotationEditorType.FREETEXT:
  9108. return new _freetext.FreeTextEditor(params);
  9109. case _util.AnnotationEditorType.INK:
  9110. return new _ink.InkEditor(params);
  9111. }
  9112. return null;
  9113. }
  9114. deserialize(data) {
  9115. switch (data.annotationType) {
  9116. case _util.AnnotationEditorType.FREETEXT:
  9117. return _freetext.FreeTextEditor.deserialize(data, this);
  9118. case _util.AnnotationEditorType.INK:
  9119. return _ink.InkEditor.deserialize(data, this);
  9120. }
  9121. return null;
  9122. }
  9123. #createAndAddNewEditor(event) {
  9124. const id = this.getNextId();
  9125. const editor = this.#createNewEditor({
  9126. parent: this,
  9127. id,
  9128. x: event.offsetX,
  9129. y: event.offsetY
  9130. });
  9131. if (editor) {
  9132. this.add(editor);
  9133. }
  9134. return editor;
  9135. }
  9136. setSelected(editor) {
  9137. this.#uiManager.setSelected(editor);
  9138. }
  9139. toggleSelected(editor) {
  9140. this.#uiManager.toggleSelected(editor);
  9141. }
  9142. isSelected(editor) {
  9143. return this.#uiManager.isSelected(editor);
  9144. }
  9145. unselect(editor) {
  9146. this.#uiManager.unselect(editor);
  9147. }
  9148. pointerup(event) {
  9149. const isMac = _tools.KeyboardManager.platform.isMac;
  9150. if (event.button !== 0 || event.ctrlKey && isMac) {
  9151. return;
  9152. }
  9153. if (event.target !== this.div) {
  9154. return;
  9155. }
  9156. if (!this.#allowClick) {
  9157. this.#allowClick = true;
  9158. return;
  9159. }
  9160. this.#createAndAddNewEditor(event);
  9161. }
  9162. pointerdown(event) {
  9163. const isMac = _tools.KeyboardManager.platform.isMac;
  9164. if (event.button !== 0 || event.ctrlKey && isMac) {
  9165. return;
  9166. }
  9167. if (event.target !== this.div) {
  9168. return;
  9169. }
  9170. const editor = this.#uiManager.getActive();
  9171. this.#allowClick = !editor || editor.isEmpty();
  9172. }
  9173. drop(event) {
  9174. const id = event.dataTransfer.getData("text/plain");
  9175. const editor = this.#uiManager.getEditor(id);
  9176. if (!editor) {
  9177. return;
  9178. }
  9179. event.preventDefault();
  9180. event.dataTransfer.dropEffect = "move";
  9181. this.#changeParent(editor);
  9182. const rect = this.div.getBoundingClientRect();
  9183. const endX = event.clientX - rect.x;
  9184. const endY = event.clientY - rect.y;
  9185. editor.translate(endX - editor.startX, endY - editor.startY);
  9186. this.moveDivInDOM(editor);
  9187. editor.div.focus();
  9188. }
  9189. dragover(event) {
  9190. event.preventDefault();
  9191. }
  9192. destroy() {
  9193. if (this.#uiManager.getActive()?.parent === this) {
  9194. this.#uiManager.setActiveEditor(null);
  9195. }
  9196. for (const editor of this.#editors.values()) {
  9197. this.removePointerInTextLayer(editor);
  9198. editor.isAttachedToDOM = false;
  9199. editor.div.remove();
  9200. editor.parent = null;
  9201. }
  9202. this.#textNodes.clear();
  9203. this.div = null;
  9204. this.#editors.clear();
  9205. this.#waitingEditors.clear();
  9206. this.#uiManager.removeLayer(this);
  9207. }
  9208. #cleanup() {
  9209. this.#isCleaningUp = true;
  9210. for (const editor of this.#editors.values()) {
  9211. if (editor.isEmpty()) {
  9212. editor.remove();
  9213. }
  9214. }
  9215. this.#isCleaningUp = false;
  9216. }
  9217. render(parameters) {
  9218. this.viewport = parameters.viewport;
  9219. (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
  9220. this.setDimensions();
  9221. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  9222. this.add(editor);
  9223. }
  9224. this.updateMode();
  9225. }
  9226. update(parameters) {
  9227. this.viewport = parameters.viewport;
  9228. this.setDimensions();
  9229. this.updateMode();
  9230. }
  9231. get scaleFactor() {
  9232. return this.viewport.scale;
  9233. }
  9234. get pageDimensions() {
  9235. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  9236. const width = pageURx - pageLLx;
  9237. const height = pageURy - pageLLy;
  9238. return [width, height];
  9239. }
  9240. get viewportBaseDimensions() {
  9241. const {
  9242. width,
  9243. height,
  9244. rotation
  9245. } = this.viewport;
  9246. return rotation % 180 === 0 ? [width, height] : [height, width];
  9247. }
  9248. setDimensions() {
  9249. const {
  9250. width,
  9251. height,
  9252. rotation
  9253. } = this.viewport;
  9254. const flipOrientation = rotation % 180 !== 0,
  9255. widthStr = Math.floor(width) + "px",
  9256. heightStr = Math.floor(height) + "px";
  9257. this.div.style.width = flipOrientation ? heightStr : widthStr;
  9258. this.div.style.height = flipOrientation ? widthStr : heightStr;
  9259. this.div.setAttribute("data-main-rotation", rotation);
  9260. }
  9261. }
  9262. exports.AnnotationEditorLayer = AnnotationEditorLayer;
  9263. /***/ }),
  9264. /* 23 */
  9265. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9266. Object.defineProperty(exports, "__esModule", ({
  9267. value: true
  9268. }));
  9269. exports.FreeTextEditor = void 0;
  9270. var _util = __w_pdfjs_require__(1);
  9271. var _tools = __w_pdfjs_require__(9);
  9272. var _editor = __w_pdfjs_require__(8);
  9273. class FreeTextEditor extends _editor.AnnotationEditor {
  9274. #boundEditorDivBlur = this.editorDivBlur.bind(this);
  9275. #boundEditorDivFocus = this.editorDivFocus.bind(this);
  9276. #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
  9277. #color;
  9278. #content = "";
  9279. #contentHTML = "";
  9280. #hasAlreadyBeenCommitted = false;
  9281. #fontSize;
  9282. static _freeTextDefaultContent = "";
  9283. static _l10nPromise;
  9284. static _internalPadding = 0;
  9285. static _defaultColor = null;
  9286. static _defaultFontSize = 10;
  9287. static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
  9288. constructor(params) {
  9289. super({ ...params,
  9290. name: "freeTextEditor"
  9291. });
  9292. this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  9293. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  9294. }
  9295. static initialize(l10n) {
  9296. this._l10nPromise = new Map(["free_text_default_content", "editor_free_text_aria_label"].map(str => [str, l10n.get(str)]));
  9297. const style = getComputedStyle(document.documentElement);
  9298. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  9299. }
  9300. static updateDefaultParams(type, value) {
  9301. switch (type) {
  9302. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  9303. FreeTextEditor._defaultFontSize = value;
  9304. break;
  9305. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  9306. FreeTextEditor._defaultColor = value;
  9307. break;
  9308. }
  9309. }
  9310. updateParams(type, value) {
  9311. switch (type) {
  9312. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  9313. this.#updateFontSize(value);
  9314. break;
  9315. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  9316. this.#updateColor(value);
  9317. break;
  9318. }
  9319. }
  9320. static get defaultPropertiesToUpdate() {
  9321. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
  9322. }
  9323. get propertiesToUpdate() {
  9324. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  9325. }
  9326. #updateFontSize(fontSize) {
  9327. const setFontsize = size => {
  9328. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  9329. this.translate(0, -(size - this.#fontSize) * this.parent.scaleFactor);
  9330. this.#fontSize = size;
  9331. this.#setEditorDimensions();
  9332. };
  9333. const savedFontsize = this.#fontSize;
  9334. this.parent.addCommands({
  9335. cmd: () => {
  9336. setFontsize(fontSize);
  9337. },
  9338. undo: () => {
  9339. setFontsize(savedFontsize);
  9340. },
  9341. mustExec: true,
  9342. type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
  9343. overwriteIfSameType: true,
  9344. keepUndo: true
  9345. });
  9346. }
  9347. #updateColor(color) {
  9348. const savedColor = this.#color;
  9349. this.parent.addCommands({
  9350. cmd: () => {
  9351. this.#color = color;
  9352. this.editorDiv.style.color = color;
  9353. },
  9354. undo: () => {
  9355. this.#color = savedColor;
  9356. this.editorDiv.style.color = savedColor;
  9357. },
  9358. mustExec: true,
  9359. type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
  9360. overwriteIfSameType: true,
  9361. keepUndo: true
  9362. });
  9363. }
  9364. getInitialTranslation() {
  9365. return [-FreeTextEditor._internalPadding * this.parent.scaleFactor, -(FreeTextEditor._internalPadding + this.#fontSize) * this.parent.scaleFactor];
  9366. }
  9367. rebuild() {
  9368. super.rebuild();
  9369. if (this.div === null) {
  9370. return;
  9371. }
  9372. if (!this.isAttachedToDOM) {
  9373. this.parent.add(this);
  9374. }
  9375. }
  9376. enableEditMode() {
  9377. if (this.isInEditMode()) {
  9378. return;
  9379. }
  9380. this.parent.setEditingState(false);
  9381. this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
  9382. super.enableEditMode();
  9383. this.overlayDiv.classList.remove("enabled");
  9384. this.editorDiv.contentEditable = true;
  9385. this.div.draggable = false;
  9386. this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
  9387. this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
  9388. this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
  9389. }
  9390. disableEditMode() {
  9391. if (!this.isInEditMode()) {
  9392. return;
  9393. }
  9394. this.parent.setEditingState(true);
  9395. super.disableEditMode();
  9396. this.overlayDiv.classList.add("enabled");
  9397. this.editorDiv.contentEditable = false;
  9398. this.div.draggable = true;
  9399. this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
  9400. this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
  9401. this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
  9402. this.div.focus();
  9403. this.isEditing = false;
  9404. }
  9405. focusin(event) {
  9406. super.focusin(event);
  9407. if (event.target !== this.editorDiv) {
  9408. this.editorDiv.focus();
  9409. }
  9410. }
  9411. onceAdded() {
  9412. if (this.width) {
  9413. return;
  9414. }
  9415. this.enableEditMode();
  9416. this.editorDiv.focus();
  9417. }
  9418. isEmpty() {
  9419. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  9420. }
  9421. remove() {
  9422. this.isEditing = false;
  9423. this.parent.setEditingState(true);
  9424. super.remove();
  9425. }
  9426. #extractText() {
  9427. const divs = this.editorDiv.getElementsByTagName("div");
  9428. if (divs.length === 0) {
  9429. return this.editorDiv.innerText;
  9430. }
  9431. const buffer = [];
  9432. for (let i = 0, ii = divs.length; i < ii; i++) {
  9433. const div = divs[i];
  9434. const first = div.firstChild;
  9435. if (first?.nodeName === "#text") {
  9436. buffer.push(first.data);
  9437. } else {
  9438. buffer.push("");
  9439. }
  9440. }
  9441. return buffer.join("\n");
  9442. }
  9443. #setEditorDimensions() {
  9444. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9445. const rect = this.div.getBoundingClientRect();
  9446. this.width = rect.width / parentWidth;
  9447. this.height = rect.height / parentHeight;
  9448. }
  9449. commit() {
  9450. super.commit();
  9451. if (!this.#hasAlreadyBeenCommitted) {
  9452. this.#hasAlreadyBeenCommitted = true;
  9453. this.parent.addUndoableEditor(this);
  9454. }
  9455. this.disableEditMode();
  9456. this.#contentHTML = this.editorDiv.innerHTML;
  9457. this.#content = this.#extractText().trimEnd();
  9458. this.#setEditorDimensions();
  9459. }
  9460. shouldGetKeyboardEvents() {
  9461. return this.isInEditMode();
  9462. }
  9463. dblclick(event) {
  9464. this.enableEditMode();
  9465. this.editorDiv.focus();
  9466. }
  9467. keydown(event) {
  9468. if (event.target === this.div && event.key === "Enter") {
  9469. this.enableEditMode();
  9470. this.editorDiv.focus();
  9471. }
  9472. }
  9473. editorDivKeydown(event) {
  9474. FreeTextEditor._keyboardManager.exec(this, event);
  9475. }
  9476. editorDivFocus(event) {
  9477. this.isEditing = true;
  9478. }
  9479. editorDivBlur(event) {
  9480. this.isEditing = false;
  9481. }
  9482. disableEditing() {
  9483. this.editorDiv.setAttribute("role", "comment");
  9484. this.editorDiv.removeAttribute("aria-multiline");
  9485. }
  9486. enableEditing() {
  9487. this.editorDiv.setAttribute("role", "textbox");
  9488. this.editorDiv.setAttribute("aria-multiline", true);
  9489. }
  9490. getIdForTextLayer() {
  9491. return this.editorDiv.id;
  9492. }
  9493. render() {
  9494. if (this.div) {
  9495. return this.div;
  9496. }
  9497. let baseX, baseY;
  9498. if (this.width) {
  9499. baseX = this.x;
  9500. baseY = this.y;
  9501. }
  9502. super.render();
  9503. this.editorDiv = document.createElement("div");
  9504. this.editorDiv.className = "internal";
  9505. this.editorDiv.setAttribute("id", `${this.id}-editor`);
  9506. this.enableEditing();
  9507. FreeTextEditor._l10nPromise.get("editor_free_text_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
  9508. FreeTextEditor._l10nPromise.get("free_text_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
  9509. this.editorDiv.contentEditable = true;
  9510. const {
  9511. style
  9512. } = this.editorDiv;
  9513. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  9514. style.color = this.#color;
  9515. this.div.append(this.editorDiv);
  9516. this.overlayDiv = document.createElement("div");
  9517. this.overlayDiv.classList.add("overlay", "enabled");
  9518. this.div.append(this.overlayDiv);
  9519. (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
  9520. if (this.width) {
  9521. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9522. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  9523. this.editorDiv.innerHTML = this.#contentHTML;
  9524. this.div.draggable = true;
  9525. this.editorDiv.contentEditable = false;
  9526. } else {
  9527. this.div.draggable = false;
  9528. this.editorDiv.contentEditable = true;
  9529. }
  9530. return this.div;
  9531. }
  9532. get contentDiv() {
  9533. return this.editorDiv;
  9534. }
  9535. static deserialize(data, parent) {
  9536. const editor = super.deserialize(data, parent);
  9537. editor.#fontSize = data.fontSize;
  9538. editor.#color = _util.Util.makeHexColor(...data.color);
  9539. editor.#content = data.value;
  9540. editor.#contentHTML = data.value.split("\n").map(line => `<div>${line}</div>`).join("");
  9541. return editor;
  9542. }
  9543. serialize() {
  9544. if (this.isEmpty()) {
  9545. return null;
  9546. }
  9547. const padding = FreeTextEditor._internalPadding * this.parent.scaleFactor;
  9548. const rect = this.getRect(padding, padding);
  9549. const color = _editor.AnnotationEditor._colorManager.convert(getComputedStyle(this.editorDiv).color);
  9550. return {
  9551. annotationType: _util.AnnotationEditorType.FREETEXT,
  9552. color,
  9553. fontSize: this.#fontSize,
  9554. value: this.#content,
  9555. pageIndex: this.parent.pageIndex,
  9556. rect,
  9557. rotation: this.rotation
  9558. };
  9559. }
  9560. }
  9561. exports.FreeTextEditor = FreeTextEditor;
  9562. /***/ }),
  9563. /* 24 */
  9564. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9565. Object.defineProperty(exports, "__esModule", ({
  9566. value: true
  9567. }));
  9568. exports.InkEditor = void 0;
  9569. Object.defineProperty(exports, "fitCurve", ({
  9570. enumerable: true,
  9571. get: function () {
  9572. return _pdfjsFitCurve.fitCurve;
  9573. }
  9574. }));
  9575. var _util = __w_pdfjs_require__(1);
  9576. var _editor = __w_pdfjs_require__(8);
  9577. var _pdfjsFitCurve = __w_pdfjs_require__(25);
  9578. var _tools = __w_pdfjs_require__(9);
  9579. const RESIZER_SIZE = 16;
  9580. class InkEditor extends _editor.AnnotationEditor {
  9581. #aspectRatio = 0;
  9582. #baseHeight = 0;
  9583. #baseWidth = 0;
  9584. #boundCanvasPointermove = this.canvasPointermove.bind(this);
  9585. #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
  9586. #boundCanvasPointerup = this.canvasPointerup.bind(this);
  9587. #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
  9588. #disableEditing = false;
  9589. #isCanvasInitialized = false;
  9590. #lastPoint = null;
  9591. #observer = null;
  9592. #realWidth = 0;
  9593. #realHeight = 0;
  9594. #requestFrameCallback = null;
  9595. static _defaultColor = null;
  9596. static _defaultOpacity = 1;
  9597. static _defaultThickness = 1;
  9598. static _l10nPromise;
  9599. constructor(params) {
  9600. super({ ...params,
  9601. name: "inkEditor"
  9602. });
  9603. this.color = params.color || null;
  9604. this.thickness = params.thickness || null;
  9605. this.opacity = params.opacity || null;
  9606. this.paths = [];
  9607. this.bezierPath2D = [];
  9608. this.currentPath = [];
  9609. this.scaleFactor = 1;
  9610. this.translationX = this.translationY = 0;
  9611. this.x = 0;
  9612. this.y = 0;
  9613. }
  9614. static initialize(l10n) {
  9615. this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink_aria_label"].map(str => [str, l10n.get(str)]));
  9616. }
  9617. static updateDefaultParams(type, value) {
  9618. switch (type) {
  9619. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9620. InkEditor._defaultThickness = value;
  9621. break;
  9622. case _util.AnnotationEditorParamsType.INK_COLOR:
  9623. InkEditor._defaultColor = value;
  9624. break;
  9625. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9626. InkEditor._defaultOpacity = value / 100;
  9627. break;
  9628. }
  9629. }
  9630. updateParams(type, value) {
  9631. switch (type) {
  9632. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9633. this.#updateThickness(value);
  9634. break;
  9635. case _util.AnnotationEditorParamsType.INK_COLOR:
  9636. this.#updateColor(value);
  9637. break;
  9638. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9639. this.#updateOpacity(value);
  9640. break;
  9641. }
  9642. }
  9643. static get defaultPropertiesToUpdate() {
  9644. 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)]];
  9645. }
  9646. get propertiesToUpdate() {
  9647. 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))]];
  9648. }
  9649. #updateThickness(thickness) {
  9650. const savedThickness = this.thickness;
  9651. this.parent.addCommands({
  9652. cmd: () => {
  9653. this.thickness = thickness;
  9654. this.#fitToContent();
  9655. },
  9656. undo: () => {
  9657. this.thickness = savedThickness;
  9658. this.#fitToContent();
  9659. },
  9660. mustExec: true,
  9661. type: _util.AnnotationEditorParamsType.INK_THICKNESS,
  9662. overwriteIfSameType: true,
  9663. keepUndo: true
  9664. });
  9665. }
  9666. #updateColor(color) {
  9667. const savedColor = this.color;
  9668. this.parent.addCommands({
  9669. cmd: () => {
  9670. this.color = color;
  9671. this.#redraw();
  9672. },
  9673. undo: () => {
  9674. this.color = savedColor;
  9675. this.#redraw();
  9676. },
  9677. mustExec: true,
  9678. type: _util.AnnotationEditorParamsType.INK_COLOR,
  9679. overwriteIfSameType: true,
  9680. keepUndo: true
  9681. });
  9682. }
  9683. #updateOpacity(opacity) {
  9684. opacity /= 100;
  9685. const savedOpacity = this.opacity;
  9686. this.parent.addCommands({
  9687. cmd: () => {
  9688. this.opacity = opacity;
  9689. this.#redraw();
  9690. },
  9691. undo: () => {
  9692. this.opacity = savedOpacity;
  9693. this.#redraw();
  9694. },
  9695. mustExec: true,
  9696. type: _util.AnnotationEditorParamsType.INK_OPACITY,
  9697. overwriteIfSameType: true,
  9698. keepUndo: true
  9699. });
  9700. }
  9701. rebuild() {
  9702. super.rebuild();
  9703. if (this.div === null) {
  9704. return;
  9705. }
  9706. if (!this.canvas) {
  9707. this.#createCanvas();
  9708. this.#createObserver();
  9709. }
  9710. if (!this.isAttachedToDOM) {
  9711. this.parent.add(this);
  9712. this.#setCanvasDims();
  9713. }
  9714. this.#fitToContent();
  9715. }
  9716. remove() {
  9717. if (this.canvas === null) {
  9718. return;
  9719. }
  9720. if (!this.isEmpty()) {
  9721. this.commit();
  9722. }
  9723. this.canvas.width = this.canvas.height = 0;
  9724. this.canvas.remove();
  9725. this.canvas = null;
  9726. this.#observer.disconnect();
  9727. this.#observer = null;
  9728. super.remove();
  9729. }
  9730. enableEditMode() {
  9731. if (this.#disableEditing || this.canvas === null) {
  9732. return;
  9733. }
  9734. super.enableEditMode();
  9735. this.div.draggable = false;
  9736. this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
  9737. this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
  9738. }
  9739. disableEditMode() {
  9740. if (!this.isInEditMode() || this.canvas === null) {
  9741. return;
  9742. }
  9743. super.disableEditMode();
  9744. this.div.draggable = !this.isEmpty();
  9745. this.div.classList.remove("editing");
  9746. this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
  9747. this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
  9748. }
  9749. onceAdded() {
  9750. this.div.draggable = !this.isEmpty();
  9751. }
  9752. isEmpty() {
  9753. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  9754. }
  9755. #getInitialBBox() {
  9756. const {
  9757. width,
  9758. height,
  9759. rotation
  9760. } = this.parent.viewport;
  9761. switch (rotation) {
  9762. case 90:
  9763. return [0, width, width, height];
  9764. case 180:
  9765. return [width, height, width, height];
  9766. case 270:
  9767. return [height, 0, width, height];
  9768. default:
  9769. return [0, 0, width, height];
  9770. }
  9771. }
  9772. #setStroke() {
  9773. this.ctx.lineWidth = this.thickness * this.parent.scaleFactor / this.scaleFactor;
  9774. this.ctx.lineCap = "round";
  9775. this.ctx.lineJoin = "round";
  9776. this.ctx.miterLimit = 10;
  9777. this.ctx.strokeStyle = `${this.color}${(0, _tools.opacityToHex)(this.opacity)}`;
  9778. }
  9779. #startDrawing(x, y) {
  9780. this.isEditing = true;
  9781. if (!this.#isCanvasInitialized) {
  9782. this.#isCanvasInitialized = true;
  9783. this.#setCanvasDims();
  9784. this.thickness ||= InkEditor._defaultThickness;
  9785. this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  9786. this.opacity ??= InkEditor._defaultOpacity;
  9787. }
  9788. this.currentPath.push([x, y]);
  9789. this.#lastPoint = null;
  9790. this.#setStroke();
  9791. this.ctx.beginPath();
  9792. this.ctx.moveTo(x, y);
  9793. this.#requestFrameCallback = () => {
  9794. if (!this.#requestFrameCallback) {
  9795. return;
  9796. }
  9797. if (this.#lastPoint) {
  9798. if (this.isEmpty()) {
  9799. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  9800. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  9801. } else {
  9802. this.#redraw();
  9803. }
  9804. this.ctx.lineTo(...this.#lastPoint);
  9805. this.#lastPoint = null;
  9806. this.ctx.stroke();
  9807. }
  9808. window.requestAnimationFrame(this.#requestFrameCallback);
  9809. };
  9810. window.requestAnimationFrame(this.#requestFrameCallback);
  9811. }
  9812. #draw(x, y) {
  9813. const [lastX, lastY] = this.currentPath.at(-1);
  9814. if (x === lastX && y === lastY) {
  9815. return;
  9816. }
  9817. this.currentPath.push([x, y]);
  9818. this.#lastPoint = [x, y];
  9819. }
  9820. #stopDrawing(x, y) {
  9821. this.ctx.closePath();
  9822. this.#requestFrameCallback = null;
  9823. x = Math.min(Math.max(x, 0), this.canvas.width);
  9824. y = Math.min(Math.max(y, 0), this.canvas.height);
  9825. const [lastX, lastY] = this.currentPath.at(-1);
  9826. if (x !== lastX || y !== lastY) {
  9827. this.currentPath.push([x, y]);
  9828. }
  9829. let bezier;
  9830. if (this.currentPath.length !== 1) {
  9831. bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
  9832. } else {
  9833. const xy = [x, y];
  9834. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  9835. }
  9836. const path2D = InkEditor.#buildPath2D(bezier);
  9837. this.currentPath.length = 0;
  9838. const cmd = () => {
  9839. this.paths.push(bezier);
  9840. this.bezierPath2D.push(path2D);
  9841. this.rebuild();
  9842. };
  9843. const undo = () => {
  9844. this.paths.pop();
  9845. this.bezierPath2D.pop();
  9846. if (this.paths.length === 0) {
  9847. this.remove();
  9848. } else {
  9849. if (!this.canvas) {
  9850. this.#createCanvas();
  9851. this.#createObserver();
  9852. }
  9853. this.#fitToContent();
  9854. }
  9855. };
  9856. this.parent.addCommands({
  9857. cmd,
  9858. undo,
  9859. mustExec: true
  9860. });
  9861. }
  9862. #redraw() {
  9863. if (this.isEmpty()) {
  9864. this.#updateTransform();
  9865. return;
  9866. }
  9867. this.#setStroke();
  9868. const {
  9869. canvas,
  9870. ctx
  9871. } = this;
  9872. ctx.setTransform(1, 0, 0, 1, 0, 0);
  9873. ctx.clearRect(0, 0, canvas.width, canvas.height);
  9874. this.#updateTransform();
  9875. for (const path of this.bezierPath2D) {
  9876. ctx.stroke(path);
  9877. }
  9878. }
  9879. commit() {
  9880. if (this.#disableEditing) {
  9881. return;
  9882. }
  9883. super.commit();
  9884. this.isEditing = false;
  9885. this.disableEditMode();
  9886. this.setInForeground();
  9887. this.#disableEditing = true;
  9888. this.div.classList.add("disabled");
  9889. this.#fitToContent(true);
  9890. this.parent.addInkEditorIfNeeded(true);
  9891. this.parent.moveDivInDOM(this);
  9892. this.div.focus();
  9893. }
  9894. focusin(event) {
  9895. super.focusin(event);
  9896. this.enableEditMode();
  9897. }
  9898. canvasPointerdown(event) {
  9899. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  9900. return;
  9901. }
  9902. this.setInForeground();
  9903. if (event.type !== "mouse") {
  9904. this.div.focus();
  9905. }
  9906. event.stopPropagation();
  9907. this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
  9908. this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
  9909. this.#startDrawing(event.offsetX, event.offsetY);
  9910. }
  9911. canvasPointermove(event) {
  9912. event.stopPropagation();
  9913. this.#draw(event.offsetX, event.offsetY);
  9914. }
  9915. canvasPointerup(event) {
  9916. if (event.button !== 0) {
  9917. return;
  9918. }
  9919. if (this.isInEditMode() && this.currentPath.length !== 0) {
  9920. event.stopPropagation();
  9921. this.#endDrawing(event);
  9922. this.setInBackground();
  9923. }
  9924. }
  9925. canvasPointerleave(event) {
  9926. this.#endDrawing(event);
  9927. this.setInBackground();
  9928. }
  9929. #endDrawing(event) {
  9930. this.#stopDrawing(event.offsetX, event.offsetY);
  9931. this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
  9932. this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
  9933. this.parent.addToAnnotationStorage(this);
  9934. }
  9935. #createCanvas() {
  9936. this.canvas = document.createElement("canvas");
  9937. this.canvas.width = this.canvas.height = 0;
  9938. this.canvas.className = "inkEditorCanvas";
  9939. InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
  9940. this.div.append(this.canvas);
  9941. this.ctx = this.canvas.getContext("2d");
  9942. }
  9943. #createObserver() {
  9944. this.#observer = new ResizeObserver(entries => {
  9945. const rect = entries[0].contentRect;
  9946. if (rect.width && rect.height) {
  9947. this.setDimensions(rect.width, rect.height);
  9948. }
  9949. });
  9950. this.#observer.observe(this.div);
  9951. }
  9952. render() {
  9953. if (this.div) {
  9954. return this.div;
  9955. }
  9956. let baseX, baseY;
  9957. if (this.width) {
  9958. baseX = this.x;
  9959. baseY = this.y;
  9960. }
  9961. super.render();
  9962. InkEditor._l10nPromise.get("editor_ink_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
  9963. const [x, y, w, h] = this.#getInitialBBox();
  9964. this.setAt(x, y, 0, 0);
  9965. this.setDims(w, h);
  9966. this.#createCanvas();
  9967. if (this.width) {
  9968. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9969. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  9970. this.#isCanvasInitialized = true;
  9971. this.#setCanvasDims();
  9972. this.setDims(this.width * parentWidth, this.height * parentHeight);
  9973. this.#redraw();
  9974. this.#setMinDims();
  9975. this.div.classList.add("disabled");
  9976. } else {
  9977. this.div.classList.add("editing");
  9978. this.enableEditMode();
  9979. }
  9980. this.#createObserver();
  9981. return this.div;
  9982. }
  9983. #setCanvasDims() {
  9984. if (!this.#isCanvasInitialized) {
  9985. return;
  9986. }
  9987. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9988. this.canvas.width = Math.ceil(this.width * parentWidth);
  9989. this.canvas.height = Math.ceil(this.height * parentHeight);
  9990. this.#updateTransform();
  9991. }
  9992. setDimensions(width, height) {
  9993. const roundedWidth = Math.round(width);
  9994. const roundedHeight = Math.round(height);
  9995. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  9996. return;
  9997. }
  9998. this.#realWidth = roundedWidth;
  9999. this.#realHeight = roundedHeight;
  10000. this.canvas.style.visibility = "hidden";
  10001. if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
  10002. height = Math.ceil(width / this.#aspectRatio);
  10003. this.setDims(width, height);
  10004. }
  10005. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  10006. this.width = width / parentWidth;
  10007. this.height = height / parentHeight;
  10008. if (this.#disableEditing) {
  10009. this.#setScaleFactor(width, height);
  10010. }
  10011. this.#setCanvasDims();
  10012. this.#redraw();
  10013. this.canvas.style.visibility = "visible";
  10014. }
  10015. #setScaleFactor(width, height) {
  10016. const padding = this.#getPadding();
  10017. const scaleFactorW = (width - padding) / this.#baseWidth;
  10018. const scaleFactorH = (height - padding) / this.#baseHeight;
  10019. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  10020. }
  10021. #updateTransform() {
  10022. const padding = this.#getPadding() / 2;
  10023. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  10024. }
  10025. static #buildPath2D(bezier) {
  10026. const path2D = new Path2D();
  10027. for (let i = 0, ii = bezier.length; i < ii; i++) {
  10028. const [first, control1, control2, second] = bezier[i];
  10029. if (i === 0) {
  10030. path2D.moveTo(...first);
  10031. }
  10032. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  10033. }
  10034. return path2D;
  10035. }
  10036. #serializePaths(s, tx, ty, h) {
  10037. const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
  10038. const paths = [];
  10039. const padding = this.thickness / 2;
  10040. let buffer, points;
  10041. for (const bezier of this.paths) {
  10042. buffer = [];
  10043. points = [];
  10044. for (let i = 0, ii = bezier.length; i < ii; i++) {
  10045. const [first, control1, control2, second] = bezier[i];
  10046. const p10 = s * (first[0] + tx) + padding;
  10047. const p11 = h - s * (first[1] + ty) - padding;
  10048. const p20 = s * (control1[0] + tx) + padding;
  10049. const p21 = h - s * (control1[1] + ty) - padding;
  10050. const p30 = s * (control2[0] + tx) + padding;
  10051. const p31 = h - s * (control2[1] + ty) - padding;
  10052. const p40 = s * (second[0] + tx) + padding;
  10053. const p41 = h - s * (second[1] + ty) - padding;
  10054. if (i === 0) {
  10055. buffer.push(p10, p11);
  10056. points.push(p10, p11);
  10057. }
  10058. buffer.push(p20, p21, p30, p31, p40, p41);
  10059. this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
  10060. }
  10061. paths.push({
  10062. bezier: buffer,
  10063. points
  10064. });
  10065. }
  10066. return paths;
  10067. }
  10068. #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
  10069. if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
  10070. points.push(p40, p41);
  10071. return;
  10072. }
  10073. for (let i = 1; i < n - 1; i++) {
  10074. const t = i / n;
  10075. const mt = 1 - t;
  10076. let q10 = t * p10 + mt * p20;
  10077. let q11 = t * p11 + mt * p21;
  10078. let q20 = t * p20 + mt * p30;
  10079. let q21 = t * p21 + mt * p31;
  10080. const q30 = t * p30 + mt * p40;
  10081. const q31 = t * p31 + mt * p41;
  10082. q10 = t * q10 + mt * q20;
  10083. q11 = t * q11 + mt * q21;
  10084. q20 = t * q20 + mt * q30;
  10085. q21 = t * q21 + mt * q31;
  10086. q10 = t * q10 + mt * q20;
  10087. q11 = t * q11 + mt * q21;
  10088. points.push(q10, q11);
  10089. }
  10090. points.push(p40, p41);
  10091. }
  10092. #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
  10093. const tol = 10;
  10094. const ax = (3 * p20 - 2 * p10 - p40) ** 2;
  10095. const ay = (3 * p21 - 2 * p11 - p41) ** 2;
  10096. const bx = (3 * p30 - p10 - 2 * p40) ** 2;
  10097. const by = (3 * p31 - p11 - 2 * p41) ** 2;
  10098. return Math.max(ax, bx) + Math.max(ay, by) <= tol;
  10099. }
  10100. #getBbox() {
  10101. let xMin = Infinity;
  10102. let xMax = -Infinity;
  10103. let yMin = Infinity;
  10104. let yMax = -Infinity;
  10105. for (const path of this.paths) {
  10106. for (const [first, control1, control2, second] of path) {
  10107. const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  10108. xMin = Math.min(xMin, bbox[0]);
  10109. yMin = Math.min(yMin, bbox[1]);
  10110. xMax = Math.max(xMax, bbox[2]);
  10111. yMax = Math.max(yMax, bbox[3]);
  10112. }
  10113. }
  10114. return [xMin, yMin, xMax, yMax];
  10115. }
  10116. #getPadding() {
  10117. return this.#disableEditing ? Math.ceil(this.thickness * this.parent.scaleFactor) : 0;
  10118. }
  10119. #fitToContent(firstTime = false) {
  10120. if (this.isEmpty()) {
  10121. return;
  10122. }
  10123. if (!this.#disableEditing) {
  10124. this.#redraw();
  10125. return;
  10126. }
  10127. const bbox = this.#getBbox();
  10128. const padding = this.#getPadding();
  10129. this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  10130. this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  10131. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  10132. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  10133. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  10134. this.width = width / parentWidth;
  10135. this.height = height / parentHeight;
  10136. this.#aspectRatio = width / height;
  10137. this.#setMinDims();
  10138. const prevTranslationX = this.translationX;
  10139. const prevTranslationY = this.translationY;
  10140. this.translationX = -bbox[0];
  10141. this.translationY = -bbox[1];
  10142. this.#setCanvasDims();
  10143. this.#redraw();
  10144. this.#realWidth = width;
  10145. this.#realHeight = height;
  10146. this.setDims(width, height);
  10147. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  10148. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  10149. }
  10150. #setMinDims() {
  10151. const {
  10152. style
  10153. } = this.div;
  10154. if (this.#aspectRatio >= 1) {
  10155. style.minHeight = `${RESIZER_SIZE}px`;
  10156. style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
  10157. } else {
  10158. style.minWidth = `${RESIZER_SIZE}px`;
  10159. style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
  10160. }
  10161. }
  10162. static deserialize(data, parent) {
  10163. const editor = super.deserialize(data, parent);
  10164. editor.thickness = data.thickness;
  10165. editor.color = _util.Util.makeHexColor(...data.color);
  10166. editor.opacity = data.opacity;
  10167. const [pageWidth, pageHeight] = parent.pageDimensions;
  10168. const width = editor.width * pageWidth;
  10169. const height = editor.height * pageHeight;
  10170. const scaleFactor = parent.scaleFactor;
  10171. const padding = data.thickness / 2;
  10172. editor.#aspectRatio = width / height;
  10173. editor.#disableEditing = true;
  10174. editor.#realWidth = Math.round(width);
  10175. editor.#realHeight = Math.round(height);
  10176. for (const {
  10177. bezier
  10178. } of data.paths) {
  10179. const path = [];
  10180. editor.paths.push(path);
  10181. let p0 = scaleFactor * (bezier[0] - padding);
  10182. let p1 = scaleFactor * (height - bezier[1] - padding);
  10183. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  10184. const p10 = scaleFactor * (bezier[i] - padding);
  10185. const p11 = scaleFactor * (height - bezier[i + 1] - padding);
  10186. const p20 = scaleFactor * (bezier[i + 2] - padding);
  10187. const p21 = scaleFactor * (height - bezier[i + 3] - padding);
  10188. const p30 = scaleFactor * (bezier[i + 4] - padding);
  10189. const p31 = scaleFactor * (height - bezier[i + 5] - padding);
  10190. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  10191. p0 = p30;
  10192. p1 = p31;
  10193. }
  10194. const path2D = this.#buildPath2D(path);
  10195. editor.bezierPath2D.push(path2D);
  10196. }
  10197. const bbox = editor.#getBbox();
  10198. editor.#baseWidth = bbox[2] - bbox[0];
  10199. editor.#baseHeight = bbox[3] - bbox[1];
  10200. editor.#setScaleFactor(width, height);
  10201. return editor;
  10202. }
  10203. serialize() {
  10204. if (this.isEmpty()) {
  10205. return null;
  10206. }
  10207. const rect = this.getRect(0, 0);
  10208. const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
  10209. const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  10210. return {
  10211. annotationType: _util.AnnotationEditorType.INK,
  10212. color,
  10213. thickness: this.thickness,
  10214. opacity: this.opacity,
  10215. paths: this.#serializePaths(this.scaleFactor / this.parent.scaleFactor, this.translationX, this.translationY, height),
  10216. pageIndex: this.parent.pageIndex,
  10217. rect,
  10218. rotation: this.rotation
  10219. };
  10220. }
  10221. }
  10222. exports.InkEditor = InkEditor;
  10223. /***/ }),
  10224. /* 25 */
  10225. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10226. Object.defineProperty(exports, "__esModule", ({
  10227. value: true
  10228. }));
  10229. exports.fitCurve = void 0;
  10230. const fitCurve = __w_pdfjs_require__(26);
  10231. exports.fitCurve = fitCurve;
  10232. /***/ }),
  10233. /* 26 */
  10234. /***/ ((module) => {
  10235. function fitCurve(points, maxError, progressCallback) {
  10236. if (!Array.isArray(points)) {
  10237. throw new TypeError("First argument should be an array");
  10238. }
  10239. points.forEach(point => {
  10240. if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
  10241. throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
  10242. }
  10243. });
  10244. points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
  10245. if (points.length < 2) {
  10246. return [];
  10247. }
  10248. const len = points.length;
  10249. const leftTangent = createTangent(points[1], points[0]);
  10250. const rightTangent = createTangent(points[len - 2], points[len - 1]);
  10251. return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
  10252. }
  10253. function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
  10254. const MaxIterations = 20;
  10255. var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
  10256. if (points.length === 2) {
  10257. dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
  10258. bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
  10259. return [bezCurve];
  10260. }
  10261. u = chordLengthParameterize(points);
  10262. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
  10263. if (maxError === 0 || maxError < error) {
  10264. return [bezCurve];
  10265. }
  10266. if (maxError < error * error) {
  10267. uPrime = u;
  10268. prevErr = maxError;
  10269. prevSplit = splitPoint;
  10270. for (i = 0; i < MaxIterations; i++) {
  10271. uPrime = reparameterize(bezCurve, points, uPrime);
  10272. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
  10273. if (maxError < error) {
  10274. return [bezCurve];
  10275. } else if (splitPoint === prevSplit) {
  10276. let errChange = maxError / prevErr;
  10277. if (errChange > .9999 && errChange < 1.0001) {
  10278. break;
  10279. }
  10280. }
  10281. prevErr = maxError;
  10282. prevSplit = splitPoint;
  10283. }
  10284. }
  10285. beziers = [];
  10286. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
  10287. if (centerVector.every(val => val === 0)) {
  10288. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
  10289. [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
  10290. }
  10291. toCenterTangent = maths.normalize(centerVector);
  10292. fromCenterTangent = maths.mulItems(toCenterTangent, -1);
  10293. beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
  10294. beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
  10295. return beziers;
  10296. }
  10297. ;
  10298. function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
  10299. var bezCurve, maxError, splitPoint;
  10300. bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
  10301. [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
  10302. if (progressCallback) {
  10303. progressCallback({
  10304. bez: bezCurve,
  10305. points: points,
  10306. params: paramsOrig,
  10307. maxErr: maxError,
  10308. maxPoint: splitPoint
  10309. });
  10310. }
  10311. return [bezCurve, maxError, splitPoint];
  10312. }
  10313. function generateBezier(points, parameters, leftTangent, rightTangent) {
  10314. var bezCurve,
  10315. A,
  10316. a,
  10317. C,
  10318. X,
  10319. det_C0_C1,
  10320. det_C0_X,
  10321. det_X_C1,
  10322. alpha_l,
  10323. alpha_r,
  10324. epsilon,
  10325. segLength,
  10326. i,
  10327. len,
  10328. tmp,
  10329. u,
  10330. ux,
  10331. firstPoint = points[0],
  10332. lastPoint = points[points.length - 1];
  10333. bezCurve = [firstPoint, null, null, lastPoint];
  10334. A = maths.zeros_Xx2x2(parameters.length);
  10335. for (i = 0, len = parameters.length; i < len; i++) {
  10336. u = parameters[i];
  10337. ux = 1 - u;
  10338. a = A[i];
  10339. a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
  10340. a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
  10341. }
  10342. C = [[0, 0], [0, 0]];
  10343. X = [0, 0];
  10344. for (i = 0, len = points.length; i < len; i++) {
  10345. u = parameters[i];
  10346. a = A[i];
  10347. C[0][0] += maths.dot(a[0], a[0]);
  10348. C[0][1] += maths.dot(a[0], a[1]);
  10349. C[1][0] += maths.dot(a[0], a[1]);
  10350. C[1][1] += maths.dot(a[1], a[1]);
  10351. tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
  10352. X[0] += maths.dot(a[0], tmp);
  10353. X[1] += maths.dot(a[1], tmp);
  10354. }
  10355. det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  10356. det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
  10357. det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
  10358. alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
  10359. alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
  10360. segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
  10361. epsilon = 1.0e-6 * segLength;
  10362. if (alpha_l < epsilon || alpha_r < epsilon) {
  10363. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
  10364. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
  10365. } else {
  10366. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
  10367. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
  10368. }
  10369. return bezCurve;
  10370. }
  10371. ;
  10372. function reparameterize(bezier, points, parameters) {
  10373. return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
  10374. }
  10375. ;
  10376. function newtonRaphsonRootFind(bez, point, u) {
  10377. var d = maths.subtract(bezier.q(bez, u), point),
  10378. qprime = bezier.qprime(bez, u),
  10379. numerator = maths.mulMatrix(d, qprime),
  10380. denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
  10381. if (denominator === 0) {
  10382. return u;
  10383. } else {
  10384. return u - numerator / denominator;
  10385. }
  10386. }
  10387. ;
  10388. function chordLengthParameterize(points) {
  10389. var u = [],
  10390. currU,
  10391. prevU,
  10392. prevP;
  10393. points.forEach((p, i) => {
  10394. currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
  10395. u.push(currU);
  10396. prevU = currU;
  10397. prevP = p;
  10398. });
  10399. u = u.map(x => x / prevU);
  10400. return u;
  10401. }
  10402. ;
  10403. function computeMaxError(points, bez, parameters) {
  10404. var dist, maxDist, splitPoint, v, i, count, point, t;
  10405. maxDist = 0;
  10406. splitPoint = Math.floor(points.length / 2);
  10407. const t_distMap = mapTtoRelativeDistances(bez, 10);
  10408. for (i = 0, count = points.length; i < count; i++) {
  10409. point = points[i];
  10410. t = find_t(bez, parameters[i], t_distMap, 10);
  10411. v = maths.subtract(bezier.q(bez, t), point);
  10412. dist = v[0] * v[0] + v[1] * v[1];
  10413. if (dist > maxDist) {
  10414. maxDist = dist;
  10415. splitPoint = i;
  10416. }
  10417. }
  10418. return [maxDist, splitPoint];
  10419. }
  10420. ;
  10421. var mapTtoRelativeDistances = function (bez, B_parts) {
  10422. var B_t_curr;
  10423. var B_t_dist = [0];
  10424. var B_t_prev = bez[0];
  10425. var sumLen = 0;
  10426. for (var i = 1; i <= B_parts; i++) {
  10427. B_t_curr = bezier.q(bez, i / B_parts);
  10428. sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
  10429. B_t_dist.push(sumLen);
  10430. B_t_prev = B_t_curr;
  10431. }
  10432. B_t_dist = B_t_dist.map(x => x / sumLen);
  10433. return B_t_dist;
  10434. };
  10435. function find_t(bez, param, t_distMap, B_parts) {
  10436. if (param < 0) {
  10437. return 0;
  10438. }
  10439. if (param > 1) {
  10440. return 1;
  10441. }
  10442. var lenMax, lenMin, tMax, tMin, t;
  10443. for (var i = 1; i <= B_parts; i++) {
  10444. if (param <= t_distMap[i]) {
  10445. tMin = (i - 1) / B_parts;
  10446. tMax = i / B_parts;
  10447. lenMin = t_distMap[i - 1];
  10448. lenMax = t_distMap[i];
  10449. t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
  10450. break;
  10451. }
  10452. }
  10453. return t;
  10454. }
  10455. function createTangent(pointA, pointB) {
  10456. return maths.normalize(maths.subtract(pointA, pointB));
  10457. }
  10458. class maths {
  10459. static zeros_Xx2x2(x) {
  10460. var zs = [];
  10461. while (x--) {
  10462. zs.push([0, 0]);
  10463. }
  10464. return zs;
  10465. }
  10466. static mulItems(items, multiplier) {
  10467. return items.map(x => x * multiplier);
  10468. }
  10469. static mulMatrix(m1, m2) {
  10470. return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
  10471. }
  10472. static subtract(arr1, arr2) {
  10473. return arr1.map((x1, i) => x1 - arr2[i]);
  10474. }
  10475. static addArrays(arr1, arr2) {
  10476. return arr1.map((x1, i) => x1 + arr2[i]);
  10477. }
  10478. static addItems(items, addition) {
  10479. return items.map(x => x + addition);
  10480. }
  10481. static sum(items) {
  10482. return items.reduce((sum, x) => sum + x);
  10483. }
  10484. static dot(m1, m2) {
  10485. return maths.mulMatrix(m1, m2);
  10486. }
  10487. static vectorLen(v) {
  10488. return Math.hypot(...v);
  10489. }
  10490. static divItems(items, divisor) {
  10491. return items.map(x => x / divisor);
  10492. }
  10493. static squareItems(items) {
  10494. return items.map(x => x * x);
  10495. }
  10496. static normalize(v) {
  10497. return this.divItems(v, this.vectorLen(v));
  10498. }
  10499. }
  10500. class bezier {
  10501. static q(ctrlPoly, t) {
  10502. var tx = 1.0 - t;
  10503. var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
  10504. pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
  10505. pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
  10506. pD = maths.mulItems(ctrlPoly[3], t * t * t);
  10507. return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
  10508. }
  10509. static qprime(ctrlPoly, t) {
  10510. var tx = 1.0 - t;
  10511. var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
  10512. pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
  10513. pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
  10514. return maths.addArrays(maths.addArrays(pA, pB), pC);
  10515. }
  10516. static qprimeprime(ctrlPoly, t) {
  10517. 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));
  10518. }
  10519. }
  10520. module.exports = fitCurve;
  10521. module.exports.fitCubic = fitCubic;
  10522. module.exports.createTangent = createTangent;
  10523. /***/ }),
  10524. /* 27 */
  10525. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10526. Object.defineProperty(exports, "__esModule", ({
  10527. value: true
  10528. }));
  10529. exports.AnnotationLayer = void 0;
  10530. var _util = __w_pdfjs_require__(1);
  10531. var _display_utils = __w_pdfjs_require__(4);
  10532. var _annotation_storage = __w_pdfjs_require__(7);
  10533. var _scripting_utils = __w_pdfjs_require__(28);
  10534. var _xfa_layer = __w_pdfjs_require__(29);
  10535. const DEFAULT_TAB_INDEX = 1000;
  10536. const DEFAULT_FONT_SIZE = 9;
  10537. const GetElementsByNameSet = new WeakSet();
  10538. function getRectDims(rect) {
  10539. return {
  10540. width: rect[2] - rect[0],
  10541. height: rect[3] - rect[1]
  10542. };
  10543. }
  10544. class AnnotationElementFactory {
  10545. static create(parameters) {
  10546. const subtype = parameters.data.annotationType;
  10547. switch (subtype) {
  10548. case _util.AnnotationType.LINK:
  10549. return new LinkAnnotationElement(parameters);
  10550. case _util.AnnotationType.TEXT:
  10551. return new TextAnnotationElement(parameters);
  10552. case _util.AnnotationType.WIDGET:
  10553. const fieldType = parameters.data.fieldType;
  10554. switch (fieldType) {
  10555. case "Tx":
  10556. return new TextWidgetAnnotationElement(parameters);
  10557. case "Btn":
  10558. if (parameters.data.radioButton) {
  10559. return new RadioButtonWidgetAnnotationElement(parameters);
  10560. } else if (parameters.data.checkBox) {
  10561. return new CheckboxWidgetAnnotationElement(parameters);
  10562. }
  10563. return new PushButtonWidgetAnnotationElement(parameters);
  10564. case "Ch":
  10565. return new ChoiceWidgetAnnotationElement(parameters);
  10566. }
  10567. return new WidgetAnnotationElement(parameters);
  10568. case _util.AnnotationType.POPUP:
  10569. return new PopupAnnotationElement(parameters);
  10570. case _util.AnnotationType.FREETEXT:
  10571. return new FreeTextAnnotationElement(parameters);
  10572. case _util.AnnotationType.LINE:
  10573. return new LineAnnotationElement(parameters);
  10574. case _util.AnnotationType.SQUARE:
  10575. return new SquareAnnotationElement(parameters);
  10576. case _util.AnnotationType.CIRCLE:
  10577. return new CircleAnnotationElement(parameters);
  10578. case _util.AnnotationType.POLYLINE:
  10579. return new PolylineAnnotationElement(parameters);
  10580. case _util.AnnotationType.CARET:
  10581. return new CaretAnnotationElement(parameters);
  10582. case _util.AnnotationType.INK:
  10583. return new InkAnnotationElement(parameters);
  10584. case _util.AnnotationType.POLYGON:
  10585. return new PolygonAnnotationElement(parameters);
  10586. case _util.AnnotationType.HIGHLIGHT:
  10587. return new HighlightAnnotationElement(parameters);
  10588. case _util.AnnotationType.UNDERLINE:
  10589. return new UnderlineAnnotationElement(parameters);
  10590. case _util.AnnotationType.SQUIGGLY:
  10591. return new SquigglyAnnotationElement(parameters);
  10592. case _util.AnnotationType.STRIKEOUT:
  10593. return new StrikeOutAnnotationElement(parameters);
  10594. case _util.AnnotationType.STAMP:
  10595. return new StampAnnotationElement(parameters);
  10596. case _util.AnnotationType.FILEATTACHMENT:
  10597. return new FileAttachmentAnnotationElement(parameters);
  10598. default:
  10599. return new AnnotationElement(parameters);
  10600. }
  10601. }
  10602. }
  10603. class AnnotationElement {
  10604. constructor(parameters, {
  10605. isRenderable = false,
  10606. ignoreBorder = false,
  10607. createQuadrilaterals = false
  10608. } = {}) {
  10609. this.isRenderable = isRenderable;
  10610. this.data = parameters.data;
  10611. this.layer = parameters.layer;
  10612. this.page = parameters.page;
  10613. this.viewport = parameters.viewport;
  10614. this.linkService = parameters.linkService;
  10615. this.downloadManager = parameters.downloadManager;
  10616. this.imageResourcesPath = parameters.imageResourcesPath;
  10617. this.renderForms = parameters.renderForms;
  10618. this.svgFactory = parameters.svgFactory;
  10619. this.annotationStorage = parameters.annotationStorage;
  10620. this.enableScripting = parameters.enableScripting;
  10621. this.hasJSActions = parameters.hasJSActions;
  10622. this._fieldObjects = parameters.fieldObjects;
  10623. this._mouseState = parameters.mouseState;
  10624. if (isRenderable) {
  10625. this.container = this._createContainer(ignoreBorder);
  10626. }
  10627. if (createQuadrilaterals) {
  10628. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  10629. }
  10630. }
  10631. _createContainer(ignoreBorder = false) {
  10632. const data = this.data,
  10633. page = this.page,
  10634. viewport = this.viewport;
  10635. const container = document.createElement("section");
  10636. const {
  10637. width,
  10638. height
  10639. } = getRectDims(data.rect);
  10640. const [pageLLx, pageLLy, pageURx, pageURy] = viewport.viewBox;
  10641. const pageWidth = pageURx - pageLLx;
  10642. const pageHeight = pageURy - pageLLy;
  10643. container.setAttribute("data-annotation-id", data.id);
  10644. 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]]);
  10645. if (!ignoreBorder && data.borderStyle.width > 0) {
  10646. container.style.borderWidth = `${data.borderStyle.width}px`;
  10647. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  10648. const verticalRadius = data.borderStyle.verticalCornerRadius;
  10649. if (horizontalRadius > 0 || verticalRadius > 0) {
  10650. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  10651. container.style.borderRadius = radius;
  10652. }
  10653. switch (data.borderStyle.style) {
  10654. case _util.AnnotationBorderStyleType.SOLID:
  10655. container.style.borderStyle = "solid";
  10656. break;
  10657. case _util.AnnotationBorderStyleType.DASHED:
  10658. container.style.borderStyle = "dashed";
  10659. break;
  10660. case _util.AnnotationBorderStyleType.BEVELED:
  10661. (0, _util.warn)("Unimplemented border style: beveled");
  10662. break;
  10663. case _util.AnnotationBorderStyleType.INSET:
  10664. (0, _util.warn)("Unimplemented border style: inset");
  10665. break;
  10666. case _util.AnnotationBorderStyleType.UNDERLINE:
  10667. container.style.borderBottomStyle = "solid";
  10668. break;
  10669. default:
  10670. break;
  10671. }
  10672. const borderColor = data.borderColor || null;
  10673. if (borderColor) {
  10674. container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  10675. } else {
  10676. container.style.borderWidth = 0;
  10677. }
  10678. }
  10679. container.style.left = `${100 * (rect[0] - pageLLx) / pageWidth}%`;
  10680. container.style.top = `${100 * (rect[1] - pageLLy) / pageHeight}%`;
  10681. const {
  10682. rotation
  10683. } = data;
  10684. if (data.hasOwnCanvas || rotation === 0) {
  10685. container.style.width = `${100 * width / pageWidth}%`;
  10686. container.style.height = `${100 * height / pageHeight}%`;
  10687. } else {
  10688. this.setRotation(rotation, container);
  10689. }
  10690. return container;
  10691. }
  10692. setRotation(angle, container = this.container) {
  10693. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  10694. const pageWidth = pageURx - pageLLx;
  10695. const pageHeight = pageURy - pageLLy;
  10696. const {
  10697. width,
  10698. height
  10699. } = getRectDims(this.data.rect);
  10700. let elementWidth, elementHeight;
  10701. if (angle % 180 === 0) {
  10702. elementWidth = 100 * width / pageWidth;
  10703. elementHeight = 100 * height / pageHeight;
  10704. } else {
  10705. elementWidth = 100 * height / pageWidth;
  10706. elementHeight = 100 * width / pageHeight;
  10707. }
  10708. container.style.width = `${elementWidth}%`;
  10709. container.style.height = `${elementHeight}%`;
  10710. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  10711. }
  10712. get _commonActions() {
  10713. const setColor = (jsName, styleName, event) => {
  10714. const color = event.detail[jsName];
  10715. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  10716. };
  10717. return (0, _util.shadow)(this, "_commonActions", {
  10718. display: event => {
  10719. const hidden = event.detail.display % 2 === 1;
  10720. this.container.style.visibility = hidden ? "hidden" : "visible";
  10721. this.annotationStorage.setValue(this.data.id, {
  10722. hidden,
  10723. print: event.detail.display === 0 || event.detail.display === 3
  10724. });
  10725. },
  10726. print: event => {
  10727. this.annotationStorage.setValue(this.data.id, {
  10728. print: event.detail.print
  10729. });
  10730. },
  10731. hidden: event => {
  10732. this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
  10733. this.annotationStorage.setValue(this.data.id, {
  10734. hidden: event.detail.hidden
  10735. });
  10736. },
  10737. focus: event => {
  10738. setTimeout(() => event.target.focus({
  10739. preventScroll: false
  10740. }), 0);
  10741. },
  10742. userName: event => {
  10743. event.target.title = event.detail.userName;
  10744. },
  10745. readonly: event => {
  10746. if (event.detail.readonly) {
  10747. event.target.setAttribute("readonly", "");
  10748. } else {
  10749. event.target.removeAttribute("readonly");
  10750. }
  10751. },
  10752. required: event => {
  10753. this._setRequired(event.target, event.detail.required);
  10754. },
  10755. bgColor: event => {
  10756. setColor("bgColor", "backgroundColor", event);
  10757. },
  10758. fillColor: event => {
  10759. setColor("fillColor", "backgroundColor", event);
  10760. },
  10761. fgColor: event => {
  10762. setColor("fgColor", "color", event);
  10763. },
  10764. textColor: event => {
  10765. setColor("textColor", "color", event);
  10766. },
  10767. borderColor: event => {
  10768. setColor("borderColor", "borderColor", event);
  10769. },
  10770. strokeColor: event => {
  10771. setColor("strokeColor", "borderColor", event);
  10772. },
  10773. rotation: event => {
  10774. const angle = event.detail.rotation;
  10775. this.setRotation(angle);
  10776. this.annotationStorage.setValue(this.data.id, {
  10777. rotation: angle
  10778. });
  10779. }
  10780. });
  10781. }
  10782. _dispatchEventFromSandbox(actions, jsEvent) {
  10783. const commonActions = this._commonActions;
  10784. for (const name of Object.keys(jsEvent.detail)) {
  10785. const action = actions[name] || commonActions[name];
  10786. if (action) {
  10787. action(jsEvent);
  10788. }
  10789. }
  10790. }
  10791. _setDefaultPropertiesFromJS(element) {
  10792. if (!this.enableScripting) {
  10793. return;
  10794. }
  10795. const storedData = this.annotationStorage.getRawValue(this.data.id);
  10796. if (!storedData) {
  10797. return;
  10798. }
  10799. const commonActions = this._commonActions;
  10800. for (const [actionName, detail] of Object.entries(storedData)) {
  10801. const action = commonActions[actionName];
  10802. if (action) {
  10803. action({
  10804. detail,
  10805. target: element
  10806. });
  10807. delete storedData[actionName];
  10808. }
  10809. }
  10810. }
  10811. _createQuadrilaterals(ignoreBorder = false) {
  10812. if (!this.data.quadPoints) {
  10813. return null;
  10814. }
  10815. const quadrilaterals = [];
  10816. const savedRect = this.data.rect;
  10817. for (const quadPoint of this.data.quadPoints) {
  10818. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  10819. quadrilaterals.push(this._createContainer(ignoreBorder));
  10820. }
  10821. this.data.rect = savedRect;
  10822. return quadrilaterals;
  10823. }
  10824. _createPopup(trigger, data) {
  10825. let container = this.container;
  10826. if (this.quadrilaterals) {
  10827. trigger = trigger || this.quadrilaterals;
  10828. container = this.quadrilaterals[0];
  10829. }
  10830. if (!trigger) {
  10831. trigger = document.createElement("div");
  10832. trigger.className = "popupTriggerArea";
  10833. container.append(trigger);
  10834. }
  10835. const popupElement = new PopupElement({
  10836. container,
  10837. trigger,
  10838. color: data.color,
  10839. titleObj: data.titleObj,
  10840. modificationDate: data.modificationDate,
  10841. contentsObj: data.contentsObj,
  10842. richText: data.richText,
  10843. hideWrapper: true
  10844. });
  10845. const popup = popupElement.render();
  10846. popup.style.left = "100%";
  10847. container.append(popup);
  10848. }
  10849. _renderQuadrilaterals(className) {
  10850. for (const quadrilateral of this.quadrilaterals) {
  10851. quadrilateral.className = className;
  10852. }
  10853. return this.quadrilaterals;
  10854. }
  10855. render() {
  10856. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  10857. }
  10858. _getElementsByName(name, skipId = null) {
  10859. const fields = [];
  10860. if (this._fieldObjects) {
  10861. const fieldObj = this._fieldObjects[name];
  10862. if (fieldObj) {
  10863. for (const {
  10864. page,
  10865. id,
  10866. exportValues
  10867. } of fieldObj) {
  10868. if (page === -1) {
  10869. continue;
  10870. }
  10871. if (id === skipId) {
  10872. continue;
  10873. }
  10874. const exportValue = typeof exportValues === "string" ? exportValues : null;
  10875. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  10876. if (domElement && !GetElementsByNameSet.has(domElement)) {
  10877. (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
  10878. continue;
  10879. }
  10880. fields.push({
  10881. id,
  10882. exportValue,
  10883. domElement
  10884. });
  10885. }
  10886. }
  10887. return fields;
  10888. }
  10889. for (const domElement of document.getElementsByName(name)) {
  10890. const {
  10891. id,
  10892. exportValue
  10893. } = domElement;
  10894. if (id === skipId) {
  10895. continue;
  10896. }
  10897. if (!GetElementsByNameSet.has(domElement)) {
  10898. continue;
  10899. }
  10900. fields.push({
  10901. id,
  10902. exportValue,
  10903. domElement
  10904. });
  10905. }
  10906. return fields;
  10907. }
  10908. static get platform() {
  10909. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  10910. return (0, _util.shadow)(this, "platform", {
  10911. isWin: platform.includes("Win"),
  10912. isMac: platform.includes("Mac")
  10913. });
  10914. }
  10915. }
  10916. class LinkAnnotationElement extends AnnotationElement {
  10917. constructor(parameters, options = null) {
  10918. super(parameters, {
  10919. isRenderable: true,
  10920. ignoreBorder: !!options?.ignoreBorder,
  10921. createQuadrilaterals: true
  10922. });
  10923. this.isTooltipOnly = parameters.data.isTooltipOnly;
  10924. }
  10925. render() {
  10926. const {
  10927. data,
  10928. linkService
  10929. } = this;
  10930. const link = document.createElement("a");
  10931. link.setAttribute("data-element-id", data.id);
  10932. let isBound = false;
  10933. if (data.url) {
  10934. linkService.addLinkAttributes(link, data.url, data.newWindow);
  10935. isBound = true;
  10936. } else if (data.action) {
  10937. this._bindNamedAction(link, data.action);
  10938. isBound = true;
  10939. } else if (data.dest) {
  10940. this._bindLink(link, data.dest);
  10941. isBound = true;
  10942. } else {
  10943. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  10944. this._bindJSAction(link, data);
  10945. isBound = true;
  10946. }
  10947. if (data.resetForm) {
  10948. this._bindResetFormAction(link, data.resetForm);
  10949. isBound = true;
  10950. } else if (this.isTooltipOnly && !isBound) {
  10951. this._bindLink(link, "");
  10952. isBound = true;
  10953. }
  10954. }
  10955. if (this.quadrilaterals) {
  10956. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  10957. const linkElement = index === 0 ? link : link.cloneNode();
  10958. quadrilateral.append(linkElement);
  10959. return quadrilateral;
  10960. });
  10961. }
  10962. this.container.className = "linkAnnotation";
  10963. if (isBound) {
  10964. this.container.append(link);
  10965. }
  10966. return this.container;
  10967. }
  10968. _bindLink(link, destination) {
  10969. link.href = this.linkService.getDestinationHash(destination);
  10970. link.onclick = () => {
  10971. if (destination) {
  10972. this.linkService.goToDestination(destination);
  10973. }
  10974. return false;
  10975. };
  10976. if (destination || destination === "") {
  10977. link.className = "internalLink";
  10978. }
  10979. }
  10980. _bindNamedAction(link, action) {
  10981. link.href = this.linkService.getAnchorUrl("");
  10982. link.onclick = () => {
  10983. this.linkService.executeNamedAction(action);
  10984. return false;
  10985. };
  10986. link.className = "internalLink";
  10987. }
  10988. _bindJSAction(link, data) {
  10989. link.href = this.linkService.getAnchorUrl("");
  10990. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  10991. for (const name of Object.keys(data.actions)) {
  10992. const jsName = map.get(name);
  10993. if (!jsName) {
  10994. continue;
  10995. }
  10996. link[jsName] = () => {
  10997. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10998. source: this,
  10999. detail: {
  11000. id: data.id,
  11001. name
  11002. }
  11003. });
  11004. return false;
  11005. };
  11006. }
  11007. if (!link.onclick) {
  11008. link.onclick = () => false;
  11009. }
  11010. link.className = "internalLink";
  11011. }
  11012. _bindResetFormAction(link, resetForm) {
  11013. const otherClickAction = link.onclick;
  11014. if (!otherClickAction) {
  11015. link.href = this.linkService.getAnchorUrl("");
  11016. }
  11017. link.className = "internalLink";
  11018. if (!this._fieldObjects) {
  11019. (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  11020. if (!otherClickAction) {
  11021. link.onclick = () => false;
  11022. }
  11023. return;
  11024. }
  11025. link.onclick = () => {
  11026. if (otherClickAction) {
  11027. otherClickAction();
  11028. }
  11029. const {
  11030. fields: resetFormFields,
  11031. refs: resetFormRefs,
  11032. include
  11033. } = resetForm;
  11034. const allFields = [];
  11035. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  11036. const fieldIds = new Set(resetFormRefs);
  11037. for (const fieldName of resetFormFields) {
  11038. const fields = this._fieldObjects[fieldName] || [];
  11039. for (const {
  11040. id
  11041. } of fields) {
  11042. fieldIds.add(id);
  11043. }
  11044. }
  11045. for (const fields of Object.values(this._fieldObjects)) {
  11046. for (const field of fields) {
  11047. if (fieldIds.has(field.id) === include) {
  11048. allFields.push(field);
  11049. }
  11050. }
  11051. }
  11052. } else {
  11053. for (const fields of Object.values(this._fieldObjects)) {
  11054. allFields.push(...fields);
  11055. }
  11056. }
  11057. const storage = this.annotationStorage;
  11058. const allIds = [];
  11059. for (const field of allFields) {
  11060. const {
  11061. id
  11062. } = field;
  11063. allIds.push(id);
  11064. switch (field.type) {
  11065. case "text":
  11066. {
  11067. const value = field.defaultValue || "";
  11068. storage.setValue(id, {
  11069. value
  11070. });
  11071. break;
  11072. }
  11073. case "checkbox":
  11074. case "radiobutton":
  11075. {
  11076. const value = field.defaultValue === field.exportValues;
  11077. storage.setValue(id, {
  11078. value
  11079. });
  11080. break;
  11081. }
  11082. case "combobox":
  11083. case "listbox":
  11084. {
  11085. const value = field.defaultValue || "";
  11086. storage.setValue(id, {
  11087. value
  11088. });
  11089. break;
  11090. }
  11091. default:
  11092. continue;
  11093. }
  11094. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  11095. if (!domElement) {
  11096. continue;
  11097. } else if (!GetElementsByNameSet.has(domElement)) {
  11098. (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
  11099. continue;
  11100. }
  11101. domElement.dispatchEvent(new Event("resetform"));
  11102. }
  11103. if (this.enableScripting) {
  11104. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11105. source: this,
  11106. detail: {
  11107. id: "app",
  11108. ids: allIds,
  11109. name: "ResetForm"
  11110. }
  11111. });
  11112. }
  11113. return false;
  11114. };
  11115. }
  11116. }
  11117. class TextAnnotationElement extends AnnotationElement {
  11118. constructor(parameters) {
  11119. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11120. super(parameters, {
  11121. isRenderable
  11122. });
  11123. }
  11124. render() {
  11125. this.container.className = "textAnnotation";
  11126. const image = document.createElement("img");
  11127. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  11128. image.alt = "[{{type}} Annotation]";
  11129. image.dataset.l10nId = "text_annotation_type";
  11130. image.dataset.l10nArgs = JSON.stringify({
  11131. type: this.data.name
  11132. });
  11133. if (!this.data.hasPopup) {
  11134. this._createPopup(image, this.data);
  11135. }
  11136. this.container.append(image);
  11137. return this.container;
  11138. }
  11139. }
  11140. class WidgetAnnotationElement extends AnnotationElement {
  11141. render() {
  11142. if (this.data.alternativeText) {
  11143. this.container.title = this.data.alternativeText;
  11144. }
  11145. return this.container;
  11146. }
  11147. _getKeyModifier(event) {
  11148. const {
  11149. isWin,
  11150. isMac
  11151. } = AnnotationElement.platform;
  11152. return isWin && event.ctrlKey || isMac && event.metaKey;
  11153. }
  11154. _setEventListener(element, baseName, eventName, valueGetter) {
  11155. if (baseName.includes("mouse")) {
  11156. element.addEventListener(baseName, event => {
  11157. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11158. source: this,
  11159. detail: {
  11160. id: this.data.id,
  11161. name: eventName,
  11162. value: valueGetter(event),
  11163. shift: event.shiftKey,
  11164. modifier: this._getKeyModifier(event)
  11165. }
  11166. });
  11167. });
  11168. } else {
  11169. element.addEventListener(baseName, event => {
  11170. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11171. source: this,
  11172. detail: {
  11173. id: this.data.id,
  11174. name: eventName,
  11175. value: valueGetter(event)
  11176. }
  11177. });
  11178. });
  11179. }
  11180. }
  11181. _setEventListeners(element, names, getter) {
  11182. for (const [baseName, eventName] of names) {
  11183. if (eventName === "Action" || this.data.actions?.[eventName]) {
  11184. this._setEventListener(element, baseName, eventName, getter);
  11185. }
  11186. }
  11187. }
  11188. _setBackgroundColor(element) {
  11189. const color = this.data.backgroundColor || null;
  11190. element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  11191. }
  11192. _setTextStyle(element) {
  11193. const TEXT_ALIGNMENT = ["left", "center", "right"];
  11194. const {
  11195. fontColor
  11196. } = this.data.defaultAppearanceData;
  11197. const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
  11198. const style = element.style;
  11199. let computedFontSize;
  11200. if (this.data.multiLine) {
  11201. const height = Math.abs(this.data.rect[3] - this.data.rect[1]);
  11202. const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
  11203. const lineHeight = height / numberOfLines;
  11204. computedFontSize = Math.min(fontSize, Math.round(lineHeight / _util.LINE_FACTOR));
  11205. } else {
  11206. const height = Math.abs(this.data.rect[3] - this.data.rect[1]);
  11207. computedFontSize = Math.min(fontSize, Math.round(height / _util.LINE_FACTOR));
  11208. }
  11209. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  11210. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  11211. if (this.data.textAlignment !== null) {
  11212. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  11213. }
  11214. }
  11215. _setRequired(element, isRequired) {
  11216. if (isRequired) {
  11217. element.setAttribute("required", true);
  11218. } else {
  11219. element.removeAttribute("required");
  11220. }
  11221. element.setAttribute("aria-required", isRequired);
  11222. }
  11223. }
  11224. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  11225. constructor(parameters) {
  11226. const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  11227. super(parameters, {
  11228. isRenderable
  11229. });
  11230. }
  11231. setPropertyOnSiblings(base, key, value, keyInStorage) {
  11232. const storage = this.annotationStorage;
  11233. for (const element of this._getElementsByName(base.name, base.id)) {
  11234. if (element.domElement) {
  11235. element.domElement[key] = value;
  11236. }
  11237. storage.setValue(element.id, {
  11238. [keyInStorage]: value
  11239. });
  11240. }
  11241. }
  11242. render() {
  11243. const storage = this.annotationStorage;
  11244. const id = this.data.id;
  11245. this.container.className = "textWidgetAnnotation";
  11246. let element = null;
  11247. if (this.renderForms) {
  11248. const storedData = storage.getValue(id, {
  11249. value: this.data.fieldValue
  11250. });
  11251. const textContent = storedData.formattedValue || storedData.value || "";
  11252. const elementData = {
  11253. userValue: textContent,
  11254. formattedValue: null,
  11255. valueOnFocus: ""
  11256. };
  11257. if (this.data.multiLine) {
  11258. element = document.createElement("textarea");
  11259. element.textContent = textContent;
  11260. if (this.data.doNotScroll) {
  11261. element.style.overflowY = "hidden";
  11262. }
  11263. } else {
  11264. element = document.createElement("input");
  11265. element.type = "text";
  11266. element.setAttribute("value", textContent);
  11267. if (this.data.doNotScroll) {
  11268. element.style.overflowX = "hidden";
  11269. }
  11270. }
  11271. GetElementsByNameSet.add(element);
  11272. element.setAttribute("data-element-id", id);
  11273. element.disabled = this.data.readOnly;
  11274. element.name = this.data.fieldName;
  11275. element.tabIndex = DEFAULT_TAB_INDEX;
  11276. this._setRequired(element, this.data.required);
  11277. element.addEventListener("input", event => {
  11278. storage.setValue(id, {
  11279. value: event.target.value
  11280. });
  11281. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  11282. });
  11283. element.addEventListener("resetform", event => {
  11284. const defaultValue = this.data.defaultFieldValue ?? "";
  11285. element.value = elementData.userValue = defaultValue;
  11286. elementData.formattedValue = null;
  11287. });
  11288. let blurListener = event => {
  11289. const {
  11290. formattedValue
  11291. } = elementData;
  11292. if (formattedValue !== null && formattedValue !== undefined) {
  11293. event.target.value = formattedValue;
  11294. }
  11295. event.target.scrollLeft = 0;
  11296. };
  11297. if (this.enableScripting && this.hasJSActions) {
  11298. element.addEventListener("focus", event => {
  11299. if (elementData.userValue) {
  11300. event.target.value = elementData.userValue;
  11301. }
  11302. elementData.valueOnFocus = event.target.value;
  11303. });
  11304. element.addEventListener("updatefromsandbox", jsEvent => {
  11305. const actions = {
  11306. value(event) {
  11307. elementData.userValue = event.detail.value ?? "";
  11308. storage.setValue(id, {
  11309. value: elementData.userValue.toString()
  11310. });
  11311. event.target.value = elementData.userValue;
  11312. },
  11313. formattedValue(event) {
  11314. const {
  11315. formattedValue
  11316. } = event.detail;
  11317. elementData.formattedValue = formattedValue;
  11318. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  11319. event.target.value = formattedValue;
  11320. }
  11321. storage.setValue(id, {
  11322. formattedValue
  11323. });
  11324. },
  11325. selRange(event) {
  11326. event.target.setSelectionRange(...event.detail.selRange);
  11327. }
  11328. };
  11329. this._dispatchEventFromSandbox(actions, jsEvent);
  11330. });
  11331. element.addEventListener("keydown", event => {
  11332. let commitKey = -1;
  11333. if (event.key === "Escape") {
  11334. commitKey = 0;
  11335. } else if (event.key === "Enter") {
  11336. commitKey = 2;
  11337. } else if (event.key === "Tab") {
  11338. commitKey = 3;
  11339. }
  11340. if (commitKey === -1) {
  11341. return;
  11342. }
  11343. const {
  11344. value
  11345. } = event.target;
  11346. if (elementData.valueOnFocus === value) {
  11347. return;
  11348. }
  11349. elementData.userValue = value;
  11350. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11351. source: this,
  11352. detail: {
  11353. id,
  11354. name: "Keystroke",
  11355. value,
  11356. willCommit: true,
  11357. commitKey,
  11358. selStart: event.target.selectionStart,
  11359. selEnd: event.target.selectionEnd
  11360. }
  11361. });
  11362. });
  11363. const _blurListener = blurListener;
  11364. blurListener = null;
  11365. element.addEventListener("blur", event => {
  11366. const {
  11367. value
  11368. } = event.target;
  11369. elementData.userValue = value;
  11370. if (this._mouseState.isDown && elementData.valueOnFocus !== value) {
  11371. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11372. source: this,
  11373. detail: {
  11374. id,
  11375. name: "Keystroke",
  11376. value,
  11377. willCommit: true,
  11378. commitKey: 1,
  11379. selStart: event.target.selectionStart,
  11380. selEnd: event.target.selectionEnd
  11381. }
  11382. });
  11383. }
  11384. _blurListener(event);
  11385. });
  11386. if (this.data.actions?.Keystroke) {
  11387. element.addEventListener("beforeinput", event => {
  11388. const {
  11389. data,
  11390. target
  11391. } = event;
  11392. const {
  11393. value,
  11394. selectionStart,
  11395. selectionEnd
  11396. } = target;
  11397. let selStart = selectionStart,
  11398. selEnd = selectionEnd;
  11399. switch (event.inputType) {
  11400. case "deleteWordBackward":
  11401. {
  11402. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  11403. if (match) {
  11404. selStart -= match[0].length;
  11405. }
  11406. break;
  11407. }
  11408. case "deleteWordForward":
  11409. {
  11410. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  11411. if (match) {
  11412. selEnd += match[0].length;
  11413. }
  11414. break;
  11415. }
  11416. case "deleteContentBackward":
  11417. if (selectionStart === selectionEnd) {
  11418. selStart -= 1;
  11419. }
  11420. break;
  11421. case "deleteContentForward":
  11422. if (selectionStart === selectionEnd) {
  11423. selEnd += 1;
  11424. }
  11425. break;
  11426. }
  11427. event.preventDefault();
  11428. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11429. source: this,
  11430. detail: {
  11431. id,
  11432. name: "Keystroke",
  11433. value,
  11434. change: data || "",
  11435. willCommit: false,
  11436. selStart,
  11437. selEnd
  11438. }
  11439. });
  11440. });
  11441. }
  11442. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  11443. }
  11444. if (blurListener) {
  11445. element.addEventListener("blur", blurListener);
  11446. }
  11447. if (this.data.maxLen !== null) {
  11448. element.maxLength = this.data.maxLen;
  11449. }
  11450. if (this.data.comb) {
  11451. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  11452. const combWidth = fieldWidth / this.data.maxLen;
  11453. element.classList.add("comb");
  11454. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  11455. }
  11456. } else {
  11457. element = document.createElement("div");
  11458. element.textContent = this.data.fieldValue;
  11459. element.style.verticalAlign = "middle";
  11460. element.style.display = "table-cell";
  11461. }
  11462. this._setTextStyle(element);
  11463. this._setBackgroundColor(element);
  11464. this._setDefaultPropertiesFromJS(element);
  11465. this.container.append(element);
  11466. return this.container;
  11467. }
  11468. }
  11469. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  11470. constructor(parameters) {
  11471. super(parameters, {
  11472. isRenderable: parameters.renderForms
  11473. });
  11474. }
  11475. render() {
  11476. const storage = this.annotationStorage;
  11477. const data = this.data;
  11478. const id = data.id;
  11479. let value = storage.getValue(id, {
  11480. value: data.exportValue === data.fieldValue
  11481. }).value;
  11482. if (typeof value === "string") {
  11483. value = value !== "Off";
  11484. storage.setValue(id, {
  11485. value
  11486. });
  11487. }
  11488. this.container.className = "buttonWidgetAnnotation checkBox";
  11489. const element = document.createElement("input");
  11490. GetElementsByNameSet.add(element);
  11491. element.setAttribute("data-element-id", id);
  11492. element.disabled = data.readOnly;
  11493. this._setRequired(element, this.data.required);
  11494. element.type = "checkbox";
  11495. element.name = data.fieldName;
  11496. if (value) {
  11497. element.setAttribute("checked", true);
  11498. }
  11499. element.setAttribute("exportValue", data.exportValue);
  11500. element.tabIndex = DEFAULT_TAB_INDEX;
  11501. element.addEventListener("change", event => {
  11502. const {
  11503. name,
  11504. checked
  11505. } = event.target;
  11506. for (const checkbox of this._getElementsByName(name, id)) {
  11507. const curChecked = checked && checkbox.exportValue === data.exportValue;
  11508. if (checkbox.domElement) {
  11509. checkbox.domElement.checked = curChecked;
  11510. }
  11511. storage.setValue(checkbox.id, {
  11512. value: curChecked
  11513. });
  11514. }
  11515. storage.setValue(id, {
  11516. value: checked
  11517. });
  11518. });
  11519. element.addEventListener("resetform", event => {
  11520. const defaultValue = data.defaultFieldValue || "Off";
  11521. event.target.checked = defaultValue === data.exportValue;
  11522. });
  11523. if (this.enableScripting && this.hasJSActions) {
  11524. element.addEventListener("updatefromsandbox", jsEvent => {
  11525. const actions = {
  11526. value(event) {
  11527. event.target.checked = event.detail.value !== "Off";
  11528. storage.setValue(id, {
  11529. value: event.target.checked
  11530. });
  11531. }
  11532. };
  11533. this._dispatchEventFromSandbox(actions, jsEvent);
  11534. });
  11535. 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);
  11536. }
  11537. this._setBackgroundColor(element);
  11538. this._setDefaultPropertiesFromJS(element);
  11539. this.container.append(element);
  11540. return this.container;
  11541. }
  11542. }
  11543. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  11544. constructor(parameters) {
  11545. super(parameters, {
  11546. isRenderable: parameters.renderForms
  11547. });
  11548. }
  11549. render() {
  11550. this.container.className = "buttonWidgetAnnotation radioButton";
  11551. const storage = this.annotationStorage;
  11552. const data = this.data;
  11553. const id = data.id;
  11554. let value = storage.getValue(id, {
  11555. value: data.fieldValue === data.buttonValue
  11556. }).value;
  11557. if (typeof value === "string") {
  11558. value = value !== data.buttonValue;
  11559. storage.setValue(id, {
  11560. value
  11561. });
  11562. }
  11563. const element = document.createElement("input");
  11564. GetElementsByNameSet.add(element);
  11565. element.setAttribute("data-element-id", id);
  11566. element.disabled = data.readOnly;
  11567. this._setRequired(element, this.data.required);
  11568. element.type = "radio";
  11569. element.name = data.fieldName;
  11570. if (value) {
  11571. element.setAttribute("checked", true);
  11572. }
  11573. element.tabIndex = DEFAULT_TAB_INDEX;
  11574. element.addEventListener("change", event => {
  11575. const {
  11576. name,
  11577. checked
  11578. } = event.target;
  11579. for (const radio of this._getElementsByName(name, id)) {
  11580. storage.setValue(radio.id, {
  11581. value: false
  11582. });
  11583. }
  11584. storage.setValue(id, {
  11585. value: checked
  11586. });
  11587. });
  11588. element.addEventListener("resetform", event => {
  11589. const defaultValue = data.defaultFieldValue;
  11590. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  11591. });
  11592. if (this.enableScripting && this.hasJSActions) {
  11593. const pdfButtonValue = data.buttonValue;
  11594. element.addEventListener("updatefromsandbox", jsEvent => {
  11595. const actions = {
  11596. value: event => {
  11597. const checked = pdfButtonValue === event.detail.value;
  11598. for (const radio of this._getElementsByName(event.target.name)) {
  11599. const curChecked = checked && radio.id === id;
  11600. if (radio.domElement) {
  11601. radio.domElement.checked = curChecked;
  11602. }
  11603. storage.setValue(radio.id, {
  11604. value: curChecked
  11605. });
  11606. }
  11607. }
  11608. };
  11609. this._dispatchEventFromSandbox(actions, jsEvent);
  11610. });
  11611. 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);
  11612. }
  11613. this._setBackgroundColor(element);
  11614. this._setDefaultPropertiesFromJS(element);
  11615. this.container.append(element);
  11616. return this.container;
  11617. }
  11618. }
  11619. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  11620. constructor(parameters) {
  11621. super(parameters, {
  11622. ignoreBorder: parameters.data.hasAppearance
  11623. });
  11624. }
  11625. render() {
  11626. const container = super.render();
  11627. container.className = "buttonWidgetAnnotation pushButton";
  11628. if (this.data.alternativeText) {
  11629. container.title = this.data.alternativeText;
  11630. }
  11631. const linkElement = container.lastChild;
  11632. if (this.enableScripting && this.hasJSActions && linkElement) {
  11633. this._setDefaultPropertiesFromJS(linkElement);
  11634. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  11635. this._dispatchEventFromSandbox({}, jsEvent);
  11636. });
  11637. }
  11638. return container;
  11639. }
  11640. }
  11641. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  11642. constructor(parameters) {
  11643. super(parameters, {
  11644. isRenderable: parameters.renderForms
  11645. });
  11646. }
  11647. render() {
  11648. this.container.className = "choiceWidgetAnnotation";
  11649. const storage = this.annotationStorage;
  11650. const id = this.data.id;
  11651. const storedData = storage.getValue(id, {
  11652. value: this.data.fieldValue
  11653. });
  11654. const selectElement = document.createElement("select");
  11655. GetElementsByNameSet.add(selectElement);
  11656. selectElement.setAttribute("data-element-id", id);
  11657. selectElement.disabled = this.data.readOnly;
  11658. this._setRequired(selectElement, this.data.required);
  11659. selectElement.name = this.data.fieldName;
  11660. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  11661. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  11662. if (!this.data.combo) {
  11663. selectElement.size = this.data.options.length;
  11664. if (this.data.multiSelect) {
  11665. selectElement.multiple = true;
  11666. }
  11667. }
  11668. selectElement.addEventListener("resetform", event => {
  11669. const defaultValue = this.data.defaultFieldValue;
  11670. for (const option of selectElement.options) {
  11671. option.selected = option.value === defaultValue;
  11672. }
  11673. });
  11674. for (const option of this.data.options) {
  11675. const optionElement = document.createElement("option");
  11676. optionElement.textContent = option.displayValue;
  11677. optionElement.value = option.exportValue;
  11678. if (storedData.value.includes(option.exportValue)) {
  11679. optionElement.setAttribute("selected", true);
  11680. addAnEmptyEntry = false;
  11681. }
  11682. selectElement.append(optionElement);
  11683. }
  11684. let removeEmptyEntry = null;
  11685. if (addAnEmptyEntry) {
  11686. const noneOptionElement = document.createElement("option");
  11687. noneOptionElement.value = " ";
  11688. noneOptionElement.setAttribute("hidden", true);
  11689. noneOptionElement.setAttribute("selected", true);
  11690. selectElement.prepend(noneOptionElement);
  11691. removeEmptyEntry = () => {
  11692. noneOptionElement.remove();
  11693. selectElement.removeEventListener("input", removeEmptyEntry);
  11694. removeEmptyEntry = null;
  11695. };
  11696. selectElement.addEventListener("input", removeEmptyEntry);
  11697. }
  11698. const getValue = (event, isExport) => {
  11699. const name = isExport ? "value" : "textContent";
  11700. const options = event.target.options;
  11701. if (!event.target.multiple) {
  11702. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  11703. }
  11704. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  11705. };
  11706. const getItems = event => {
  11707. const options = event.target.options;
  11708. return Array.prototype.map.call(options, option => {
  11709. return {
  11710. displayValue: option.textContent,
  11711. exportValue: option.value
  11712. };
  11713. });
  11714. };
  11715. if (this.enableScripting && this.hasJSActions) {
  11716. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  11717. const actions = {
  11718. value(event) {
  11719. removeEmptyEntry?.();
  11720. const value = event.detail.value;
  11721. const values = new Set(Array.isArray(value) ? value : [value]);
  11722. for (const option of selectElement.options) {
  11723. option.selected = values.has(option.value);
  11724. }
  11725. storage.setValue(id, {
  11726. value: getValue(event, true)
  11727. });
  11728. },
  11729. multipleSelection(event) {
  11730. selectElement.multiple = true;
  11731. },
  11732. remove(event) {
  11733. const options = selectElement.options;
  11734. const index = event.detail.remove;
  11735. options[index].selected = false;
  11736. selectElement.remove(index);
  11737. if (options.length > 0) {
  11738. const i = Array.prototype.findIndex.call(options, option => option.selected);
  11739. if (i === -1) {
  11740. options[0].selected = true;
  11741. }
  11742. }
  11743. storage.setValue(id, {
  11744. value: getValue(event, true),
  11745. items: getItems(event)
  11746. });
  11747. },
  11748. clear(event) {
  11749. while (selectElement.length !== 0) {
  11750. selectElement.remove(0);
  11751. }
  11752. storage.setValue(id, {
  11753. value: null,
  11754. items: []
  11755. });
  11756. },
  11757. insert(event) {
  11758. const {
  11759. index,
  11760. displayValue,
  11761. exportValue
  11762. } = event.detail.insert;
  11763. const selectChild = selectElement.children[index];
  11764. const optionElement = document.createElement("option");
  11765. optionElement.textContent = displayValue;
  11766. optionElement.value = exportValue;
  11767. if (selectChild) {
  11768. selectChild.before(optionElement);
  11769. } else {
  11770. selectElement.append(optionElement);
  11771. }
  11772. storage.setValue(id, {
  11773. value: getValue(event, true),
  11774. items: getItems(event)
  11775. });
  11776. },
  11777. items(event) {
  11778. const {
  11779. items
  11780. } = event.detail;
  11781. while (selectElement.length !== 0) {
  11782. selectElement.remove(0);
  11783. }
  11784. for (const item of items) {
  11785. const {
  11786. displayValue,
  11787. exportValue
  11788. } = item;
  11789. const optionElement = document.createElement("option");
  11790. optionElement.textContent = displayValue;
  11791. optionElement.value = exportValue;
  11792. selectElement.append(optionElement);
  11793. }
  11794. if (selectElement.options.length > 0) {
  11795. selectElement.options[0].selected = true;
  11796. }
  11797. storage.setValue(id, {
  11798. value: getValue(event, true),
  11799. items: getItems(event)
  11800. });
  11801. },
  11802. indices(event) {
  11803. const indices = new Set(event.detail.indices);
  11804. for (const option of event.target.options) {
  11805. option.selected = indices.has(option.index);
  11806. }
  11807. storage.setValue(id, {
  11808. value: getValue(event, true)
  11809. });
  11810. },
  11811. editable(event) {
  11812. event.target.disabled = !event.detail.editable;
  11813. }
  11814. };
  11815. this._dispatchEventFromSandbox(actions, jsEvent);
  11816. });
  11817. selectElement.addEventListener("input", event => {
  11818. const exportValue = getValue(event, true);
  11819. const value = getValue(event, false);
  11820. storage.setValue(id, {
  11821. value: exportValue
  11822. });
  11823. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11824. source: this,
  11825. detail: {
  11826. id,
  11827. name: "Keystroke",
  11828. value,
  11829. changeEx: exportValue,
  11830. willCommit: true,
  11831. commitKey: 1,
  11832. keyDown: false
  11833. }
  11834. });
  11835. });
  11836. 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);
  11837. } else {
  11838. selectElement.addEventListener("input", function (event) {
  11839. storage.setValue(id, {
  11840. value: getValue(event, true)
  11841. });
  11842. });
  11843. }
  11844. if (this.data.combo) {
  11845. this._setTextStyle(selectElement);
  11846. } else {}
  11847. this._setBackgroundColor(selectElement);
  11848. this._setDefaultPropertiesFromJS(selectElement);
  11849. this.container.append(selectElement);
  11850. return this.container;
  11851. }
  11852. }
  11853. class PopupAnnotationElement extends AnnotationElement {
  11854. constructor(parameters) {
  11855. const isRenderable = !!(parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11856. super(parameters, {
  11857. isRenderable
  11858. });
  11859. }
  11860. render() {
  11861. const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"];
  11862. this.container.className = "popupAnnotation";
  11863. if (IGNORE_TYPES.includes(this.data.parentType)) {
  11864. return this.container;
  11865. }
  11866. const selector = `[data-annotation-id="${this.data.parentId}"]`;
  11867. const parentElements = this.layer.querySelectorAll(selector);
  11868. if (parentElements.length === 0) {
  11869. return this.container;
  11870. }
  11871. const popup = new PopupElement({
  11872. container: this.container,
  11873. trigger: Array.from(parentElements),
  11874. color: this.data.color,
  11875. titleObj: this.data.titleObj,
  11876. modificationDate: this.data.modificationDate,
  11877. contentsObj: this.data.contentsObj,
  11878. richText: this.data.richText
  11879. });
  11880. const page = this.page;
  11881. 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]]);
  11882. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  11883. const popupTop = rect[1];
  11884. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  11885. const pageWidth = pageURx - pageLLx;
  11886. const pageHeight = pageURy - pageLLy;
  11887. this.container.style.left = `${100 * (popupLeft - pageLLx) / pageWidth}%`;
  11888. this.container.style.top = `${100 * (popupTop - pageLLy) / pageHeight}%`;
  11889. this.container.append(popup.render());
  11890. return this.container;
  11891. }
  11892. }
  11893. class PopupElement {
  11894. constructor(parameters) {
  11895. this.container = parameters.container;
  11896. this.trigger = parameters.trigger;
  11897. this.color = parameters.color;
  11898. this.titleObj = parameters.titleObj;
  11899. this.modificationDate = parameters.modificationDate;
  11900. this.contentsObj = parameters.contentsObj;
  11901. this.richText = parameters.richText;
  11902. this.hideWrapper = parameters.hideWrapper || false;
  11903. this.pinned = false;
  11904. }
  11905. render() {
  11906. const BACKGROUND_ENLIGHT = 0.7;
  11907. const wrapper = document.createElement("div");
  11908. wrapper.className = "popupWrapper";
  11909. this.hideElement = this.hideWrapper ? wrapper : this.container;
  11910. this.hideElement.hidden = true;
  11911. const popup = document.createElement("div");
  11912. popup.className = "popup";
  11913. const color = this.color;
  11914. if (color) {
  11915. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  11916. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  11917. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  11918. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  11919. }
  11920. const title = document.createElement("h1");
  11921. title.dir = this.titleObj.dir;
  11922. title.textContent = this.titleObj.str;
  11923. popup.append(title);
  11924. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  11925. if (dateObject) {
  11926. const modificationDate = document.createElement("span");
  11927. modificationDate.className = "popupDate";
  11928. modificationDate.textContent = "{{date}}, {{time}}";
  11929. modificationDate.dataset.l10nId = "annotation_date_string";
  11930. modificationDate.dataset.l10nArgs = JSON.stringify({
  11931. date: dateObject.toLocaleDateString(),
  11932. time: dateObject.toLocaleTimeString()
  11933. });
  11934. popup.append(modificationDate);
  11935. }
  11936. if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
  11937. _xfa_layer.XfaLayer.render({
  11938. xfaHtml: this.richText.html,
  11939. intent: "richText",
  11940. div: popup
  11941. });
  11942. popup.lastChild.className = "richText popupContent";
  11943. } else {
  11944. const contents = this._formatContents(this.contentsObj);
  11945. popup.append(contents);
  11946. }
  11947. if (!Array.isArray(this.trigger)) {
  11948. this.trigger = [this.trigger];
  11949. }
  11950. for (const element of this.trigger) {
  11951. element.addEventListener("click", this._toggle.bind(this));
  11952. element.addEventListener("mouseover", this._show.bind(this, false));
  11953. element.addEventListener("mouseout", this._hide.bind(this, false));
  11954. }
  11955. popup.addEventListener("click", this._hide.bind(this, true));
  11956. wrapper.append(popup);
  11957. return wrapper;
  11958. }
  11959. _formatContents({
  11960. str,
  11961. dir
  11962. }) {
  11963. const p = document.createElement("p");
  11964. p.className = "popupContent";
  11965. p.dir = dir;
  11966. const lines = str.split(/(?:\r\n?|\n)/);
  11967. for (let i = 0, ii = lines.length; i < ii; ++i) {
  11968. const line = lines[i];
  11969. p.append(document.createTextNode(line));
  11970. if (i < ii - 1) {
  11971. p.append(document.createElement("br"));
  11972. }
  11973. }
  11974. return p;
  11975. }
  11976. _toggle() {
  11977. if (this.pinned) {
  11978. this._hide(true);
  11979. } else {
  11980. this._show(true);
  11981. }
  11982. }
  11983. _show(pin = false) {
  11984. if (pin) {
  11985. this.pinned = true;
  11986. }
  11987. if (this.hideElement.hidden) {
  11988. this.hideElement.hidden = false;
  11989. this.container.style.zIndex += 1;
  11990. }
  11991. }
  11992. _hide(unpin = true) {
  11993. if (unpin) {
  11994. this.pinned = false;
  11995. }
  11996. if (!this.hideElement.hidden && !this.pinned) {
  11997. this.hideElement.hidden = true;
  11998. this.container.style.zIndex -= 1;
  11999. }
  12000. }
  12001. }
  12002. class FreeTextAnnotationElement extends AnnotationElement {
  12003. constructor(parameters) {
  12004. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12005. super(parameters, {
  12006. isRenderable,
  12007. ignoreBorder: true
  12008. });
  12009. }
  12010. render() {
  12011. this.container.className = "freeTextAnnotation";
  12012. if (!this.data.hasPopup) {
  12013. this._createPopup(null, this.data);
  12014. }
  12015. return this.container;
  12016. }
  12017. }
  12018. class LineAnnotationElement extends AnnotationElement {
  12019. constructor(parameters) {
  12020. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12021. super(parameters, {
  12022. isRenderable,
  12023. ignoreBorder: true
  12024. });
  12025. }
  12026. render() {
  12027. this.container.className = "lineAnnotation";
  12028. const data = this.data;
  12029. const {
  12030. width,
  12031. height
  12032. } = getRectDims(data.rect);
  12033. const svg = this.svgFactory.create(width, height, true);
  12034. const line = this.svgFactory.createElement("svg:line");
  12035. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  12036. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  12037. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  12038. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  12039. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  12040. line.setAttribute("stroke", "transparent");
  12041. line.setAttribute("fill", "transparent");
  12042. svg.append(line);
  12043. this.container.append(svg);
  12044. this._createPopup(line, data);
  12045. return this.container;
  12046. }
  12047. }
  12048. class SquareAnnotationElement extends AnnotationElement {
  12049. constructor(parameters) {
  12050. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12051. super(parameters, {
  12052. isRenderable,
  12053. ignoreBorder: true
  12054. });
  12055. }
  12056. render() {
  12057. this.container.className = "squareAnnotation";
  12058. const data = this.data;
  12059. const {
  12060. width,
  12061. height
  12062. } = getRectDims(data.rect);
  12063. const svg = this.svgFactory.create(width, height, true);
  12064. const borderWidth = data.borderStyle.width;
  12065. const square = this.svgFactory.createElement("svg:rect");
  12066. square.setAttribute("x", borderWidth / 2);
  12067. square.setAttribute("y", borderWidth / 2);
  12068. square.setAttribute("width", width - borderWidth);
  12069. square.setAttribute("height", height - borderWidth);
  12070. square.setAttribute("stroke-width", borderWidth || 1);
  12071. square.setAttribute("stroke", "transparent");
  12072. square.setAttribute("fill", "transparent");
  12073. svg.append(square);
  12074. this.container.append(svg);
  12075. this._createPopup(square, data);
  12076. return this.container;
  12077. }
  12078. }
  12079. class CircleAnnotationElement extends AnnotationElement {
  12080. constructor(parameters) {
  12081. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12082. super(parameters, {
  12083. isRenderable,
  12084. ignoreBorder: true
  12085. });
  12086. }
  12087. render() {
  12088. this.container.className = "circleAnnotation";
  12089. const data = this.data;
  12090. const {
  12091. width,
  12092. height
  12093. } = getRectDims(data.rect);
  12094. const svg = this.svgFactory.create(width, height, true);
  12095. const borderWidth = data.borderStyle.width;
  12096. const circle = this.svgFactory.createElement("svg:ellipse");
  12097. circle.setAttribute("cx", width / 2);
  12098. circle.setAttribute("cy", height / 2);
  12099. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  12100. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  12101. circle.setAttribute("stroke-width", borderWidth || 1);
  12102. circle.setAttribute("stroke", "transparent");
  12103. circle.setAttribute("fill", "transparent");
  12104. svg.append(circle);
  12105. this.container.append(svg);
  12106. this._createPopup(circle, data);
  12107. return this.container;
  12108. }
  12109. }
  12110. class PolylineAnnotationElement extends AnnotationElement {
  12111. constructor(parameters) {
  12112. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12113. super(parameters, {
  12114. isRenderable,
  12115. ignoreBorder: true
  12116. });
  12117. this.containerClassName = "polylineAnnotation";
  12118. this.svgElementName = "svg:polyline";
  12119. }
  12120. render() {
  12121. this.container.className = this.containerClassName;
  12122. const data = this.data;
  12123. const {
  12124. width,
  12125. height
  12126. } = getRectDims(data.rect);
  12127. const svg = this.svgFactory.create(width, height, true);
  12128. let points = [];
  12129. for (const coordinate of data.vertices) {
  12130. const x = coordinate.x - data.rect[0];
  12131. const y = data.rect[3] - coordinate.y;
  12132. points.push(x + "," + y);
  12133. }
  12134. points = points.join(" ");
  12135. const polyline = this.svgFactory.createElement(this.svgElementName);
  12136. polyline.setAttribute("points", points);
  12137. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  12138. polyline.setAttribute("stroke", "transparent");
  12139. polyline.setAttribute("fill", "transparent");
  12140. svg.append(polyline);
  12141. this.container.append(svg);
  12142. this._createPopup(polyline, data);
  12143. return this.container;
  12144. }
  12145. }
  12146. class PolygonAnnotationElement extends PolylineAnnotationElement {
  12147. constructor(parameters) {
  12148. super(parameters);
  12149. this.containerClassName = "polygonAnnotation";
  12150. this.svgElementName = "svg:polygon";
  12151. }
  12152. }
  12153. class CaretAnnotationElement extends AnnotationElement {
  12154. constructor(parameters) {
  12155. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12156. super(parameters, {
  12157. isRenderable,
  12158. ignoreBorder: true
  12159. });
  12160. }
  12161. render() {
  12162. this.container.className = "caretAnnotation";
  12163. if (!this.data.hasPopup) {
  12164. this._createPopup(null, this.data);
  12165. }
  12166. return this.container;
  12167. }
  12168. }
  12169. class InkAnnotationElement extends AnnotationElement {
  12170. constructor(parameters) {
  12171. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12172. super(parameters, {
  12173. isRenderable,
  12174. ignoreBorder: true
  12175. });
  12176. this.containerClassName = "inkAnnotation";
  12177. this.svgElementName = "svg:polyline";
  12178. }
  12179. render() {
  12180. this.container.className = this.containerClassName;
  12181. const data = this.data;
  12182. const {
  12183. width,
  12184. height
  12185. } = getRectDims(data.rect);
  12186. const svg = this.svgFactory.create(width, height, true);
  12187. for (const inkList of data.inkLists) {
  12188. let points = [];
  12189. for (const coordinate of inkList) {
  12190. const x = coordinate.x - data.rect[0];
  12191. const y = data.rect[3] - coordinate.y;
  12192. points.push(`${x},${y}`);
  12193. }
  12194. points = points.join(" ");
  12195. const polyline = this.svgFactory.createElement(this.svgElementName);
  12196. polyline.setAttribute("points", points);
  12197. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  12198. polyline.setAttribute("stroke", "transparent");
  12199. polyline.setAttribute("fill", "transparent");
  12200. this._createPopup(polyline, data);
  12201. svg.append(polyline);
  12202. }
  12203. this.container.append(svg);
  12204. return this.container;
  12205. }
  12206. }
  12207. class HighlightAnnotationElement extends AnnotationElement {
  12208. constructor(parameters) {
  12209. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12210. super(parameters, {
  12211. isRenderable,
  12212. ignoreBorder: true,
  12213. createQuadrilaterals: true
  12214. });
  12215. }
  12216. render() {
  12217. if (!this.data.hasPopup) {
  12218. this._createPopup(null, this.data);
  12219. }
  12220. if (this.quadrilaterals) {
  12221. return this._renderQuadrilaterals("highlightAnnotation");
  12222. }
  12223. this.container.className = "highlightAnnotation";
  12224. return this.container;
  12225. }
  12226. }
  12227. class UnderlineAnnotationElement extends AnnotationElement {
  12228. constructor(parameters) {
  12229. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12230. super(parameters, {
  12231. isRenderable,
  12232. ignoreBorder: true,
  12233. createQuadrilaterals: true
  12234. });
  12235. }
  12236. render() {
  12237. if (!this.data.hasPopup) {
  12238. this._createPopup(null, this.data);
  12239. }
  12240. if (this.quadrilaterals) {
  12241. return this._renderQuadrilaterals("underlineAnnotation");
  12242. }
  12243. this.container.className = "underlineAnnotation";
  12244. return this.container;
  12245. }
  12246. }
  12247. class SquigglyAnnotationElement extends AnnotationElement {
  12248. constructor(parameters) {
  12249. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12250. super(parameters, {
  12251. isRenderable,
  12252. ignoreBorder: true,
  12253. createQuadrilaterals: true
  12254. });
  12255. }
  12256. render() {
  12257. if (!this.data.hasPopup) {
  12258. this._createPopup(null, this.data);
  12259. }
  12260. if (this.quadrilaterals) {
  12261. return this._renderQuadrilaterals("squigglyAnnotation");
  12262. }
  12263. this.container.className = "squigglyAnnotation";
  12264. return this.container;
  12265. }
  12266. }
  12267. class StrikeOutAnnotationElement extends AnnotationElement {
  12268. constructor(parameters) {
  12269. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12270. super(parameters, {
  12271. isRenderable,
  12272. ignoreBorder: true,
  12273. createQuadrilaterals: true
  12274. });
  12275. }
  12276. render() {
  12277. if (!this.data.hasPopup) {
  12278. this._createPopup(null, this.data);
  12279. }
  12280. if (this.quadrilaterals) {
  12281. return this._renderQuadrilaterals("strikeoutAnnotation");
  12282. }
  12283. this.container.className = "strikeoutAnnotation";
  12284. return this.container;
  12285. }
  12286. }
  12287. class StampAnnotationElement extends AnnotationElement {
  12288. constructor(parameters) {
  12289. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12290. super(parameters, {
  12291. isRenderable,
  12292. ignoreBorder: true
  12293. });
  12294. }
  12295. render() {
  12296. this.container.className = "stampAnnotation";
  12297. if (!this.data.hasPopup) {
  12298. this._createPopup(null, this.data);
  12299. }
  12300. return this.container;
  12301. }
  12302. }
  12303. class FileAttachmentAnnotationElement extends AnnotationElement {
  12304. constructor(parameters) {
  12305. super(parameters, {
  12306. isRenderable: true
  12307. });
  12308. const {
  12309. filename,
  12310. content
  12311. } = this.data.file;
  12312. this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
  12313. this.content = content;
  12314. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  12315. source: this,
  12316. filename,
  12317. content
  12318. });
  12319. }
  12320. render() {
  12321. this.container.className = "fileAttachmentAnnotation";
  12322. const trigger = document.createElement("div");
  12323. trigger.className = "popupTriggerArea";
  12324. trigger.addEventListener("dblclick", this._download.bind(this));
  12325. if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
  12326. this._createPopup(trigger, this.data);
  12327. }
  12328. this.container.append(trigger);
  12329. return this.container;
  12330. }
  12331. _download() {
  12332. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  12333. }
  12334. }
  12335. class AnnotationLayer {
  12336. static render(parameters) {
  12337. const {
  12338. annotations,
  12339. div,
  12340. viewport
  12341. } = parameters;
  12342. this.#setDimensions(div, viewport);
  12343. const sortedAnnotations = [],
  12344. popupAnnotations = [];
  12345. for (const data of annotations) {
  12346. if (!data) {
  12347. continue;
  12348. }
  12349. if (data.annotationType === _util.AnnotationType.POPUP) {
  12350. popupAnnotations.push(data);
  12351. continue;
  12352. }
  12353. const {
  12354. width,
  12355. height
  12356. } = getRectDims(data.rect);
  12357. if (width <= 0 || height <= 0) {
  12358. continue;
  12359. }
  12360. sortedAnnotations.push(data);
  12361. }
  12362. if (popupAnnotations.length) {
  12363. sortedAnnotations.push(...popupAnnotations);
  12364. }
  12365. for (const data of sortedAnnotations) {
  12366. const element = AnnotationElementFactory.create({
  12367. data,
  12368. layer: div,
  12369. page: parameters.page,
  12370. viewport,
  12371. linkService: parameters.linkService,
  12372. downloadManager: parameters.downloadManager,
  12373. imageResourcesPath: parameters.imageResourcesPath || "",
  12374. renderForms: parameters.renderForms !== false,
  12375. svgFactory: new _display_utils.DOMSVGFactory(),
  12376. annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
  12377. enableScripting: parameters.enableScripting,
  12378. hasJSActions: parameters.hasJSActions,
  12379. fieldObjects: parameters.fieldObjects,
  12380. mouseState: parameters.mouseState || {
  12381. isDown: false
  12382. }
  12383. });
  12384. if (element.isRenderable) {
  12385. const rendered = element.render();
  12386. if (data.hidden) {
  12387. rendered.style.visibility = "hidden";
  12388. }
  12389. if (Array.isArray(rendered)) {
  12390. for (const renderedElement of rendered) {
  12391. div.append(renderedElement);
  12392. }
  12393. } else {
  12394. if (element instanceof PopupAnnotationElement) {
  12395. div.prepend(rendered);
  12396. } else {
  12397. div.append(rendered);
  12398. }
  12399. }
  12400. }
  12401. }
  12402. this.#setAnnotationCanvasMap(div, parameters.annotationCanvasMap);
  12403. }
  12404. static update(parameters) {
  12405. const {
  12406. annotationCanvasMap,
  12407. div,
  12408. viewport
  12409. } = parameters;
  12410. this.#setDimensions(div, viewport);
  12411. this.#setAnnotationCanvasMap(div, annotationCanvasMap);
  12412. div.hidden = false;
  12413. }
  12414. static #setDimensions(div, {
  12415. width,
  12416. height,
  12417. rotation
  12418. }) {
  12419. const {
  12420. style
  12421. } = div;
  12422. const flipOrientation = rotation % 180 !== 0,
  12423. widthStr = Math.floor(width) + "px",
  12424. heightStr = Math.floor(height) + "px";
  12425. style.width = flipOrientation ? heightStr : widthStr;
  12426. style.height = flipOrientation ? widthStr : heightStr;
  12427. div.setAttribute("data-main-rotation", rotation);
  12428. }
  12429. static #setAnnotationCanvasMap(div, annotationCanvasMap) {
  12430. if (!annotationCanvasMap) {
  12431. return;
  12432. }
  12433. for (const [id, canvas] of annotationCanvasMap) {
  12434. const element = div.querySelector(`[data-annotation-id="${id}"]`);
  12435. if (!element) {
  12436. continue;
  12437. }
  12438. const {
  12439. firstChild
  12440. } = element;
  12441. if (!firstChild) {
  12442. element.append(canvas);
  12443. } else if (firstChild.nodeName === "CANVAS") {
  12444. firstChild.replaceWith(canvas);
  12445. } else {
  12446. firstChild.before(canvas);
  12447. }
  12448. }
  12449. annotationCanvasMap.clear();
  12450. }
  12451. }
  12452. exports.AnnotationLayer = AnnotationLayer;
  12453. /***/ }),
  12454. /* 28 */
  12455. /***/ ((__unused_webpack_module, exports) => {
  12456. Object.defineProperty(exports, "__esModule", ({
  12457. value: true
  12458. }));
  12459. exports.ColorConverters = void 0;
  12460. function makeColorComp(n) {
  12461. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  12462. }
  12463. class ColorConverters {
  12464. static CMYK_G([c, y, m, k]) {
  12465. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  12466. }
  12467. static G_CMYK([g]) {
  12468. return ["CMYK", 0, 0, 0, 1 - g];
  12469. }
  12470. static G_RGB([g]) {
  12471. return ["RGB", g, g, g];
  12472. }
  12473. static G_HTML([g]) {
  12474. const G = makeColorComp(g);
  12475. return `#${G}${G}${G}`;
  12476. }
  12477. static RGB_G([r, g, b]) {
  12478. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  12479. }
  12480. static RGB_HTML([r, g, b]) {
  12481. const R = makeColorComp(r);
  12482. const G = makeColorComp(g);
  12483. const B = makeColorComp(b);
  12484. return `#${R}${G}${B}`;
  12485. }
  12486. static T_HTML() {
  12487. return "#00000000";
  12488. }
  12489. static CMYK_RGB([c, y, m, k]) {
  12490. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  12491. }
  12492. static CMYK_HTML(components) {
  12493. const rgb = this.CMYK_RGB(components).slice(1);
  12494. return this.RGB_HTML(rgb);
  12495. }
  12496. static RGB_CMYK([r, g, b]) {
  12497. const c = 1 - r;
  12498. const m = 1 - g;
  12499. const y = 1 - b;
  12500. const k = Math.min(c, m, y);
  12501. return ["CMYK", c, m, y, k];
  12502. }
  12503. }
  12504. exports.ColorConverters = ColorConverters;
  12505. /***/ }),
  12506. /* 29 */
  12507. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12508. Object.defineProperty(exports, "__esModule", ({
  12509. value: true
  12510. }));
  12511. exports.XfaLayer = void 0;
  12512. var _xfa_text = __w_pdfjs_require__(20);
  12513. class XfaLayer {
  12514. static setupStorage(html, id, element, storage, intent) {
  12515. const storedData = storage.getValue(id, {
  12516. value: null
  12517. });
  12518. switch (element.name) {
  12519. case "textarea":
  12520. if (storedData.value !== null) {
  12521. html.textContent = storedData.value;
  12522. }
  12523. if (intent === "print") {
  12524. break;
  12525. }
  12526. html.addEventListener("input", event => {
  12527. storage.setValue(id, {
  12528. value: event.target.value
  12529. });
  12530. });
  12531. break;
  12532. case "input":
  12533. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  12534. if (storedData.value === element.attributes.xfaOn) {
  12535. html.setAttribute("checked", true);
  12536. } else if (storedData.value === element.attributes.xfaOff) {
  12537. html.removeAttribute("checked");
  12538. }
  12539. if (intent === "print") {
  12540. break;
  12541. }
  12542. html.addEventListener("change", event => {
  12543. storage.setValue(id, {
  12544. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  12545. });
  12546. });
  12547. } else {
  12548. if (storedData.value !== null) {
  12549. html.setAttribute("value", storedData.value);
  12550. }
  12551. if (intent === "print") {
  12552. break;
  12553. }
  12554. html.addEventListener("input", event => {
  12555. storage.setValue(id, {
  12556. value: event.target.value
  12557. });
  12558. });
  12559. }
  12560. break;
  12561. case "select":
  12562. if (storedData.value !== null) {
  12563. for (const option of element.children) {
  12564. if (option.attributes.value === storedData.value) {
  12565. option.attributes.selected = true;
  12566. }
  12567. }
  12568. }
  12569. html.addEventListener("input", event => {
  12570. const options = event.target.options;
  12571. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  12572. storage.setValue(id, {
  12573. value
  12574. });
  12575. });
  12576. break;
  12577. }
  12578. }
  12579. static setAttributes({
  12580. html,
  12581. element,
  12582. storage = null,
  12583. intent,
  12584. linkService
  12585. }) {
  12586. const {
  12587. attributes
  12588. } = element;
  12589. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  12590. if (attributes.type === "radio") {
  12591. attributes.name = `${attributes.name}-${intent}`;
  12592. }
  12593. for (const [key, value] of Object.entries(attributes)) {
  12594. if (value === null || value === undefined) {
  12595. continue;
  12596. }
  12597. switch (key) {
  12598. case "class":
  12599. if (value.length) {
  12600. html.setAttribute(key, value.join(" "));
  12601. }
  12602. break;
  12603. case "dataId":
  12604. break;
  12605. case "id":
  12606. html.setAttribute("data-element-id", value);
  12607. break;
  12608. case "style":
  12609. Object.assign(html.style, value);
  12610. break;
  12611. case "textContent":
  12612. html.textContent = value;
  12613. break;
  12614. default:
  12615. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  12616. html.setAttribute(key, value);
  12617. }
  12618. }
  12619. }
  12620. if (isHTMLAnchorElement) {
  12621. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  12622. }
  12623. if (storage && attributes.dataId) {
  12624. this.setupStorage(html, attributes.dataId, element, storage);
  12625. }
  12626. }
  12627. static render(parameters) {
  12628. const storage = parameters.annotationStorage;
  12629. const linkService = parameters.linkService;
  12630. const root = parameters.xfaHtml;
  12631. const intent = parameters.intent || "display";
  12632. const rootHtml = document.createElement(root.name);
  12633. if (root.attributes) {
  12634. this.setAttributes({
  12635. html: rootHtml,
  12636. element: root,
  12637. intent,
  12638. linkService
  12639. });
  12640. }
  12641. const stack = [[root, -1, rootHtml]];
  12642. const rootDiv = parameters.div;
  12643. rootDiv.append(rootHtml);
  12644. if (parameters.viewport) {
  12645. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12646. rootDiv.style.transform = transform;
  12647. }
  12648. if (intent !== "richText") {
  12649. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  12650. }
  12651. const textDivs = [];
  12652. while (stack.length > 0) {
  12653. const [parent, i, html] = stack.at(-1);
  12654. if (i + 1 === parent.children.length) {
  12655. stack.pop();
  12656. continue;
  12657. }
  12658. const child = parent.children[++stack.at(-1)[1]];
  12659. if (child === null) {
  12660. continue;
  12661. }
  12662. const {
  12663. name
  12664. } = child;
  12665. if (name === "#text") {
  12666. const node = document.createTextNode(child.value);
  12667. textDivs.push(node);
  12668. html.append(node);
  12669. continue;
  12670. }
  12671. let childHtml;
  12672. if (child?.attributes?.xmlns) {
  12673. childHtml = document.createElementNS(child.attributes.xmlns, name);
  12674. } else {
  12675. childHtml = document.createElement(name);
  12676. }
  12677. html.append(childHtml);
  12678. if (child.attributes) {
  12679. this.setAttributes({
  12680. html: childHtml,
  12681. element: child,
  12682. storage,
  12683. intent,
  12684. linkService
  12685. });
  12686. }
  12687. if (child.children && child.children.length > 0) {
  12688. stack.push([child, -1, childHtml]);
  12689. } else if (child.value) {
  12690. const node = document.createTextNode(child.value);
  12691. if (_xfa_text.XfaText.shouldBuildText(name)) {
  12692. textDivs.push(node);
  12693. }
  12694. childHtml.append(node);
  12695. }
  12696. }
  12697. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  12698. el.setAttribute("readOnly", true);
  12699. }
  12700. return {
  12701. textDivs
  12702. };
  12703. }
  12704. static update(parameters) {
  12705. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12706. parameters.div.style.transform = transform;
  12707. parameters.div.hidden = false;
  12708. }
  12709. }
  12710. exports.XfaLayer = XfaLayer;
  12711. /***/ }),
  12712. /* 30 */
  12713. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12714. Object.defineProperty(exports, "__esModule", ({
  12715. value: true
  12716. }));
  12717. exports.TextLayerRenderTask = void 0;
  12718. exports.renderTextLayer = renderTextLayer;
  12719. var _util = __w_pdfjs_require__(1);
  12720. var _display_utils = __w_pdfjs_require__(4);
  12721. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  12722. const DEFAULT_FONT_SIZE = 30;
  12723. const DEFAULT_FONT_ASCENT = 0.8;
  12724. const ascentCache = new Map();
  12725. const AllWhitespaceRegexp = /^\s+$/g;
  12726. function getAscent(fontFamily, ctx) {
  12727. const cachedAscent = ascentCache.get(fontFamily);
  12728. if (cachedAscent) {
  12729. return cachedAscent;
  12730. }
  12731. ctx.save();
  12732. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  12733. const metrics = ctx.measureText("");
  12734. let ascent = metrics.fontBoundingBoxAscent;
  12735. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  12736. if (ascent) {
  12737. ctx.restore();
  12738. const ratio = ascent / (ascent + descent);
  12739. ascentCache.set(fontFamily, ratio);
  12740. return ratio;
  12741. }
  12742. ctx.strokeStyle = "red";
  12743. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12744. ctx.strokeText("g", 0, 0);
  12745. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12746. descent = 0;
  12747. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  12748. if (pixels[i] > 0) {
  12749. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  12750. break;
  12751. }
  12752. }
  12753. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12754. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  12755. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12756. ascent = 0;
  12757. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  12758. if (pixels[i] > 0) {
  12759. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  12760. break;
  12761. }
  12762. }
  12763. ctx.restore();
  12764. if (ascent) {
  12765. const ratio = ascent / (ascent + descent);
  12766. ascentCache.set(fontFamily, ratio);
  12767. return ratio;
  12768. }
  12769. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  12770. return DEFAULT_FONT_ASCENT;
  12771. }
  12772. function appendText(task, geom, styles, ctx) {
  12773. const textDiv = document.createElement("span");
  12774. const textDivProperties = task._enhanceTextSelection ? {
  12775. angle: 0,
  12776. canvasWidth: 0,
  12777. hasText: geom.str !== "",
  12778. hasEOL: geom.hasEOL,
  12779. originalTransform: null,
  12780. paddingBottom: 0,
  12781. paddingLeft: 0,
  12782. paddingRight: 0,
  12783. paddingTop: 0,
  12784. scale: 1,
  12785. fontSize: 0
  12786. } : {
  12787. angle: 0,
  12788. canvasWidth: 0,
  12789. hasText: geom.str !== "",
  12790. hasEOL: geom.hasEOL,
  12791. fontSize: 0
  12792. };
  12793. task._textDivs.push(textDiv);
  12794. const tx = _util.Util.transform(task._viewport.transform, geom.transform);
  12795. let angle = Math.atan2(tx[1], tx[0]);
  12796. const style = styles[geom.fontName];
  12797. if (style.vertical) {
  12798. angle += Math.PI / 2;
  12799. }
  12800. const fontHeight = Math.hypot(tx[2], tx[3]);
  12801. const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
  12802. let left, top;
  12803. if (angle === 0) {
  12804. left = tx[4];
  12805. top = tx[5] - fontAscent;
  12806. } else {
  12807. left = tx[4] + fontAscent * Math.sin(angle);
  12808. top = tx[5] - fontAscent * Math.cos(angle);
  12809. }
  12810. textDiv.style.left = `${left}px`;
  12811. textDiv.style.top = `${top}px`;
  12812. textDiv.style.fontSize = `${fontHeight}px`;
  12813. textDiv.style.fontFamily = style.fontFamily;
  12814. textDivProperties.fontSize = fontHeight;
  12815. textDiv.setAttribute("role", "presentation");
  12816. textDiv.textContent = geom.str;
  12817. textDiv.dir = geom.dir;
  12818. if (task._fontInspectorEnabled) {
  12819. textDiv.dataset.fontName = geom.fontName;
  12820. }
  12821. if (angle !== 0) {
  12822. textDivProperties.angle = angle * (180 / Math.PI);
  12823. }
  12824. let shouldScaleText = false;
  12825. if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) {
  12826. shouldScaleText = true;
  12827. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  12828. const absScaleX = Math.abs(geom.transform[0]),
  12829. absScaleY = Math.abs(geom.transform[3]);
  12830. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  12831. shouldScaleText = true;
  12832. }
  12833. }
  12834. if (shouldScaleText) {
  12835. if (style.vertical) {
  12836. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  12837. } else {
  12838. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  12839. }
  12840. }
  12841. task._textDivProperties.set(textDiv, textDivProperties);
  12842. if (task._textContentStream) {
  12843. task._layoutText(textDiv);
  12844. }
  12845. if (task._enhanceTextSelection && textDivProperties.hasText) {
  12846. let angleCos = 1,
  12847. angleSin = 0;
  12848. if (angle !== 0) {
  12849. angleCos = Math.cos(angle);
  12850. angleSin = Math.sin(angle);
  12851. }
  12852. const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  12853. const divHeight = fontHeight;
  12854. let m, b;
  12855. if (angle !== 0) {
  12856. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  12857. b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  12858. } else {
  12859. b = [left, top, left + divWidth, top + divHeight];
  12860. }
  12861. task._bounds.push({
  12862. left: b[0],
  12863. top: b[1],
  12864. right: b[2],
  12865. bottom: b[3],
  12866. div: textDiv,
  12867. size: [divWidth, divHeight],
  12868. m
  12869. });
  12870. }
  12871. }
  12872. function render(task) {
  12873. if (task._canceled) {
  12874. return;
  12875. }
  12876. const textDivs = task._textDivs;
  12877. const capability = task._capability;
  12878. const textDivsLength = textDivs.length;
  12879. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  12880. task._renderingDone = true;
  12881. capability.resolve();
  12882. return;
  12883. }
  12884. if (!task._textContentStream) {
  12885. for (let i = 0; i < textDivsLength; i++) {
  12886. task._layoutText(textDivs[i]);
  12887. }
  12888. }
  12889. task._renderingDone = true;
  12890. capability.resolve();
  12891. }
  12892. function findPositiveMin(ts, offset, count) {
  12893. let result = 0;
  12894. for (let i = 0; i < count; i++) {
  12895. const t = ts[offset++];
  12896. if (t > 0) {
  12897. result = result ? Math.min(t, result) : t;
  12898. }
  12899. }
  12900. return result;
  12901. }
  12902. function expand(task) {
  12903. const bounds = task._bounds;
  12904. const viewport = task._viewport;
  12905. const expanded = expandBounds(viewport.width, viewport.height, bounds);
  12906. for (let i = 0; i < expanded.length; i++) {
  12907. const div = bounds[i].div;
  12908. const divProperties = task._textDivProperties.get(div);
  12909. if (divProperties.angle === 0) {
  12910. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  12911. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  12912. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  12913. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  12914. task._textDivProperties.set(div, divProperties);
  12915. continue;
  12916. }
  12917. const e = expanded[i],
  12918. b = bounds[i];
  12919. const m = b.m,
  12920. c = m[0],
  12921. s = m[1];
  12922. const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  12923. const ts = new Float64Array(64);
  12924. for (let j = 0, jj = points.length; j < jj; j++) {
  12925. const t = _util.Util.applyTransform(points[j], m);
  12926. ts[j + 0] = c && (e.left - t[0]) / c;
  12927. ts[j + 4] = s && (e.top - t[1]) / s;
  12928. ts[j + 8] = c && (e.right - t[0]) / c;
  12929. ts[j + 12] = s && (e.bottom - t[1]) / s;
  12930. ts[j + 16] = s && (e.left - t[0]) / -s;
  12931. ts[j + 20] = c && (e.top - t[1]) / c;
  12932. ts[j + 24] = s && (e.right - t[0]) / -s;
  12933. ts[j + 28] = c && (e.bottom - t[1]) / c;
  12934. ts[j + 32] = c && (e.left - t[0]) / -c;
  12935. ts[j + 36] = s && (e.top - t[1]) / -s;
  12936. ts[j + 40] = c && (e.right - t[0]) / -c;
  12937. ts[j + 44] = s && (e.bottom - t[1]) / -s;
  12938. ts[j + 48] = s && (e.left - t[0]) / s;
  12939. ts[j + 52] = c && (e.top - t[1]) / -c;
  12940. ts[j + 56] = s && (e.right - t[0]) / s;
  12941. ts[j + 60] = c && (e.bottom - t[1]) / -c;
  12942. }
  12943. const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  12944. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  12945. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  12946. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  12947. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  12948. task._textDivProperties.set(div, divProperties);
  12949. }
  12950. }
  12951. function expandBounds(width, height, boxes) {
  12952. const bounds = boxes.map(function (box, i) {
  12953. return {
  12954. x1: box.left,
  12955. y1: box.top,
  12956. x2: box.right,
  12957. y2: box.bottom,
  12958. index: i,
  12959. x1New: undefined,
  12960. x2New: undefined
  12961. };
  12962. });
  12963. expandBoundsLTR(width, bounds);
  12964. const expanded = new Array(boxes.length);
  12965. for (const b of bounds) {
  12966. const i = b.index;
  12967. expanded[i] = {
  12968. left: b.x1New,
  12969. top: 0,
  12970. right: b.x2New,
  12971. bottom: 0
  12972. };
  12973. }
  12974. boxes.map(function (box, i) {
  12975. const e = expanded[i],
  12976. b = bounds[i];
  12977. b.x1 = box.top;
  12978. b.y1 = width - e.right;
  12979. b.x2 = box.bottom;
  12980. b.y2 = width - e.left;
  12981. b.index = i;
  12982. b.x1New = undefined;
  12983. b.x2New = undefined;
  12984. });
  12985. expandBoundsLTR(height, bounds);
  12986. for (const b of bounds) {
  12987. const i = b.index;
  12988. expanded[i].top = b.x1New;
  12989. expanded[i].bottom = b.x2New;
  12990. }
  12991. return expanded;
  12992. }
  12993. function expandBoundsLTR(width, bounds) {
  12994. bounds.sort(function (a, b) {
  12995. return a.x1 - b.x1 || a.index - b.index;
  12996. });
  12997. const fakeBoundary = {
  12998. x1: -Infinity,
  12999. y1: -Infinity,
  13000. x2: 0,
  13001. y2: Infinity,
  13002. index: -1,
  13003. x1New: 0,
  13004. x2New: 0
  13005. };
  13006. const horizon = [{
  13007. start: -Infinity,
  13008. end: Infinity,
  13009. boundary: fakeBoundary
  13010. }];
  13011. for (const boundary of bounds) {
  13012. let i = 0;
  13013. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  13014. i++;
  13015. }
  13016. let j = horizon.length - 1;
  13017. while (j >= 0 && horizon[j].start >= boundary.y2) {
  13018. j--;
  13019. }
  13020. let horizonPart, affectedBoundary;
  13021. let q,
  13022. k,
  13023. maxXNew = -Infinity;
  13024. for (q = i; q <= j; q++) {
  13025. horizonPart = horizon[q];
  13026. affectedBoundary = horizonPart.boundary;
  13027. let xNew;
  13028. if (affectedBoundary.x2 > boundary.x1) {
  13029. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  13030. } else if (affectedBoundary.x2New === undefined) {
  13031. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  13032. } else {
  13033. xNew = affectedBoundary.x2New;
  13034. }
  13035. if (xNew > maxXNew) {
  13036. maxXNew = xNew;
  13037. }
  13038. }
  13039. boundary.x1New = maxXNew;
  13040. for (q = i; q <= j; q++) {
  13041. horizonPart = horizon[q];
  13042. affectedBoundary = horizonPart.boundary;
  13043. if (affectedBoundary.x2New === undefined) {
  13044. if (affectedBoundary.x2 > boundary.x1) {
  13045. if (affectedBoundary.index > boundary.index) {
  13046. affectedBoundary.x2New = affectedBoundary.x2;
  13047. }
  13048. } else {
  13049. affectedBoundary.x2New = maxXNew;
  13050. }
  13051. } else if (affectedBoundary.x2New > maxXNew) {
  13052. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  13053. }
  13054. }
  13055. const changedHorizon = [];
  13056. let lastBoundary = null;
  13057. for (q = i; q <= j; q++) {
  13058. horizonPart = horizon[q];
  13059. affectedBoundary = horizonPart.boundary;
  13060. const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  13061. if (lastBoundary === useBoundary) {
  13062. changedHorizon.at(-1).end = horizonPart.end;
  13063. } else {
  13064. changedHorizon.push({
  13065. start: horizonPart.start,
  13066. end: horizonPart.end,
  13067. boundary: useBoundary
  13068. });
  13069. lastBoundary = useBoundary;
  13070. }
  13071. }
  13072. if (horizon[i].start < boundary.y1) {
  13073. changedHorizon[0].start = boundary.y1;
  13074. changedHorizon.unshift({
  13075. start: horizon[i].start,
  13076. end: boundary.y1,
  13077. boundary: horizon[i].boundary
  13078. });
  13079. }
  13080. if (boundary.y2 < horizon[j].end) {
  13081. changedHorizon.at(-1).end = boundary.y2;
  13082. changedHorizon.push({
  13083. start: boundary.y2,
  13084. end: horizon[j].end,
  13085. boundary: horizon[j].boundary
  13086. });
  13087. }
  13088. for (q = i; q <= j; q++) {
  13089. horizonPart = horizon[q];
  13090. affectedBoundary = horizonPart.boundary;
  13091. if (affectedBoundary.x2New !== undefined) {
  13092. continue;
  13093. }
  13094. let used = false;
  13095. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  13096. used = horizon[k].boundary === affectedBoundary;
  13097. }
  13098. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  13099. used = horizon[k].boundary === affectedBoundary;
  13100. }
  13101. for (k = 0; !used && k < changedHorizon.length; k++) {
  13102. used = changedHorizon[k].boundary === affectedBoundary;
  13103. }
  13104. if (!used) {
  13105. affectedBoundary.x2New = maxXNew;
  13106. }
  13107. }
  13108. Array.prototype.splice.apply(horizon, [i, j - i + 1, ...changedHorizon]);
  13109. }
  13110. for (const horizonPart of horizon) {
  13111. const affectedBoundary = horizonPart.boundary;
  13112. if (affectedBoundary.x2New === undefined) {
  13113. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  13114. }
  13115. }
  13116. }
  13117. class TextLayerRenderTask {
  13118. constructor({
  13119. textContent,
  13120. textContentStream,
  13121. container,
  13122. viewport,
  13123. textDivs,
  13124. textContentItemsStr,
  13125. enhanceTextSelection
  13126. }) {
  13127. if (enhanceTextSelection) {
  13128. (0, _display_utils.deprecated)("The `enhanceTextSelection` functionality will be removed in the future.");
  13129. }
  13130. this._textContent = textContent;
  13131. this._textContentStream = textContentStream;
  13132. this._container = container;
  13133. this._document = container.ownerDocument;
  13134. this._viewport = viewport;
  13135. this._textDivs = textDivs || [];
  13136. this._textContentItemsStr = textContentItemsStr || [];
  13137. this._enhanceTextSelection = !!enhanceTextSelection;
  13138. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  13139. this._reader = null;
  13140. this._layoutTextLastFontSize = null;
  13141. this._layoutTextLastFontFamily = null;
  13142. this._layoutTextCtx = null;
  13143. this._textDivProperties = new WeakMap();
  13144. this._renderingDone = false;
  13145. this._canceled = false;
  13146. this._capability = (0, _util.createPromiseCapability)();
  13147. this._renderTimer = null;
  13148. this._bounds = [];
  13149. this._devicePixelRatio = globalThis.devicePixelRatio || 1;
  13150. this._capability.promise.finally(() => {
  13151. if (!this._enhanceTextSelection) {
  13152. this._textDivProperties = null;
  13153. }
  13154. if (this._layoutTextCtx) {
  13155. this._layoutTextCtx.canvas.width = 0;
  13156. this._layoutTextCtx.canvas.height = 0;
  13157. this._layoutTextCtx = null;
  13158. }
  13159. }).catch(() => {});
  13160. }
  13161. get promise() {
  13162. return this._capability.promise;
  13163. }
  13164. cancel() {
  13165. this._canceled = true;
  13166. if (this._reader) {
  13167. this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
  13168. this._reader = null;
  13169. }
  13170. if (this._renderTimer !== null) {
  13171. clearTimeout(this._renderTimer);
  13172. this._renderTimer = null;
  13173. }
  13174. this._capability.reject(new Error("TextLayer task cancelled."));
  13175. }
  13176. _processItems(items, styleCache) {
  13177. for (let i = 0, len = items.length; i < len; i++) {
  13178. if (items[i].str === undefined) {
  13179. if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") {
  13180. const parent = this._container;
  13181. this._container = document.createElement("span");
  13182. this._container.classList.add("markedContent");
  13183. if (items[i].id !== null) {
  13184. this._container.setAttribute("id", `${items[i].id}`);
  13185. }
  13186. parent.append(this._container);
  13187. } else if (items[i].type === "endMarkedContent") {
  13188. this._container = this._container.parentNode;
  13189. }
  13190. continue;
  13191. }
  13192. this._textContentItemsStr.push(items[i].str);
  13193. appendText(this, items[i], styleCache, this._layoutTextCtx);
  13194. }
  13195. }
  13196. _layoutText(textDiv) {
  13197. const textDivProperties = this._textDivProperties.get(textDiv);
  13198. let transform = "";
  13199. if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
  13200. const {
  13201. fontFamily
  13202. } = textDiv.style;
  13203. const {
  13204. fontSize
  13205. } = textDivProperties;
  13206. if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
  13207. this._layoutTextCtx.font = `${fontSize * this._devicePixelRatio}px ${fontFamily}`;
  13208. this._layoutTextLastFontSize = fontSize;
  13209. this._layoutTextLastFontFamily = fontFamily;
  13210. }
  13211. const {
  13212. width
  13213. } = this._layoutTextCtx.measureText(textDiv.textContent);
  13214. if (width > 0) {
  13215. const scale = this._devicePixelRatio * textDivProperties.canvasWidth / width;
  13216. if (this._enhanceTextSelection) {
  13217. textDivProperties.scale = scale;
  13218. }
  13219. transform = `scaleX(${scale})`;
  13220. }
  13221. }
  13222. if (textDivProperties.angle !== 0) {
  13223. transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
  13224. }
  13225. if (transform.length > 0) {
  13226. if (this._enhanceTextSelection) {
  13227. textDivProperties.originalTransform = transform;
  13228. }
  13229. textDiv.style.transform = transform;
  13230. }
  13231. if (textDivProperties.hasText) {
  13232. this._container.append(textDiv);
  13233. }
  13234. if (textDivProperties.hasEOL) {
  13235. const br = document.createElement("br");
  13236. br.setAttribute("role", "presentation");
  13237. this._container.append(br);
  13238. }
  13239. }
  13240. _render(timeout = 0) {
  13241. const capability = (0, _util.createPromiseCapability)();
  13242. let styleCache = Object.create(null);
  13243. const canvas = this._document.createElement("canvas");
  13244. canvas.height = canvas.width = DEFAULT_FONT_SIZE;
  13245. this._layoutTextCtx = canvas.getContext("2d", {
  13246. alpha: false
  13247. });
  13248. if (this._textContent) {
  13249. const textItems = this._textContent.items;
  13250. const textStyles = this._textContent.styles;
  13251. this._processItems(textItems, textStyles);
  13252. capability.resolve();
  13253. } else if (this._textContentStream) {
  13254. const pump = () => {
  13255. this._reader.read().then(({
  13256. value,
  13257. done
  13258. }) => {
  13259. if (done) {
  13260. capability.resolve();
  13261. return;
  13262. }
  13263. Object.assign(styleCache, value.styles);
  13264. this._processItems(value.items, styleCache);
  13265. pump();
  13266. }, capability.reject);
  13267. };
  13268. this._reader = this._textContentStream.getReader();
  13269. pump();
  13270. } else {
  13271. throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');
  13272. }
  13273. capability.promise.then(() => {
  13274. styleCache = null;
  13275. if (!timeout) {
  13276. render(this);
  13277. } else {
  13278. this._renderTimer = setTimeout(() => {
  13279. render(this);
  13280. this._renderTimer = null;
  13281. }, timeout);
  13282. }
  13283. }, this._capability.reject);
  13284. }
  13285. expandTextDivs(expandDivs = false) {
  13286. if (!this._enhanceTextSelection || !this._renderingDone) {
  13287. return;
  13288. }
  13289. if (this._bounds !== null) {
  13290. expand(this);
  13291. this._bounds = null;
  13292. }
  13293. const transformBuf = [],
  13294. paddingBuf = [];
  13295. for (let i = 0, ii = this._textDivs.length; i < ii; i++) {
  13296. const div = this._textDivs[i];
  13297. const divProps = this._textDivProperties.get(div);
  13298. if (!divProps.hasText) {
  13299. continue;
  13300. }
  13301. if (expandDivs) {
  13302. transformBuf.length = 0;
  13303. paddingBuf.length = 0;
  13304. if (divProps.originalTransform) {
  13305. transformBuf.push(divProps.originalTransform);
  13306. }
  13307. if (divProps.paddingTop > 0) {
  13308. paddingBuf.push(`${divProps.paddingTop}px`);
  13309. transformBuf.push(`translateY(${-divProps.paddingTop}px)`);
  13310. } else {
  13311. paddingBuf.push(0);
  13312. }
  13313. if (divProps.paddingRight > 0) {
  13314. paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`);
  13315. } else {
  13316. paddingBuf.push(0);
  13317. }
  13318. if (divProps.paddingBottom > 0) {
  13319. paddingBuf.push(`${divProps.paddingBottom}px`);
  13320. } else {
  13321. paddingBuf.push(0);
  13322. }
  13323. if (divProps.paddingLeft > 0) {
  13324. paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`);
  13325. transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`);
  13326. } else {
  13327. paddingBuf.push(0);
  13328. }
  13329. div.style.padding = paddingBuf.join(" ");
  13330. if (transformBuf.length) {
  13331. div.style.transform = transformBuf.join(" ");
  13332. }
  13333. } else {
  13334. div.style.padding = null;
  13335. div.style.transform = divProps.originalTransform;
  13336. }
  13337. }
  13338. }
  13339. }
  13340. exports.TextLayerRenderTask = TextLayerRenderTask;
  13341. function renderTextLayer(renderParameters) {
  13342. const task = new TextLayerRenderTask({
  13343. textContent: renderParameters.textContent,
  13344. textContentStream: renderParameters.textContentStream,
  13345. container: renderParameters.container,
  13346. viewport: renderParameters.viewport,
  13347. textDivs: renderParameters.textDivs,
  13348. textContentItemsStr: renderParameters.textContentItemsStr,
  13349. enhanceTextSelection: renderParameters.enhanceTextSelection
  13350. });
  13351. task._render(renderParameters.timeout);
  13352. return task;
  13353. }
  13354. /***/ }),
  13355. /* 31 */
  13356. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  13357. Object.defineProperty(exports, "__esModule", ({
  13358. value: true
  13359. }));
  13360. exports.SVGGraphics = void 0;
  13361. var _display_utils = __w_pdfjs_require__(4);
  13362. var _util = __w_pdfjs_require__(1);
  13363. var _is_node = __w_pdfjs_require__(3);
  13364. let SVGGraphics = class {
  13365. constructor() {
  13366. (0, _util.unreachable)("Not implemented: SVGGraphics");
  13367. }
  13368. };
  13369. exports.SVGGraphics = SVGGraphics;
  13370. {
  13371. const SVG_DEFAULTS = {
  13372. fontStyle: "normal",
  13373. fontWeight: "normal",
  13374. fillColor: "#000000"
  13375. };
  13376. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  13377. const XLINK_NS = "http://www.w3.org/1999/xlink";
  13378. const LINE_CAP_STYLES = ["butt", "round", "square"];
  13379. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  13380. const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
  13381. if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
  13382. return URL.createObjectURL(new Blob([data], {
  13383. type: contentType
  13384. }));
  13385. }
  13386. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  13387. let buffer = `data:${contentType};base64,`;
  13388. for (let i = 0, ii = data.length; i < ii; i += 3) {
  13389. const b1 = data[i] & 0xff;
  13390. const b2 = data[i + 1] & 0xff;
  13391. const b3 = data[i + 2] & 0xff;
  13392. const d1 = b1 >> 2,
  13393. d2 = (b1 & 3) << 4 | b2 >> 4;
  13394. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  13395. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  13396. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  13397. }
  13398. return buffer;
  13399. };
  13400. const convertImgDataToPng = function () {
  13401. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  13402. const CHUNK_WRAPPER_SIZE = 12;
  13403. const crcTable = new Int32Array(256);
  13404. for (let i = 0; i < 256; i++) {
  13405. let c = i;
  13406. for (let h = 0; h < 8; h++) {
  13407. if (c & 1) {
  13408. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  13409. } else {
  13410. c = c >> 1 & 0x7fffffff;
  13411. }
  13412. }
  13413. crcTable[i] = c;
  13414. }
  13415. function crc32(data, start, end) {
  13416. let crc = -1;
  13417. for (let i = start; i < end; i++) {
  13418. const a = (crc ^ data[i]) & 0xff;
  13419. const b = crcTable[a];
  13420. crc = crc >>> 8 ^ b;
  13421. }
  13422. return crc ^ -1;
  13423. }
  13424. function writePngChunk(type, body, data, offset) {
  13425. let p = offset;
  13426. const len = body.length;
  13427. data[p] = len >> 24 & 0xff;
  13428. data[p + 1] = len >> 16 & 0xff;
  13429. data[p + 2] = len >> 8 & 0xff;
  13430. data[p + 3] = len & 0xff;
  13431. p += 4;
  13432. data[p] = type.charCodeAt(0) & 0xff;
  13433. data[p + 1] = type.charCodeAt(1) & 0xff;
  13434. data[p + 2] = type.charCodeAt(2) & 0xff;
  13435. data[p + 3] = type.charCodeAt(3) & 0xff;
  13436. p += 4;
  13437. data.set(body, p);
  13438. p += body.length;
  13439. const crc = crc32(data, offset + 4, p);
  13440. data[p] = crc >> 24 & 0xff;
  13441. data[p + 1] = crc >> 16 & 0xff;
  13442. data[p + 2] = crc >> 8 & 0xff;
  13443. data[p + 3] = crc & 0xff;
  13444. }
  13445. function adler32(data, start, end) {
  13446. let a = 1;
  13447. let b = 0;
  13448. for (let i = start; i < end; ++i) {
  13449. a = (a + (data[i] & 0xff)) % 65521;
  13450. b = (b + a) % 65521;
  13451. }
  13452. return b << 16 | a;
  13453. }
  13454. function deflateSync(literals) {
  13455. if (!_is_node.isNodeJS) {
  13456. return deflateSyncUncompressed(literals);
  13457. }
  13458. try {
  13459. let input;
  13460. if (parseInt(process.versions.node) >= 8) {
  13461. input = literals;
  13462. } else {
  13463. input = Buffer.from(literals);
  13464. }
  13465. const output = require("zlib").deflateSync(input, {
  13466. level: 9
  13467. });
  13468. return output instanceof Uint8Array ? output : new Uint8Array(output);
  13469. } catch (e) {
  13470. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  13471. }
  13472. return deflateSyncUncompressed(literals);
  13473. }
  13474. function deflateSyncUncompressed(literals) {
  13475. let len = literals.length;
  13476. const maxBlockLength = 0xffff;
  13477. const deflateBlocks = Math.ceil(len / maxBlockLength);
  13478. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  13479. let pi = 0;
  13480. idat[pi++] = 0x78;
  13481. idat[pi++] = 0x9c;
  13482. let pos = 0;
  13483. while (len > maxBlockLength) {
  13484. idat[pi++] = 0x00;
  13485. idat[pi++] = 0xff;
  13486. idat[pi++] = 0xff;
  13487. idat[pi++] = 0x00;
  13488. idat[pi++] = 0x00;
  13489. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  13490. pi += maxBlockLength;
  13491. pos += maxBlockLength;
  13492. len -= maxBlockLength;
  13493. }
  13494. idat[pi++] = 0x01;
  13495. idat[pi++] = len & 0xff;
  13496. idat[pi++] = len >> 8 & 0xff;
  13497. idat[pi++] = ~len & 0xffff & 0xff;
  13498. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  13499. idat.set(literals.subarray(pos), pi);
  13500. pi += literals.length - pos;
  13501. const adler = adler32(literals, 0, literals.length);
  13502. idat[pi++] = adler >> 24 & 0xff;
  13503. idat[pi++] = adler >> 16 & 0xff;
  13504. idat[pi++] = adler >> 8 & 0xff;
  13505. idat[pi++] = adler & 0xff;
  13506. return idat;
  13507. }
  13508. function encode(imgData, kind, forceDataSchema, isMask) {
  13509. const width = imgData.width;
  13510. const height = imgData.height;
  13511. let bitDepth, colorType, lineSize;
  13512. const bytes = imgData.data;
  13513. switch (kind) {
  13514. case _util.ImageKind.GRAYSCALE_1BPP:
  13515. colorType = 0;
  13516. bitDepth = 1;
  13517. lineSize = width + 7 >> 3;
  13518. break;
  13519. case _util.ImageKind.RGB_24BPP:
  13520. colorType = 2;
  13521. bitDepth = 8;
  13522. lineSize = width * 3;
  13523. break;
  13524. case _util.ImageKind.RGBA_32BPP:
  13525. colorType = 6;
  13526. bitDepth = 8;
  13527. lineSize = width * 4;
  13528. break;
  13529. default:
  13530. throw new Error("invalid format");
  13531. }
  13532. const literals = new Uint8Array((1 + lineSize) * height);
  13533. let offsetLiterals = 0,
  13534. offsetBytes = 0;
  13535. for (let y = 0; y < height; ++y) {
  13536. literals[offsetLiterals++] = 0;
  13537. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  13538. offsetBytes += lineSize;
  13539. offsetLiterals += lineSize;
  13540. }
  13541. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  13542. offsetLiterals = 0;
  13543. for (let y = 0; y < height; y++) {
  13544. offsetLiterals++;
  13545. for (let i = 0; i < lineSize; i++) {
  13546. literals[offsetLiterals++] ^= 0xff;
  13547. }
  13548. }
  13549. }
  13550. 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]);
  13551. const idat = deflateSync(literals);
  13552. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  13553. const data = new Uint8Array(pngLength);
  13554. let offset = 0;
  13555. data.set(PNG_HEADER, offset);
  13556. offset += PNG_HEADER.length;
  13557. writePngChunk("IHDR", ihdr, data, offset);
  13558. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  13559. writePngChunk("IDATA", idat, data, offset);
  13560. offset += CHUNK_WRAPPER_SIZE + idat.length;
  13561. writePngChunk("IEND", new Uint8Array(0), data, offset);
  13562. return createObjectURL(data, "image/png", forceDataSchema);
  13563. }
  13564. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  13565. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  13566. return encode(imgData, kind, forceDataSchema, isMask);
  13567. };
  13568. }();
  13569. class SVGExtraState {
  13570. constructor() {
  13571. this.fontSizeScale = 1;
  13572. this.fontWeight = SVG_DEFAULTS.fontWeight;
  13573. this.fontSize = 0;
  13574. this.textMatrix = _util.IDENTITY_MATRIX;
  13575. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  13576. this.leading = 0;
  13577. this.textRenderingMode = _util.TextRenderingMode.FILL;
  13578. this.textMatrixScale = 1;
  13579. this.x = 0;
  13580. this.y = 0;
  13581. this.lineX = 0;
  13582. this.lineY = 0;
  13583. this.charSpacing = 0;
  13584. this.wordSpacing = 0;
  13585. this.textHScale = 1;
  13586. this.textRise = 0;
  13587. this.fillColor = SVG_DEFAULTS.fillColor;
  13588. this.strokeColor = "#000000";
  13589. this.fillAlpha = 1;
  13590. this.strokeAlpha = 1;
  13591. this.lineWidth = 1;
  13592. this.lineJoin = "";
  13593. this.lineCap = "";
  13594. this.miterLimit = 0;
  13595. this.dashArray = [];
  13596. this.dashPhase = 0;
  13597. this.dependencies = [];
  13598. this.activeClipUrl = null;
  13599. this.clipGroup = null;
  13600. this.maskId = "";
  13601. }
  13602. clone() {
  13603. return Object.create(this);
  13604. }
  13605. setCurrentPoint(x, y) {
  13606. this.x = x;
  13607. this.y = y;
  13608. }
  13609. }
  13610. function opListToTree(opList) {
  13611. let opTree = [];
  13612. const tmp = [];
  13613. for (const opListElement of opList) {
  13614. if (opListElement.fn === "save") {
  13615. opTree.push({
  13616. fnId: 92,
  13617. fn: "group",
  13618. items: []
  13619. });
  13620. tmp.push(opTree);
  13621. opTree = opTree.at(-1).items;
  13622. continue;
  13623. }
  13624. if (opListElement.fn === "restore") {
  13625. opTree = tmp.pop();
  13626. } else {
  13627. opTree.push(opListElement);
  13628. }
  13629. }
  13630. return opTree;
  13631. }
  13632. function pf(value) {
  13633. if (Number.isInteger(value)) {
  13634. return value.toString();
  13635. }
  13636. const s = value.toFixed(10);
  13637. let i = s.length - 1;
  13638. if (s[i] !== "0") {
  13639. return s;
  13640. }
  13641. do {
  13642. i--;
  13643. } while (s[i] === "0");
  13644. return s.substring(0, s[i] === "." ? i : i + 1);
  13645. }
  13646. function pm(m) {
  13647. if (m[4] === 0 && m[5] === 0) {
  13648. if (m[1] === 0 && m[2] === 0) {
  13649. if (m[0] === 1 && m[3] === 1) {
  13650. return "";
  13651. }
  13652. return `scale(${pf(m[0])} ${pf(m[3])})`;
  13653. }
  13654. if (m[0] === m[3] && m[1] === -m[2]) {
  13655. const a = Math.acos(m[0]) * 180 / Math.PI;
  13656. return `rotate(${pf(a)})`;
  13657. }
  13658. } else {
  13659. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  13660. return `translate(${pf(m[4])} ${pf(m[5])})`;
  13661. }
  13662. }
  13663. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  13664. }
  13665. let clipCount = 0;
  13666. let maskCount = 0;
  13667. let shadingCount = 0;
  13668. exports.SVGGraphics = SVGGraphics = class {
  13669. constructor(commonObjs, objs, forceDataSchema = false) {
  13670. (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
  13671. this.svgFactory = new _display_utils.DOMSVGFactory();
  13672. this.current = new SVGExtraState();
  13673. this.transformMatrix = _util.IDENTITY_MATRIX;
  13674. this.transformStack = [];
  13675. this.extraStack = [];
  13676. this.commonObjs = commonObjs;
  13677. this.objs = objs;
  13678. this.pendingClip = null;
  13679. this.pendingEOFill = false;
  13680. this.embedFonts = false;
  13681. this.embeddedFonts = Object.create(null);
  13682. this.cssStyle = null;
  13683. this.forceDataSchema = !!forceDataSchema;
  13684. this._operatorIdMapping = [];
  13685. for (const op in _util.OPS) {
  13686. this._operatorIdMapping[_util.OPS[op]] = op;
  13687. }
  13688. }
  13689. save() {
  13690. this.transformStack.push(this.transformMatrix);
  13691. const old = this.current;
  13692. this.extraStack.push(old);
  13693. this.current = old.clone();
  13694. }
  13695. restore() {
  13696. this.transformMatrix = this.transformStack.pop();
  13697. this.current = this.extraStack.pop();
  13698. this.pendingClip = null;
  13699. this.tgrp = null;
  13700. }
  13701. group(items) {
  13702. this.save();
  13703. this.executeOpTree(items);
  13704. this.restore();
  13705. }
  13706. loadDependencies(operatorList) {
  13707. const fnArray = operatorList.fnArray;
  13708. const argsArray = operatorList.argsArray;
  13709. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13710. if (fnArray[i] !== _util.OPS.dependency) {
  13711. continue;
  13712. }
  13713. for (const obj of argsArray[i]) {
  13714. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  13715. const promise = new Promise(resolve => {
  13716. objsPool.get(obj, resolve);
  13717. });
  13718. this.current.dependencies.push(promise);
  13719. }
  13720. }
  13721. return Promise.all(this.current.dependencies);
  13722. }
  13723. transform(a, b, c, d, e, f) {
  13724. const transformMatrix = [a, b, c, d, e, f];
  13725. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  13726. this.tgrp = null;
  13727. }
  13728. getSVG(operatorList, viewport) {
  13729. this.viewport = viewport;
  13730. const svgElement = this._initialize(viewport);
  13731. return this.loadDependencies(operatorList).then(() => {
  13732. this.transformMatrix = _util.IDENTITY_MATRIX;
  13733. this.executeOpTree(this.convertOpList(operatorList));
  13734. return svgElement;
  13735. });
  13736. }
  13737. convertOpList(operatorList) {
  13738. const operatorIdMapping = this._operatorIdMapping;
  13739. const argsArray = operatorList.argsArray;
  13740. const fnArray = operatorList.fnArray;
  13741. const opList = [];
  13742. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13743. const fnId = fnArray[i];
  13744. opList.push({
  13745. fnId,
  13746. fn: operatorIdMapping[fnId],
  13747. args: argsArray[i]
  13748. });
  13749. }
  13750. return opListToTree(opList);
  13751. }
  13752. executeOpTree(opTree) {
  13753. for (const opTreeElement of opTree) {
  13754. const fn = opTreeElement.fn;
  13755. const fnId = opTreeElement.fnId;
  13756. const args = opTreeElement.args;
  13757. switch (fnId | 0) {
  13758. case _util.OPS.beginText:
  13759. this.beginText();
  13760. break;
  13761. case _util.OPS.dependency:
  13762. break;
  13763. case _util.OPS.setLeading:
  13764. this.setLeading(args);
  13765. break;
  13766. case _util.OPS.setLeadingMoveText:
  13767. this.setLeadingMoveText(args[0], args[1]);
  13768. break;
  13769. case _util.OPS.setFont:
  13770. this.setFont(args);
  13771. break;
  13772. case _util.OPS.showText:
  13773. this.showText(args[0]);
  13774. break;
  13775. case _util.OPS.showSpacedText:
  13776. this.showText(args[0]);
  13777. break;
  13778. case _util.OPS.endText:
  13779. this.endText();
  13780. break;
  13781. case _util.OPS.moveText:
  13782. this.moveText(args[0], args[1]);
  13783. break;
  13784. case _util.OPS.setCharSpacing:
  13785. this.setCharSpacing(args[0]);
  13786. break;
  13787. case _util.OPS.setWordSpacing:
  13788. this.setWordSpacing(args[0]);
  13789. break;
  13790. case _util.OPS.setHScale:
  13791. this.setHScale(args[0]);
  13792. break;
  13793. case _util.OPS.setTextMatrix:
  13794. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  13795. break;
  13796. case _util.OPS.setTextRise:
  13797. this.setTextRise(args[0]);
  13798. break;
  13799. case _util.OPS.setTextRenderingMode:
  13800. this.setTextRenderingMode(args[0]);
  13801. break;
  13802. case _util.OPS.setLineWidth:
  13803. this.setLineWidth(args[0]);
  13804. break;
  13805. case _util.OPS.setLineJoin:
  13806. this.setLineJoin(args[0]);
  13807. break;
  13808. case _util.OPS.setLineCap:
  13809. this.setLineCap(args[0]);
  13810. break;
  13811. case _util.OPS.setMiterLimit:
  13812. this.setMiterLimit(args[0]);
  13813. break;
  13814. case _util.OPS.setFillRGBColor:
  13815. this.setFillRGBColor(args[0], args[1], args[2]);
  13816. break;
  13817. case _util.OPS.setStrokeRGBColor:
  13818. this.setStrokeRGBColor(args[0], args[1], args[2]);
  13819. break;
  13820. case _util.OPS.setStrokeColorN:
  13821. this.setStrokeColorN(args);
  13822. break;
  13823. case _util.OPS.setFillColorN:
  13824. this.setFillColorN(args);
  13825. break;
  13826. case _util.OPS.shadingFill:
  13827. this.shadingFill(args[0]);
  13828. break;
  13829. case _util.OPS.setDash:
  13830. this.setDash(args[0], args[1]);
  13831. break;
  13832. case _util.OPS.setRenderingIntent:
  13833. this.setRenderingIntent(args[0]);
  13834. break;
  13835. case _util.OPS.setFlatness:
  13836. this.setFlatness(args[0]);
  13837. break;
  13838. case _util.OPS.setGState:
  13839. this.setGState(args[0]);
  13840. break;
  13841. case _util.OPS.fill:
  13842. this.fill();
  13843. break;
  13844. case _util.OPS.eoFill:
  13845. this.eoFill();
  13846. break;
  13847. case _util.OPS.stroke:
  13848. this.stroke();
  13849. break;
  13850. case _util.OPS.fillStroke:
  13851. this.fillStroke();
  13852. break;
  13853. case _util.OPS.eoFillStroke:
  13854. this.eoFillStroke();
  13855. break;
  13856. case _util.OPS.clip:
  13857. this.clip("nonzero");
  13858. break;
  13859. case _util.OPS.eoClip:
  13860. this.clip("evenodd");
  13861. break;
  13862. case _util.OPS.paintSolidColorImageMask:
  13863. this.paintSolidColorImageMask();
  13864. break;
  13865. case _util.OPS.paintImageXObject:
  13866. this.paintImageXObject(args[0]);
  13867. break;
  13868. case _util.OPS.paintInlineImageXObject:
  13869. this.paintInlineImageXObject(args[0]);
  13870. break;
  13871. case _util.OPS.paintImageMaskXObject:
  13872. this.paintImageMaskXObject(args[0]);
  13873. break;
  13874. case _util.OPS.paintFormXObjectBegin:
  13875. this.paintFormXObjectBegin(args[0], args[1]);
  13876. break;
  13877. case _util.OPS.paintFormXObjectEnd:
  13878. this.paintFormXObjectEnd();
  13879. break;
  13880. case _util.OPS.closePath:
  13881. this.closePath();
  13882. break;
  13883. case _util.OPS.closeStroke:
  13884. this.closeStroke();
  13885. break;
  13886. case _util.OPS.closeFillStroke:
  13887. this.closeFillStroke();
  13888. break;
  13889. case _util.OPS.closeEOFillStroke:
  13890. this.closeEOFillStroke();
  13891. break;
  13892. case _util.OPS.nextLine:
  13893. this.nextLine();
  13894. break;
  13895. case _util.OPS.transform:
  13896. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  13897. break;
  13898. case _util.OPS.constructPath:
  13899. this.constructPath(args[0], args[1]);
  13900. break;
  13901. case _util.OPS.endPath:
  13902. this.endPath();
  13903. break;
  13904. case 92:
  13905. this.group(opTreeElement.items);
  13906. break;
  13907. default:
  13908. (0, _util.warn)(`Unimplemented operator ${fn}`);
  13909. break;
  13910. }
  13911. }
  13912. }
  13913. setWordSpacing(wordSpacing) {
  13914. this.current.wordSpacing = wordSpacing;
  13915. }
  13916. setCharSpacing(charSpacing) {
  13917. this.current.charSpacing = charSpacing;
  13918. }
  13919. nextLine() {
  13920. this.moveText(0, this.current.leading);
  13921. }
  13922. setTextMatrix(a, b, c, d, e, f) {
  13923. const current = this.current;
  13924. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  13925. current.textMatrixScale = Math.hypot(a, b);
  13926. current.x = current.lineX = 0;
  13927. current.y = current.lineY = 0;
  13928. current.xcoords = [];
  13929. current.ycoords = [];
  13930. current.tspan = this.svgFactory.createElement("svg:tspan");
  13931. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13932. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13933. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13934. current.txtElement = this.svgFactory.createElement("svg:text");
  13935. current.txtElement.append(current.tspan);
  13936. }
  13937. beginText() {
  13938. const current = this.current;
  13939. current.x = current.lineX = 0;
  13940. current.y = current.lineY = 0;
  13941. current.textMatrix = _util.IDENTITY_MATRIX;
  13942. current.lineMatrix = _util.IDENTITY_MATRIX;
  13943. current.textMatrixScale = 1;
  13944. current.tspan = this.svgFactory.createElement("svg:tspan");
  13945. current.txtElement = this.svgFactory.createElement("svg:text");
  13946. current.txtgrp = this.svgFactory.createElement("svg:g");
  13947. current.xcoords = [];
  13948. current.ycoords = [];
  13949. }
  13950. moveText(x, y) {
  13951. const current = this.current;
  13952. current.x = current.lineX += x;
  13953. current.y = current.lineY += y;
  13954. current.xcoords = [];
  13955. current.ycoords = [];
  13956. current.tspan = this.svgFactory.createElement("svg:tspan");
  13957. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13958. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13959. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13960. }
  13961. showText(glyphs) {
  13962. const current = this.current;
  13963. const font = current.font;
  13964. const fontSize = current.fontSize;
  13965. if (fontSize === 0) {
  13966. return;
  13967. }
  13968. const fontSizeScale = current.fontSizeScale;
  13969. const charSpacing = current.charSpacing;
  13970. const wordSpacing = current.wordSpacing;
  13971. const fontDirection = current.fontDirection;
  13972. const textHScale = current.textHScale * fontDirection;
  13973. const vertical = font.vertical;
  13974. const spacingDir = vertical ? 1 : -1;
  13975. const defaultVMetrics = font.defaultVMetrics;
  13976. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  13977. let x = 0;
  13978. for (const glyph of glyphs) {
  13979. if (glyph === null) {
  13980. x += fontDirection * wordSpacing;
  13981. continue;
  13982. } else if (typeof glyph === "number") {
  13983. x += spacingDir * glyph * fontSize / 1000;
  13984. continue;
  13985. }
  13986. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  13987. const character = glyph.fontChar;
  13988. let scaledX, scaledY;
  13989. let width = glyph.width;
  13990. if (vertical) {
  13991. let vx;
  13992. const vmetric = glyph.vmetric || defaultVMetrics;
  13993. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  13994. vx = -vx * widthAdvanceScale;
  13995. const vy = vmetric[2] * widthAdvanceScale;
  13996. width = vmetric ? -vmetric[0] : width;
  13997. scaledX = vx / fontSizeScale;
  13998. scaledY = (x + vy) / fontSizeScale;
  13999. } else {
  14000. scaledX = x / fontSizeScale;
  14001. scaledY = 0;
  14002. }
  14003. if (glyph.isInFont || font.missingFile) {
  14004. current.xcoords.push(current.x + scaledX);
  14005. if (vertical) {
  14006. current.ycoords.push(-current.y + scaledY);
  14007. }
  14008. current.tspan.textContent += character;
  14009. } else {}
  14010. let charWidth;
  14011. if (vertical) {
  14012. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  14013. } else {
  14014. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  14015. }
  14016. x += charWidth;
  14017. }
  14018. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  14019. if (vertical) {
  14020. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  14021. } else {
  14022. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  14023. }
  14024. if (vertical) {
  14025. current.y -= x;
  14026. } else {
  14027. current.x += x * textHScale;
  14028. }
  14029. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  14030. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  14031. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  14032. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  14033. }
  14034. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  14035. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  14036. }
  14037. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  14038. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  14039. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  14040. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  14041. }
  14042. if (current.fillAlpha < 1) {
  14043. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  14044. }
  14045. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  14046. current.tspan.setAttributeNS(null, "fill", "transparent");
  14047. } else {
  14048. current.tspan.setAttributeNS(null, "fill", "none");
  14049. }
  14050. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  14051. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  14052. this._setStrokeAttributes(current.tspan, lineWidthScale);
  14053. }
  14054. let textMatrix = current.textMatrix;
  14055. if (current.textRise !== 0) {
  14056. textMatrix = textMatrix.slice();
  14057. textMatrix[5] += current.textRise;
  14058. }
  14059. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  14060. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  14061. current.txtElement.append(current.tspan);
  14062. current.txtgrp.append(current.txtElement);
  14063. this._ensureTransformGroup().append(current.txtElement);
  14064. }
  14065. setLeadingMoveText(x, y) {
  14066. this.setLeading(-y);
  14067. this.moveText(x, y);
  14068. }
  14069. addFontStyle(fontObj) {
  14070. if (!fontObj.data) {
  14071. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  14072. }
  14073. if (!this.cssStyle) {
  14074. this.cssStyle = this.svgFactory.createElement("svg:style");
  14075. this.cssStyle.setAttributeNS(null, "type", "text/css");
  14076. this.defs.append(this.cssStyle);
  14077. }
  14078. const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  14079. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  14080. }
  14081. setFont(details) {
  14082. const current = this.current;
  14083. const fontObj = this.commonObjs.get(details[0]);
  14084. let size = details[1];
  14085. current.font = fontObj;
  14086. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  14087. this.addFontStyle(fontObj);
  14088. this.embeddedFonts[fontObj.loadedName] = fontObj;
  14089. }
  14090. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  14091. let bold = "normal";
  14092. if (fontObj.black) {
  14093. bold = "900";
  14094. } else if (fontObj.bold) {
  14095. bold = "bold";
  14096. }
  14097. const italic = fontObj.italic ? "italic" : "normal";
  14098. if (size < 0) {
  14099. size = -size;
  14100. current.fontDirection = -1;
  14101. } else {
  14102. current.fontDirection = 1;
  14103. }
  14104. current.fontSize = size;
  14105. current.fontFamily = fontObj.loadedName;
  14106. current.fontWeight = bold;
  14107. current.fontStyle = italic;
  14108. current.tspan = this.svgFactory.createElement("svg:tspan");
  14109. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  14110. current.xcoords = [];
  14111. current.ycoords = [];
  14112. }
  14113. endText() {
  14114. const current = this.current;
  14115. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  14116. current.element = current.txtElement;
  14117. this.clip("nonzero");
  14118. this.endPath();
  14119. }
  14120. }
  14121. setLineWidth(width) {
  14122. if (width > 0) {
  14123. this.current.lineWidth = width;
  14124. }
  14125. }
  14126. setLineCap(style) {
  14127. this.current.lineCap = LINE_CAP_STYLES[style];
  14128. }
  14129. setLineJoin(style) {
  14130. this.current.lineJoin = LINE_JOIN_STYLES[style];
  14131. }
  14132. setMiterLimit(limit) {
  14133. this.current.miterLimit = limit;
  14134. }
  14135. setStrokeAlpha(strokeAlpha) {
  14136. this.current.strokeAlpha = strokeAlpha;
  14137. }
  14138. setStrokeRGBColor(r, g, b) {
  14139. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  14140. }
  14141. setFillAlpha(fillAlpha) {
  14142. this.current.fillAlpha = fillAlpha;
  14143. }
  14144. setFillRGBColor(r, g, b) {
  14145. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  14146. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  14147. this.current.xcoords = [];
  14148. this.current.ycoords = [];
  14149. }
  14150. setStrokeColorN(args) {
  14151. this.current.strokeColor = this._makeColorN_Pattern(args);
  14152. }
  14153. setFillColorN(args) {
  14154. this.current.fillColor = this._makeColorN_Pattern(args);
  14155. }
  14156. shadingFill(args) {
  14157. const width = this.viewport.width;
  14158. const height = this.viewport.height;
  14159. const inv = _util.Util.inverseTransform(this.transformMatrix);
  14160. const bl = _util.Util.applyTransform([0, 0], inv);
  14161. const br = _util.Util.applyTransform([0, height], inv);
  14162. const ul = _util.Util.applyTransform([width, 0], inv);
  14163. const ur = _util.Util.applyTransform([width, height], inv);
  14164. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  14165. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  14166. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  14167. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  14168. const rect = this.svgFactory.createElement("svg:rect");
  14169. rect.setAttributeNS(null, "x", x0);
  14170. rect.setAttributeNS(null, "y", y0);
  14171. rect.setAttributeNS(null, "width", x1 - x0);
  14172. rect.setAttributeNS(null, "height", y1 - y0);
  14173. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  14174. if (this.current.fillAlpha < 1) {
  14175. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  14176. }
  14177. this._ensureTransformGroup().append(rect);
  14178. }
  14179. _makeColorN_Pattern(args) {
  14180. if (args[0] === "TilingPattern") {
  14181. return this._makeTilingPattern(args);
  14182. }
  14183. return this._makeShadingPattern(args);
  14184. }
  14185. _makeTilingPattern(args) {
  14186. const color = args[1];
  14187. const operatorList = args[2];
  14188. const matrix = args[3] || _util.IDENTITY_MATRIX;
  14189. const [x0, y0, x1, y1] = args[4];
  14190. const xstep = args[5];
  14191. const ystep = args[6];
  14192. const paintType = args[7];
  14193. const tilingId = `shading${shadingCount++}`;
  14194. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  14195. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  14196. const txstep = xstep * xscale;
  14197. const tystep = ystep * yscale;
  14198. const tiling = this.svgFactory.createElement("svg:pattern");
  14199. tiling.setAttributeNS(null, "id", tilingId);
  14200. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  14201. tiling.setAttributeNS(null, "width", txstep);
  14202. tiling.setAttributeNS(null, "height", tystep);
  14203. tiling.setAttributeNS(null, "x", `${tx0}`);
  14204. tiling.setAttributeNS(null, "y", `${ty0}`);
  14205. const svg = this.svg;
  14206. const transformMatrix = this.transformMatrix;
  14207. const fillColor = this.current.fillColor;
  14208. const strokeColor = this.current.strokeColor;
  14209. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  14210. this.svg = bbox;
  14211. this.transformMatrix = matrix;
  14212. if (paintType === 2) {
  14213. const cssColor = _util.Util.makeHexColor(...color);
  14214. this.current.fillColor = cssColor;
  14215. this.current.strokeColor = cssColor;
  14216. }
  14217. this.executeOpTree(this.convertOpList(operatorList));
  14218. this.svg = svg;
  14219. this.transformMatrix = transformMatrix;
  14220. this.current.fillColor = fillColor;
  14221. this.current.strokeColor = strokeColor;
  14222. tiling.append(bbox.childNodes[0]);
  14223. this.defs.append(tiling);
  14224. return `url(#${tilingId})`;
  14225. }
  14226. _makeShadingPattern(args) {
  14227. if (typeof args === "string") {
  14228. args = this.objs.get(args);
  14229. }
  14230. switch (args[0]) {
  14231. case "RadialAxial":
  14232. const shadingId = `shading${shadingCount++}`;
  14233. const colorStops = args[3];
  14234. let gradient;
  14235. switch (args[1]) {
  14236. case "axial":
  14237. const point0 = args[4];
  14238. const point1 = args[5];
  14239. gradient = this.svgFactory.createElement("svg:linearGradient");
  14240. gradient.setAttributeNS(null, "id", shadingId);
  14241. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  14242. gradient.setAttributeNS(null, "x1", point0[0]);
  14243. gradient.setAttributeNS(null, "y1", point0[1]);
  14244. gradient.setAttributeNS(null, "x2", point1[0]);
  14245. gradient.setAttributeNS(null, "y2", point1[1]);
  14246. break;
  14247. case "radial":
  14248. const focalPoint = args[4];
  14249. const circlePoint = args[5];
  14250. const focalRadius = args[6];
  14251. const circleRadius = args[7];
  14252. gradient = this.svgFactory.createElement("svg:radialGradient");
  14253. gradient.setAttributeNS(null, "id", shadingId);
  14254. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  14255. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  14256. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  14257. gradient.setAttributeNS(null, "r", circleRadius);
  14258. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  14259. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  14260. gradient.setAttributeNS(null, "fr", focalRadius);
  14261. break;
  14262. default:
  14263. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  14264. }
  14265. for (const colorStop of colorStops) {
  14266. const stop = this.svgFactory.createElement("svg:stop");
  14267. stop.setAttributeNS(null, "offset", colorStop[0]);
  14268. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  14269. gradient.append(stop);
  14270. }
  14271. this.defs.append(gradient);
  14272. return `url(#${shadingId})`;
  14273. case "Mesh":
  14274. (0, _util.warn)("Unimplemented pattern Mesh");
  14275. return null;
  14276. case "Dummy":
  14277. return "hotpink";
  14278. default:
  14279. throw new Error(`Unknown IR type: ${args[0]}`);
  14280. }
  14281. }
  14282. setDash(dashArray, dashPhase) {
  14283. this.current.dashArray = dashArray;
  14284. this.current.dashPhase = dashPhase;
  14285. }
  14286. constructPath(ops, args) {
  14287. const current = this.current;
  14288. let x = current.x,
  14289. y = current.y;
  14290. let d = [];
  14291. let j = 0;
  14292. for (const op of ops) {
  14293. switch (op | 0) {
  14294. case _util.OPS.rectangle:
  14295. x = args[j++];
  14296. y = args[j++];
  14297. const width = args[j++];
  14298. const height = args[j++];
  14299. const xw = x + width;
  14300. const yh = y + height;
  14301. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  14302. break;
  14303. case _util.OPS.moveTo:
  14304. x = args[j++];
  14305. y = args[j++];
  14306. d.push("M", pf(x), pf(y));
  14307. break;
  14308. case _util.OPS.lineTo:
  14309. x = args[j++];
  14310. y = args[j++];
  14311. d.push("L", pf(x), pf(y));
  14312. break;
  14313. case _util.OPS.curveTo:
  14314. x = args[j + 4];
  14315. y = args[j + 5];
  14316. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  14317. j += 6;
  14318. break;
  14319. case _util.OPS.curveTo2:
  14320. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  14321. x = args[j + 2];
  14322. y = args[j + 3];
  14323. j += 4;
  14324. break;
  14325. case _util.OPS.curveTo3:
  14326. x = args[j + 2];
  14327. y = args[j + 3];
  14328. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  14329. j += 4;
  14330. break;
  14331. case _util.OPS.closePath:
  14332. d.push("Z");
  14333. break;
  14334. }
  14335. }
  14336. d = d.join(" ");
  14337. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  14338. d = current.path.getAttributeNS(null, "d") + d;
  14339. } else {
  14340. current.path = this.svgFactory.createElement("svg:path");
  14341. this._ensureTransformGroup().append(current.path);
  14342. }
  14343. current.path.setAttributeNS(null, "d", d);
  14344. current.path.setAttributeNS(null, "fill", "none");
  14345. current.element = current.path;
  14346. current.setCurrentPoint(x, y);
  14347. }
  14348. endPath() {
  14349. const current = this.current;
  14350. current.path = null;
  14351. if (!this.pendingClip) {
  14352. return;
  14353. }
  14354. if (!current.element) {
  14355. this.pendingClip = null;
  14356. return;
  14357. }
  14358. const clipId = `clippath${clipCount++}`;
  14359. const clipPath = this.svgFactory.createElement("svg:clipPath");
  14360. clipPath.setAttributeNS(null, "id", clipId);
  14361. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  14362. const clipElement = current.element.cloneNode(true);
  14363. if (this.pendingClip === "evenodd") {
  14364. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  14365. } else {
  14366. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  14367. }
  14368. this.pendingClip = null;
  14369. clipPath.append(clipElement);
  14370. this.defs.append(clipPath);
  14371. if (current.activeClipUrl) {
  14372. current.clipGroup = null;
  14373. for (const prev of this.extraStack) {
  14374. prev.clipGroup = null;
  14375. }
  14376. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  14377. }
  14378. current.activeClipUrl = `url(#${clipId})`;
  14379. this.tgrp = null;
  14380. }
  14381. clip(type) {
  14382. this.pendingClip = type;
  14383. }
  14384. closePath() {
  14385. const current = this.current;
  14386. if (current.path) {
  14387. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  14388. current.path.setAttributeNS(null, "d", d);
  14389. }
  14390. }
  14391. setLeading(leading) {
  14392. this.current.leading = -leading;
  14393. }
  14394. setTextRise(textRise) {
  14395. this.current.textRise = textRise;
  14396. }
  14397. setTextRenderingMode(textRenderingMode) {
  14398. this.current.textRenderingMode = textRenderingMode;
  14399. }
  14400. setHScale(scale) {
  14401. this.current.textHScale = scale / 100;
  14402. }
  14403. setRenderingIntent(intent) {}
  14404. setFlatness(flatness) {}
  14405. setGState(states) {
  14406. for (const [key, value] of states) {
  14407. switch (key) {
  14408. case "LW":
  14409. this.setLineWidth(value);
  14410. break;
  14411. case "LC":
  14412. this.setLineCap(value);
  14413. break;
  14414. case "LJ":
  14415. this.setLineJoin(value);
  14416. break;
  14417. case "ML":
  14418. this.setMiterLimit(value);
  14419. break;
  14420. case "D":
  14421. this.setDash(value[0], value[1]);
  14422. break;
  14423. case "RI":
  14424. this.setRenderingIntent(value);
  14425. break;
  14426. case "FL":
  14427. this.setFlatness(value);
  14428. break;
  14429. case "Font":
  14430. this.setFont(value);
  14431. break;
  14432. case "CA":
  14433. this.setStrokeAlpha(value);
  14434. break;
  14435. case "ca":
  14436. this.setFillAlpha(value);
  14437. break;
  14438. default:
  14439. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  14440. break;
  14441. }
  14442. }
  14443. }
  14444. fill() {
  14445. const current = this.current;
  14446. if (current.element) {
  14447. current.element.setAttributeNS(null, "fill", current.fillColor);
  14448. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  14449. this.endPath();
  14450. }
  14451. }
  14452. stroke() {
  14453. const current = this.current;
  14454. if (current.element) {
  14455. this._setStrokeAttributes(current.element);
  14456. current.element.setAttributeNS(null, "fill", "none");
  14457. this.endPath();
  14458. }
  14459. }
  14460. _setStrokeAttributes(element, lineWidthScale = 1) {
  14461. const current = this.current;
  14462. let dashArray = current.dashArray;
  14463. if (lineWidthScale !== 1 && dashArray.length > 0) {
  14464. dashArray = dashArray.map(function (value) {
  14465. return lineWidthScale * value;
  14466. });
  14467. }
  14468. element.setAttributeNS(null, "stroke", current.strokeColor);
  14469. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  14470. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  14471. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  14472. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  14473. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  14474. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  14475. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  14476. }
  14477. eoFill() {
  14478. if (this.current.element) {
  14479. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  14480. }
  14481. this.fill();
  14482. }
  14483. fillStroke() {
  14484. this.stroke();
  14485. this.fill();
  14486. }
  14487. eoFillStroke() {
  14488. if (this.current.element) {
  14489. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  14490. }
  14491. this.fillStroke();
  14492. }
  14493. closeStroke() {
  14494. this.closePath();
  14495. this.stroke();
  14496. }
  14497. closeFillStroke() {
  14498. this.closePath();
  14499. this.fillStroke();
  14500. }
  14501. closeEOFillStroke() {
  14502. this.closePath();
  14503. this.eoFillStroke();
  14504. }
  14505. paintSolidColorImageMask() {
  14506. const rect = this.svgFactory.createElement("svg:rect");
  14507. rect.setAttributeNS(null, "x", "0");
  14508. rect.setAttributeNS(null, "y", "0");
  14509. rect.setAttributeNS(null, "width", "1px");
  14510. rect.setAttributeNS(null, "height", "1px");
  14511. rect.setAttributeNS(null, "fill", this.current.fillColor);
  14512. this._ensureTransformGroup().append(rect);
  14513. }
  14514. paintImageXObject(objId) {
  14515. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  14516. if (!imgData) {
  14517. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  14518. return;
  14519. }
  14520. this.paintInlineImageXObject(imgData);
  14521. }
  14522. paintInlineImageXObject(imgData, mask) {
  14523. const width = imgData.width;
  14524. const height = imgData.height;
  14525. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  14526. const cliprect = this.svgFactory.createElement("svg:rect");
  14527. cliprect.setAttributeNS(null, "x", "0");
  14528. cliprect.setAttributeNS(null, "y", "0");
  14529. cliprect.setAttributeNS(null, "width", pf(width));
  14530. cliprect.setAttributeNS(null, "height", pf(height));
  14531. this.current.element = cliprect;
  14532. this.clip("nonzero");
  14533. const imgEl = this.svgFactory.createElement("svg:image");
  14534. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  14535. imgEl.setAttributeNS(null, "x", "0");
  14536. imgEl.setAttributeNS(null, "y", pf(-height));
  14537. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  14538. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  14539. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  14540. if (mask) {
  14541. mask.append(imgEl);
  14542. } else {
  14543. this._ensureTransformGroup().append(imgEl);
  14544. }
  14545. }
  14546. paintImageMaskXObject(imgData) {
  14547. const current = this.current;
  14548. const width = imgData.width;
  14549. const height = imgData.height;
  14550. const fillColor = current.fillColor;
  14551. current.maskId = `mask${maskCount++}`;
  14552. const mask = this.svgFactory.createElement("svg:mask");
  14553. mask.setAttributeNS(null, "id", current.maskId);
  14554. const rect = this.svgFactory.createElement("svg:rect");
  14555. rect.setAttributeNS(null, "x", "0");
  14556. rect.setAttributeNS(null, "y", "0");
  14557. rect.setAttributeNS(null, "width", pf(width));
  14558. rect.setAttributeNS(null, "height", pf(height));
  14559. rect.setAttributeNS(null, "fill", fillColor);
  14560. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  14561. this.defs.append(mask);
  14562. this._ensureTransformGroup().append(rect);
  14563. this.paintInlineImageXObject(imgData, mask);
  14564. }
  14565. paintFormXObjectBegin(matrix, bbox) {
  14566. if (Array.isArray(matrix) && matrix.length === 6) {
  14567. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  14568. }
  14569. if (bbox) {
  14570. const width = bbox[2] - bbox[0];
  14571. const height = bbox[3] - bbox[1];
  14572. const cliprect = this.svgFactory.createElement("svg:rect");
  14573. cliprect.setAttributeNS(null, "x", bbox[0]);
  14574. cliprect.setAttributeNS(null, "y", bbox[1]);
  14575. cliprect.setAttributeNS(null, "width", pf(width));
  14576. cliprect.setAttributeNS(null, "height", pf(height));
  14577. this.current.element = cliprect;
  14578. this.clip("nonzero");
  14579. this.endPath();
  14580. }
  14581. }
  14582. paintFormXObjectEnd() {}
  14583. _initialize(viewport) {
  14584. const svg = this.svgFactory.create(viewport.width, viewport.height);
  14585. const definitions = this.svgFactory.createElement("svg:defs");
  14586. svg.append(definitions);
  14587. this.defs = definitions;
  14588. const rootGroup = this.svgFactory.createElement("svg:g");
  14589. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  14590. svg.append(rootGroup);
  14591. this.svg = rootGroup;
  14592. return svg;
  14593. }
  14594. _ensureClipGroup() {
  14595. if (!this.current.clipGroup) {
  14596. const clipGroup = this.svgFactory.createElement("svg:g");
  14597. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  14598. this.svg.append(clipGroup);
  14599. this.current.clipGroup = clipGroup;
  14600. }
  14601. return this.current.clipGroup;
  14602. }
  14603. _ensureTransformGroup() {
  14604. if (!this.tgrp) {
  14605. this.tgrp = this.svgFactory.createElement("svg:g");
  14606. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  14607. if (this.current.activeClipUrl) {
  14608. this._ensureClipGroup().append(this.tgrp);
  14609. } else {
  14610. this.svg.append(this.tgrp);
  14611. }
  14612. }
  14613. return this.tgrp;
  14614. }
  14615. };
  14616. }
  14617. /***/ }),
  14618. /* 32 */
  14619. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14620. Object.defineProperty(exports, "__esModule", ({
  14621. value: true
  14622. }));
  14623. exports.PDFNodeStream = void 0;
  14624. var _util = __w_pdfjs_require__(1);
  14625. var _network_utils = __w_pdfjs_require__(33);
  14626. ;
  14627. const fs = require("fs");
  14628. const http = require("http");
  14629. const https = require("https");
  14630. const url = require("url");
  14631. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  14632. function parseUrl(sourceUrl) {
  14633. const parsedUrl = url.parse(sourceUrl);
  14634. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  14635. return parsedUrl;
  14636. }
  14637. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  14638. return url.parse(`file:///${sourceUrl}`);
  14639. }
  14640. if (!parsedUrl.host) {
  14641. parsedUrl.protocol = "file:";
  14642. }
  14643. return parsedUrl;
  14644. }
  14645. class PDFNodeStream {
  14646. constructor(source) {
  14647. this.source = source;
  14648. this.url = parseUrl(source.url);
  14649. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  14650. this.isFsUrl = this.url.protocol === "file:";
  14651. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  14652. this._fullRequestReader = null;
  14653. this._rangeRequestReaders = [];
  14654. }
  14655. get _progressiveDataLength() {
  14656. return this._fullRequestReader?._loaded ?? 0;
  14657. }
  14658. getFullReader() {
  14659. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  14660. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  14661. return this._fullRequestReader;
  14662. }
  14663. getRangeReader(start, end) {
  14664. if (end <= this._progressiveDataLength) {
  14665. return null;
  14666. }
  14667. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  14668. this._rangeRequestReaders.push(rangeReader);
  14669. return rangeReader;
  14670. }
  14671. cancelAllRequests(reason) {
  14672. if (this._fullRequestReader) {
  14673. this._fullRequestReader.cancel(reason);
  14674. }
  14675. for (const reader of this._rangeRequestReaders.slice(0)) {
  14676. reader.cancel(reason);
  14677. }
  14678. }
  14679. }
  14680. exports.PDFNodeStream = PDFNodeStream;
  14681. class BaseFullReader {
  14682. constructor(stream) {
  14683. this._url = stream.url;
  14684. this._done = false;
  14685. this._storedError = null;
  14686. this.onProgress = null;
  14687. const source = stream.source;
  14688. this._contentLength = source.length;
  14689. this._loaded = 0;
  14690. this._filename = null;
  14691. this._disableRange = source.disableRange || false;
  14692. this._rangeChunkSize = source.rangeChunkSize;
  14693. if (!this._rangeChunkSize && !this._disableRange) {
  14694. this._disableRange = true;
  14695. }
  14696. this._isStreamingSupported = !source.disableStream;
  14697. this._isRangeSupported = !source.disableRange;
  14698. this._readableStream = null;
  14699. this._readCapability = (0, _util.createPromiseCapability)();
  14700. this._headersCapability = (0, _util.createPromiseCapability)();
  14701. }
  14702. get headersReady() {
  14703. return this._headersCapability.promise;
  14704. }
  14705. get filename() {
  14706. return this._filename;
  14707. }
  14708. get contentLength() {
  14709. return this._contentLength;
  14710. }
  14711. get isRangeSupported() {
  14712. return this._isRangeSupported;
  14713. }
  14714. get isStreamingSupported() {
  14715. return this._isStreamingSupported;
  14716. }
  14717. async read() {
  14718. await this._readCapability.promise;
  14719. if (this._done) {
  14720. return {
  14721. value: undefined,
  14722. done: true
  14723. };
  14724. }
  14725. if (this._storedError) {
  14726. throw this._storedError;
  14727. }
  14728. const chunk = this._readableStream.read();
  14729. if (chunk === null) {
  14730. this._readCapability = (0, _util.createPromiseCapability)();
  14731. return this.read();
  14732. }
  14733. this._loaded += chunk.length;
  14734. if (this.onProgress) {
  14735. this.onProgress({
  14736. loaded: this._loaded,
  14737. total: this._contentLength
  14738. });
  14739. }
  14740. const buffer = new Uint8Array(chunk).buffer;
  14741. return {
  14742. value: buffer,
  14743. done: false
  14744. };
  14745. }
  14746. cancel(reason) {
  14747. if (!this._readableStream) {
  14748. this._error(reason);
  14749. return;
  14750. }
  14751. this._readableStream.destroy(reason);
  14752. }
  14753. _error(reason) {
  14754. this._storedError = reason;
  14755. this._readCapability.resolve();
  14756. }
  14757. _setReadableStream(readableStream) {
  14758. this._readableStream = readableStream;
  14759. readableStream.on("readable", () => {
  14760. this._readCapability.resolve();
  14761. });
  14762. readableStream.on("end", () => {
  14763. readableStream.destroy();
  14764. this._done = true;
  14765. this._readCapability.resolve();
  14766. });
  14767. readableStream.on("error", reason => {
  14768. this._error(reason);
  14769. });
  14770. if (!this._isStreamingSupported && this._isRangeSupported) {
  14771. this._error(new _util.AbortException("streaming is disabled"));
  14772. }
  14773. if (this._storedError) {
  14774. this._readableStream.destroy(this._storedError);
  14775. }
  14776. }
  14777. }
  14778. class BaseRangeReader {
  14779. constructor(stream) {
  14780. this._url = stream.url;
  14781. this._done = false;
  14782. this._storedError = null;
  14783. this.onProgress = null;
  14784. this._loaded = 0;
  14785. this._readableStream = null;
  14786. this._readCapability = (0, _util.createPromiseCapability)();
  14787. const source = stream.source;
  14788. this._isStreamingSupported = !source.disableStream;
  14789. }
  14790. get isStreamingSupported() {
  14791. return this._isStreamingSupported;
  14792. }
  14793. async read() {
  14794. await this._readCapability.promise;
  14795. if (this._done) {
  14796. return {
  14797. value: undefined,
  14798. done: true
  14799. };
  14800. }
  14801. if (this._storedError) {
  14802. throw this._storedError;
  14803. }
  14804. const chunk = this._readableStream.read();
  14805. if (chunk === null) {
  14806. this._readCapability = (0, _util.createPromiseCapability)();
  14807. return this.read();
  14808. }
  14809. this._loaded += chunk.length;
  14810. if (this.onProgress) {
  14811. this.onProgress({
  14812. loaded: this._loaded
  14813. });
  14814. }
  14815. const buffer = new Uint8Array(chunk).buffer;
  14816. return {
  14817. value: buffer,
  14818. done: false
  14819. };
  14820. }
  14821. cancel(reason) {
  14822. if (!this._readableStream) {
  14823. this._error(reason);
  14824. return;
  14825. }
  14826. this._readableStream.destroy(reason);
  14827. }
  14828. _error(reason) {
  14829. this._storedError = reason;
  14830. this._readCapability.resolve();
  14831. }
  14832. _setReadableStream(readableStream) {
  14833. this._readableStream = readableStream;
  14834. readableStream.on("readable", () => {
  14835. this._readCapability.resolve();
  14836. });
  14837. readableStream.on("end", () => {
  14838. readableStream.destroy();
  14839. this._done = true;
  14840. this._readCapability.resolve();
  14841. });
  14842. readableStream.on("error", reason => {
  14843. this._error(reason);
  14844. });
  14845. if (this._storedError) {
  14846. this._readableStream.destroy(this._storedError);
  14847. }
  14848. }
  14849. }
  14850. function createRequestOptions(parsedUrl, headers) {
  14851. return {
  14852. protocol: parsedUrl.protocol,
  14853. auth: parsedUrl.auth,
  14854. host: parsedUrl.hostname,
  14855. port: parsedUrl.port,
  14856. path: parsedUrl.path,
  14857. method: "GET",
  14858. headers
  14859. };
  14860. }
  14861. class PDFNodeStreamFullReader extends BaseFullReader {
  14862. constructor(stream) {
  14863. super(stream);
  14864. const handleResponse = response => {
  14865. if (response.statusCode === 404) {
  14866. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14867. this._storedError = error;
  14868. this._headersCapability.reject(error);
  14869. return;
  14870. }
  14871. this._headersCapability.resolve();
  14872. this._setReadableStream(response);
  14873. const getResponseHeader = name => {
  14874. return this._readableStream.headers[name.toLowerCase()];
  14875. };
  14876. const {
  14877. allowRangeRequests,
  14878. suggestedLength
  14879. } = (0, _network_utils.validateRangeRequestCapabilities)({
  14880. getResponseHeader,
  14881. isHttp: stream.isHttp,
  14882. rangeChunkSize: this._rangeChunkSize,
  14883. disableRange: this._disableRange
  14884. });
  14885. this._isRangeSupported = allowRangeRequests;
  14886. this._contentLength = suggestedLength || this._contentLength;
  14887. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  14888. };
  14889. this._request = null;
  14890. if (this._url.protocol === "http:") {
  14891. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14892. } else {
  14893. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14894. }
  14895. this._request.on("error", reason => {
  14896. this._storedError = reason;
  14897. this._headersCapability.reject(reason);
  14898. });
  14899. this._request.end();
  14900. }
  14901. }
  14902. class PDFNodeStreamRangeReader extends BaseRangeReader {
  14903. constructor(stream, start, end) {
  14904. super(stream);
  14905. this._httpHeaders = {};
  14906. for (const property in stream.httpHeaders) {
  14907. const value = stream.httpHeaders[property];
  14908. if (typeof value === "undefined") {
  14909. continue;
  14910. }
  14911. this._httpHeaders[property] = value;
  14912. }
  14913. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  14914. const handleResponse = response => {
  14915. if (response.statusCode === 404) {
  14916. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14917. this._storedError = error;
  14918. return;
  14919. }
  14920. this._setReadableStream(response);
  14921. };
  14922. this._request = null;
  14923. if (this._url.protocol === "http:") {
  14924. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14925. } else {
  14926. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14927. }
  14928. this._request.on("error", reason => {
  14929. this._storedError = reason;
  14930. });
  14931. this._request.end();
  14932. }
  14933. }
  14934. class PDFNodeStreamFsFullReader extends BaseFullReader {
  14935. constructor(stream) {
  14936. super(stream);
  14937. let path = decodeURIComponent(this._url.path);
  14938. if (fileUriRegex.test(this._url.href)) {
  14939. path = path.replace(/^\//, "");
  14940. }
  14941. fs.lstat(path, (error, stat) => {
  14942. if (error) {
  14943. if (error.code === "ENOENT") {
  14944. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  14945. }
  14946. this._storedError = error;
  14947. this._headersCapability.reject(error);
  14948. return;
  14949. }
  14950. this._contentLength = stat.size;
  14951. this._setReadableStream(fs.createReadStream(path));
  14952. this._headersCapability.resolve();
  14953. });
  14954. }
  14955. }
  14956. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  14957. constructor(stream, start, end) {
  14958. super(stream);
  14959. let path = decodeURIComponent(this._url.path);
  14960. if (fileUriRegex.test(this._url.href)) {
  14961. path = path.replace(/^\//, "");
  14962. }
  14963. this._setReadableStream(fs.createReadStream(path, {
  14964. start,
  14965. end: end - 1
  14966. }));
  14967. }
  14968. }
  14969. /***/ }),
  14970. /* 33 */
  14971. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14972. Object.defineProperty(exports, "__esModule", ({
  14973. value: true
  14974. }));
  14975. exports.createResponseStatusError = createResponseStatusError;
  14976. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  14977. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  14978. exports.validateResponseStatus = validateResponseStatus;
  14979. var _util = __w_pdfjs_require__(1);
  14980. var _content_disposition = __w_pdfjs_require__(34);
  14981. var _display_utils = __w_pdfjs_require__(4);
  14982. function validateRangeRequestCapabilities({
  14983. getResponseHeader,
  14984. isHttp,
  14985. rangeChunkSize,
  14986. disableRange
  14987. }) {
  14988. const returnValues = {
  14989. allowRangeRequests: false,
  14990. suggestedLength: undefined
  14991. };
  14992. const length = parseInt(getResponseHeader("Content-Length"), 10);
  14993. if (!Number.isInteger(length)) {
  14994. return returnValues;
  14995. }
  14996. returnValues.suggestedLength = length;
  14997. if (length <= 2 * rangeChunkSize) {
  14998. return returnValues;
  14999. }
  15000. if (disableRange || !isHttp) {
  15001. return returnValues;
  15002. }
  15003. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  15004. return returnValues;
  15005. }
  15006. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  15007. if (contentEncoding !== "identity") {
  15008. return returnValues;
  15009. }
  15010. returnValues.allowRangeRequests = true;
  15011. return returnValues;
  15012. }
  15013. function extractFilenameFromHeader(getResponseHeader) {
  15014. const contentDisposition = getResponseHeader("Content-Disposition");
  15015. if (contentDisposition) {
  15016. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  15017. if (filename.includes("%")) {
  15018. try {
  15019. filename = decodeURIComponent(filename);
  15020. } catch (ex) {}
  15021. }
  15022. if ((0, _display_utils.isPdfFile)(filename)) {
  15023. return filename;
  15024. }
  15025. }
  15026. return null;
  15027. }
  15028. function createResponseStatusError(status, url) {
  15029. if (status === 404 || status === 0 && url.startsWith("file:")) {
  15030. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  15031. }
  15032. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  15033. }
  15034. function validateResponseStatus(status) {
  15035. return status === 200 || status === 206;
  15036. }
  15037. /***/ }),
  15038. /* 34 */
  15039. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  15040. Object.defineProperty(exports, "__esModule", ({
  15041. value: true
  15042. }));
  15043. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  15044. var _util = __w_pdfjs_require__(1);
  15045. function getFilenameFromContentDispositionHeader(contentDisposition) {
  15046. let needsEncodingFixup = true;
  15047. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  15048. if (tmp) {
  15049. tmp = tmp[1];
  15050. let filename = rfc2616unquote(tmp);
  15051. filename = unescape(filename);
  15052. filename = rfc5987decode(filename);
  15053. filename = rfc2047decode(filename);
  15054. return fixupEncoding(filename);
  15055. }
  15056. tmp = rfc2231getparam(contentDisposition);
  15057. if (tmp) {
  15058. const filename = rfc2047decode(tmp);
  15059. return fixupEncoding(filename);
  15060. }
  15061. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  15062. if (tmp) {
  15063. tmp = tmp[1];
  15064. let filename = rfc2616unquote(tmp);
  15065. filename = rfc2047decode(filename);
  15066. return fixupEncoding(filename);
  15067. }
  15068. function toParamRegExp(attributePattern, flags) {
  15069. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  15070. }
  15071. function textdecode(encoding, value) {
  15072. if (encoding) {
  15073. if (!/^[\x00-\xFF]+$/.test(value)) {
  15074. return value;
  15075. }
  15076. try {
  15077. const decoder = new TextDecoder(encoding, {
  15078. fatal: true
  15079. });
  15080. const buffer = (0, _util.stringToBytes)(value);
  15081. value = decoder.decode(buffer);
  15082. needsEncodingFixup = false;
  15083. } catch (e) {}
  15084. }
  15085. return value;
  15086. }
  15087. function fixupEncoding(value) {
  15088. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  15089. value = textdecode("utf-8", value);
  15090. if (needsEncodingFixup) {
  15091. value = textdecode("iso-8859-1", value);
  15092. }
  15093. }
  15094. return value;
  15095. }
  15096. function rfc2231getparam(contentDispositionStr) {
  15097. const matches = [];
  15098. let match;
  15099. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  15100. while ((match = iter.exec(contentDispositionStr)) !== null) {
  15101. let [, n, quot, part] = match;
  15102. n = parseInt(n, 10);
  15103. if (n in matches) {
  15104. if (n === 0) {
  15105. break;
  15106. }
  15107. continue;
  15108. }
  15109. matches[n] = [quot, part];
  15110. }
  15111. const parts = [];
  15112. for (let n = 0; n < matches.length; ++n) {
  15113. if (!(n in matches)) {
  15114. break;
  15115. }
  15116. let [quot, part] = matches[n];
  15117. part = rfc2616unquote(part);
  15118. if (quot) {
  15119. part = unescape(part);
  15120. if (n === 0) {
  15121. part = rfc5987decode(part);
  15122. }
  15123. }
  15124. parts.push(part);
  15125. }
  15126. return parts.join("");
  15127. }
  15128. function rfc2616unquote(value) {
  15129. if (value.startsWith('"')) {
  15130. const parts = value.slice(1).split('\\"');
  15131. for (let i = 0; i < parts.length; ++i) {
  15132. const quotindex = parts[i].indexOf('"');
  15133. if (quotindex !== -1) {
  15134. parts[i] = parts[i].slice(0, quotindex);
  15135. parts.length = i + 1;
  15136. }
  15137. parts[i] = parts[i].replace(/\\(.)/g, "$1");
  15138. }
  15139. value = parts.join('"');
  15140. }
  15141. return value;
  15142. }
  15143. function rfc5987decode(extvalue) {
  15144. const encodingend = extvalue.indexOf("'");
  15145. if (encodingend === -1) {
  15146. return extvalue;
  15147. }
  15148. const encoding = extvalue.slice(0, encodingend);
  15149. const langvalue = extvalue.slice(encodingend + 1);
  15150. const value = langvalue.replace(/^[^']*'/, "");
  15151. return textdecode(encoding, value);
  15152. }
  15153. function rfc2047decode(value) {
  15154. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  15155. return value;
  15156. }
  15157. return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  15158. if (encoding === "q" || encoding === "Q") {
  15159. text = text.replace(/_/g, " ");
  15160. text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  15161. return String.fromCharCode(parseInt(hex, 16));
  15162. });
  15163. return textdecode(charset, text);
  15164. }
  15165. try {
  15166. text = atob(text);
  15167. } catch (e) {}
  15168. return textdecode(charset, text);
  15169. });
  15170. }
  15171. return "";
  15172. }
  15173. /***/ }),
  15174. /* 35 */
  15175. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  15176. Object.defineProperty(exports, "__esModule", ({
  15177. value: true
  15178. }));
  15179. exports.PDFNetworkStream = void 0;
  15180. var _util = __w_pdfjs_require__(1);
  15181. var _network_utils = __w_pdfjs_require__(33);
  15182. ;
  15183. const OK_RESPONSE = 200;
  15184. const PARTIAL_CONTENT_RESPONSE = 206;
  15185. function getArrayBuffer(xhr) {
  15186. const data = xhr.response;
  15187. if (typeof data !== "string") {
  15188. return data;
  15189. }
  15190. const array = (0, _util.stringToBytes)(data);
  15191. return array.buffer;
  15192. }
  15193. class NetworkManager {
  15194. constructor(url, args = {}) {
  15195. this.url = url;
  15196. this.isHttp = /^https?:/i.test(url);
  15197. this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
  15198. this.withCredentials = args.withCredentials || false;
  15199. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  15200. return new XMLHttpRequest();
  15201. };
  15202. this.currXhrId = 0;
  15203. this.pendingRequests = Object.create(null);
  15204. }
  15205. requestRange(begin, end, listeners) {
  15206. const args = {
  15207. begin,
  15208. end
  15209. };
  15210. for (const prop in listeners) {
  15211. args[prop] = listeners[prop];
  15212. }
  15213. return this.request(args);
  15214. }
  15215. requestFull(listeners) {
  15216. return this.request(listeners);
  15217. }
  15218. request(args) {
  15219. const xhr = this.getXhr();
  15220. const xhrId = this.currXhrId++;
  15221. const pendingRequest = this.pendingRequests[xhrId] = {
  15222. xhr
  15223. };
  15224. xhr.open("GET", this.url);
  15225. xhr.withCredentials = this.withCredentials;
  15226. for (const property in this.httpHeaders) {
  15227. const value = this.httpHeaders[property];
  15228. if (typeof value === "undefined") {
  15229. continue;
  15230. }
  15231. xhr.setRequestHeader(property, value);
  15232. }
  15233. if (this.isHttp && "begin" in args && "end" in args) {
  15234. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  15235. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  15236. } else {
  15237. pendingRequest.expectedStatus = OK_RESPONSE;
  15238. }
  15239. xhr.responseType = "arraybuffer";
  15240. if (args.onError) {
  15241. xhr.onerror = function (evt) {
  15242. args.onError(xhr.status);
  15243. };
  15244. }
  15245. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  15246. xhr.onprogress = this.onProgress.bind(this, xhrId);
  15247. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  15248. pendingRequest.onDone = args.onDone;
  15249. pendingRequest.onError = args.onError;
  15250. pendingRequest.onProgress = args.onProgress;
  15251. xhr.send(null);
  15252. return xhrId;
  15253. }
  15254. onProgress(xhrId, evt) {
  15255. const pendingRequest = this.pendingRequests[xhrId];
  15256. if (!pendingRequest) {
  15257. return;
  15258. }
  15259. pendingRequest.onProgress?.(evt);
  15260. }
  15261. onStateChange(xhrId, evt) {
  15262. const pendingRequest = this.pendingRequests[xhrId];
  15263. if (!pendingRequest) {
  15264. return;
  15265. }
  15266. const xhr = pendingRequest.xhr;
  15267. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  15268. pendingRequest.onHeadersReceived();
  15269. delete pendingRequest.onHeadersReceived;
  15270. }
  15271. if (xhr.readyState !== 4) {
  15272. return;
  15273. }
  15274. if (!(xhrId in this.pendingRequests)) {
  15275. return;
  15276. }
  15277. delete this.pendingRequests[xhrId];
  15278. if (xhr.status === 0 && this.isHttp) {
  15279. pendingRequest.onError?.(xhr.status);
  15280. return;
  15281. }
  15282. const xhrStatus = xhr.status || OK_RESPONSE;
  15283. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  15284. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  15285. pendingRequest.onError?.(xhr.status);
  15286. return;
  15287. }
  15288. const chunk = getArrayBuffer(xhr);
  15289. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  15290. const rangeHeader = xhr.getResponseHeader("Content-Range");
  15291. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  15292. pendingRequest.onDone({
  15293. begin: parseInt(matches[1], 10),
  15294. chunk
  15295. });
  15296. } else if (chunk) {
  15297. pendingRequest.onDone({
  15298. begin: 0,
  15299. chunk
  15300. });
  15301. } else {
  15302. pendingRequest.onError?.(xhr.status);
  15303. }
  15304. }
  15305. getRequestXhr(xhrId) {
  15306. return this.pendingRequests[xhrId].xhr;
  15307. }
  15308. isPendingRequest(xhrId) {
  15309. return xhrId in this.pendingRequests;
  15310. }
  15311. abortRequest(xhrId) {
  15312. const xhr = this.pendingRequests[xhrId].xhr;
  15313. delete this.pendingRequests[xhrId];
  15314. xhr.abort();
  15315. }
  15316. }
  15317. class PDFNetworkStream {
  15318. constructor(source) {
  15319. this._source = source;
  15320. this._manager = new NetworkManager(source.url, {
  15321. httpHeaders: source.httpHeaders,
  15322. withCredentials: source.withCredentials
  15323. });
  15324. this._rangeChunkSize = source.rangeChunkSize;
  15325. this._fullRequestReader = null;
  15326. this._rangeRequestReaders = [];
  15327. }
  15328. _onRangeRequestReaderClosed(reader) {
  15329. const i = this._rangeRequestReaders.indexOf(reader);
  15330. if (i >= 0) {
  15331. this._rangeRequestReaders.splice(i, 1);
  15332. }
  15333. }
  15334. getFullReader() {
  15335. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  15336. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  15337. return this._fullRequestReader;
  15338. }
  15339. getRangeReader(begin, end) {
  15340. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  15341. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  15342. this._rangeRequestReaders.push(reader);
  15343. return reader;
  15344. }
  15345. cancelAllRequests(reason) {
  15346. this._fullRequestReader?.cancel(reason);
  15347. for (const reader of this._rangeRequestReaders.slice(0)) {
  15348. reader.cancel(reason);
  15349. }
  15350. }
  15351. }
  15352. exports.PDFNetworkStream = PDFNetworkStream;
  15353. class PDFNetworkStreamFullRequestReader {
  15354. constructor(manager, source) {
  15355. this._manager = manager;
  15356. const args = {
  15357. onHeadersReceived: this._onHeadersReceived.bind(this),
  15358. onDone: this._onDone.bind(this),
  15359. onError: this._onError.bind(this),
  15360. onProgress: this._onProgress.bind(this)
  15361. };
  15362. this._url = source.url;
  15363. this._fullRequestId = manager.requestFull(args);
  15364. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  15365. this._disableRange = source.disableRange || false;
  15366. this._contentLength = source.length;
  15367. this._rangeChunkSize = source.rangeChunkSize;
  15368. if (!this._rangeChunkSize && !this._disableRange) {
  15369. this._disableRange = true;
  15370. }
  15371. this._isStreamingSupported = false;
  15372. this._isRangeSupported = false;
  15373. this._cachedChunks = [];
  15374. this._requests = [];
  15375. this._done = false;
  15376. this._storedError = undefined;
  15377. this._filename = null;
  15378. this.onProgress = null;
  15379. }
  15380. _onHeadersReceived() {
  15381. const fullRequestXhrId = this._fullRequestId;
  15382. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  15383. const getResponseHeader = name => {
  15384. return fullRequestXhr.getResponseHeader(name);
  15385. };
  15386. const {
  15387. allowRangeRequests,
  15388. suggestedLength
  15389. } = (0, _network_utils.validateRangeRequestCapabilities)({
  15390. getResponseHeader,
  15391. isHttp: this._manager.isHttp,
  15392. rangeChunkSize: this._rangeChunkSize,
  15393. disableRange: this._disableRange
  15394. });
  15395. if (allowRangeRequests) {
  15396. this._isRangeSupported = true;
  15397. }
  15398. this._contentLength = suggestedLength || this._contentLength;
  15399. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  15400. if (this._isRangeSupported) {
  15401. this._manager.abortRequest(fullRequestXhrId);
  15402. }
  15403. this._headersReceivedCapability.resolve();
  15404. }
  15405. _onDone(data) {
  15406. if (data) {
  15407. if (this._requests.length > 0) {
  15408. const requestCapability = this._requests.shift();
  15409. requestCapability.resolve({
  15410. value: data.chunk,
  15411. done: false
  15412. });
  15413. } else {
  15414. this._cachedChunks.push(data.chunk);
  15415. }
  15416. }
  15417. this._done = true;
  15418. if (this._cachedChunks.length > 0) {
  15419. return;
  15420. }
  15421. for (const requestCapability of this._requests) {
  15422. requestCapability.resolve({
  15423. value: undefined,
  15424. done: true
  15425. });
  15426. }
  15427. this._requests.length = 0;
  15428. }
  15429. _onError(status) {
  15430. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  15431. this._headersReceivedCapability.reject(this._storedError);
  15432. for (const requestCapability of this._requests) {
  15433. requestCapability.reject(this._storedError);
  15434. }
  15435. this._requests.length = 0;
  15436. this._cachedChunks.length = 0;
  15437. }
  15438. _onProgress(evt) {
  15439. this.onProgress?.({
  15440. loaded: evt.loaded,
  15441. total: evt.lengthComputable ? evt.total : this._contentLength
  15442. });
  15443. }
  15444. get filename() {
  15445. return this._filename;
  15446. }
  15447. get isRangeSupported() {
  15448. return this._isRangeSupported;
  15449. }
  15450. get isStreamingSupported() {
  15451. return this._isStreamingSupported;
  15452. }
  15453. get contentLength() {
  15454. return this._contentLength;
  15455. }
  15456. get headersReady() {
  15457. return this._headersReceivedCapability.promise;
  15458. }
  15459. async read() {
  15460. if (this._storedError) {
  15461. throw this._storedError;
  15462. }
  15463. if (this._cachedChunks.length > 0) {
  15464. const chunk = this._cachedChunks.shift();
  15465. return {
  15466. value: chunk,
  15467. done: false
  15468. };
  15469. }
  15470. if (this._done) {
  15471. return {
  15472. value: undefined,
  15473. done: true
  15474. };
  15475. }
  15476. const requestCapability = (0, _util.createPromiseCapability)();
  15477. this._requests.push(requestCapability);
  15478. return requestCapability.promise;
  15479. }
  15480. cancel(reason) {
  15481. this._done = true;
  15482. this._headersReceivedCapability.reject(reason);
  15483. for (const requestCapability of this._requests) {
  15484. requestCapability.resolve({
  15485. value: undefined,
  15486. done: true
  15487. });
  15488. }
  15489. this._requests.length = 0;
  15490. if (this._manager.isPendingRequest(this._fullRequestId)) {
  15491. this._manager.abortRequest(this._fullRequestId);
  15492. }
  15493. this._fullRequestReader = null;
  15494. }
  15495. }
  15496. class PDFNetworkStreamRangeRequestReader {
  15497. constructor(manager, begin, end) {
  15498. this._manager = manager;
  15499. const args = {
  15500. onDone: this._onDone.bind(this),
  15501. onError: this._onError.bind(this),
  15502. onProgress: this._onProgress.bind(this)
  15503. };
  15504. this._url = manager.url;
  15505. this._requestId = manager.requestRange(begin, end, args);
  15506. this._requests = [];
  15507. this._queuedChunk = null;
  15508. this._done = false;
  15509. this._storedError = undefined;
  15510. this.onProgress = null;
  15511. this.onClosed = null;
  15512. }
  15513. _close() {
  15514. this.onClosed?.(this);
  15515. }
  15516. _onDone(data) {
  15517. const chunk = data.chunk;
  15518. if (this._requests.length > 0) {
  15519. const requestCapability = this._requests.shift();
  15520. requestCapability.resolve({
  15521. value: chunk,
  15522. done: false
  15523. });
  15524. } else {
  15525. this._queuedChunk = chunk;
  15526. }
  15527. this._done = true;
  15528. for (const requestCapability of this._requests) {
  15529. requestCapability.resolve({
  15530. value: undefined,
  15531. done: true
  15532. });
  15533. }
  15534. this._requests.length = 0;
  15535. this._close();
  15536. }
  15537. _onError(status) {
  15538. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  15539. for (const requestCapability of this._requests) {
  15540. requestCapability.reject(this._storedError);
  15541. }
  15542. this._requests.length = 0;
  15543. this._queuedChunk = null;
  15544. }
  15545. _onProgress(evt) {
  15546. if (!this.isStreamingSupported) {
  15547. this.onProgress?.({
  15548. loaded: evt.loaded
  15549. });
  15550. }
  15551. }
  15552. get isStreamingSupported() {
  15553. return false;
  15554. }
  15555. async read() {
  15556. if (this._storedError) {
  15557. throw this._storedError;
  15558. }
  15559. if (this._queuedChunk !== null) {
  15560. const chunk = this._queuedChunk;
  15561. this._queuedChunk = null;
  15562. return {
  15563. value: chunk,
  15564. done: false
  15565. };
  15566. }
  15567. if (this._done) {
  15568. return {
  15569. value: undefined,
  15570. done: true
  15571. };
  15572. }
  15573. const requestCapability = (0, _util.createPromiseCapability)();
  15574. this._requests.push(requestCapability);
  15575. return requestCapability.promise;
  15576. }
  15577. cancel(reason) {
  15578. this._done = true;
  15579. for (const requestCapability of this._requests) {
  15580. requestCapability.resolve({
  15581. value: undefined,
  15582. done: true
  15583. });
  15584. }
  15585. this._requests.length = 0;
  15586. if (this._manager.isPendingRequest(this._requestId)) {
  15587. this._manager.abortRequest(this._requestId);
  15588. }
  15589. this._close();
  15590. }
  15591. }
  15592. /***/ }),
  15593. /* 36 */
  15594. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  15595. Object.defineProperty(exports, "__esModule", ({
  15596. value: true
  15597. }));
  15598. exports.PDFFetchStream = void 0;
  15599. var _util = __w_pdfjs_require__(1);
  15600. var _network_utils = __w_pdfjs_require__(33);
  15601. ;
  15602. function createFetchOptions(headers, withCredentials, abortController) {
  15603. return {
  15604. method: "GET",
  15605. headers,
  15606. signal: abortController?.signal,
  15607. mode: "cors",
  15608. credentials: withCredentials ? "include" : "same-origin",
  15609. redirect: "follow"
  15610. };
  15611. }
  15612. function createHeaders(httpHeaders) {
  15613. const headers = new Headers();
  15614. for (const property in httpHeaders) {
  15615. const value = httpHeaders[property];
  15616. if (typeof value === "undefined") {
  15617. continue;
  15618. }
  15619. headers.append(property, value);
  15620. }
  15621. return headers;
  15622. }
  15623. class PDFFetchStream {
  15624. constructor(source) {
  15625. this.source = source;
  15626. this.isHttp = /^https?:/i.test(source.url);
  15627. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  15628. this._fullRequestReader = null;
  15629. this._rangeRequestReaders = [];
  15630. }
  15631. get _progressiveDataLength() {
  15632. return this._fullRequestReader?._loaded ?? 0;
  15633. }
  15634. getFullReader() {
  15635. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  15636. this._fullRequestReader = new PDFFetchStreamReader(this);
  15637. return this._fullRequestReader;
  15638. }
  15639. getRangeReader(begin, end) {
  15640. if (end <= this._progressiveDataLength) {
  15641. return null;
  15642. }
  15643. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  15644. this._rangeRequestReaders.push(reader);
  15645. return reader;
  15646. }
  15647. cancelAllRequests(reason) {
  15648. if (this._fullRequestReader) {
  15649. this._fullRequestReader.cancel(reason);
  15650. }
  15651. for (const reader of this._rangeRequestReaders.slice(0)) {
  15652. reader.cancel(reason);
  15653. }
  15654. }
  15655. }
  15656. exports.PDFFetchStream = PDFFetchStream;
  15657. class PDFFetchStreamReader {
  15658. constructor(stream) {
  15659. this._stream = stream;
  15660. this._reader = null;
  15661. this._loaded = 0;
  15662. this._filename = null;
  15663. const source = stream.source;
  15664. this._withCredentials = source.withCredentials || false;
  15665. this._contentLength = source.length;
  15666. this._headersCapability = (0, _util.createPromiseCapability)();
  15667. this._disableRange = source.disableRange || false;
  15668. this._rangeChunkSize = source.rangeChunkSize;
  15669. if (!this._rangeChunkSize && !this._disableRange) {
  15670. this._disableRange = true;
  15671. }
  15672. if (typeof AbortController !== "undefined") {
  15673. this._abortController = new AbortController();
  15674. }
  15675. this._isStreamingSupported = !source.disableStream;
  15676. this._isRangeSupported = !source.disableRange;
  15677. this._headers = createHeaders(this._stream.httpHeaders);
  15678. const url = source.url;
  15679. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15680. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15681. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15682. }
  15683. this._reader = response.body.getReader();
  15684. this._headersCapability.resolve();
  15685. const getResponseHeader = name => {
  15686. return response.headers.get(name);
  15687. };
  15688. const {
  15689. allowRangeRequests,
  15690. suggestedLength
  15691. } = (0, _network_utils.validateRangeRequestCapabilities)({
  15692. getResponseHeader,
  15693. isHttp: this._stream.isHttp,
  15694. rangeChunkSize: this._rangeChunkSize,
  15695. disableRange: this._disableRange
  15696. });
  15697. this._isRangeSupported = allowRangeRequests;
  15698. this._contentLength = suggestedLength || this._contentLength;
  15699. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  15700. if (!this._isStreamingSupported && this._isRangeSupported) {
  15701. this.cancel(new _util.AbortException("Streaming is disabled."));
  15702. }
  15703. }).catch(this._headersCapability.reject);
  15704. this.onProgress = null;
  15705. }
  15706. get headersReady() {
  15707. return this._headersCapability.promise;
  15708. }
  15709. get filename() {
  15710. return this._filename;
  15711. }
  15712. get contentLength() {
  15713. return this._contentLength;
  15714. }
  15715. get isRangeSupported() {
  15716. return this._isRangeSupported;
  15717. }
  15718. get isStreamingSupported() {
  15719. return this._isStreamingSupported;
  15720. }
  15721. async read() {
  15722. await this._headersCapability.promise;
  15723. const {
  15724. value,
  15725. done
  15726. } = await this._reader.read();
  15727. if (done) {
  15728. return {
  15729. value,
  15730. done
  15731. };
  15732. }
  15733. this._loaded += value.byteLength;
  15734. if (this.onProgress) {
  15735. this.onProgress({
  15736. loaded: this._loaded,
  15737. total: this._contentLength
  15738. });
  15739. }
  15740. const buffer = new Uint8Array(value).buffer;
  15741. return {
  15742. value: buffer,
  15743. done: false
  15744. };
  15745. }
  15746. cancel(reason) {
  15747. if (this._reader) {
  15748. this._reader.cancel(reason);
  15749. }
  15750. if (this._abortController) {
  15751. this._abortController.abort();
  15752. }
  15753. }
  15754. }
  15755. class PDFFetchStreamRangeReader {
  15756. constructor(stream, begin, end) {
  15757. this._stream = stream;
  15758. this._reader = null;
  15759. this._loaded = 0;
  15760. const source = stream.source;
  15761. this._withCredentials = source.withCredentials || false;
  15762. this._readCapability = (0, _util.createPromiseCapability)();
  15763. this._isStreamingSupported = !source.disableStream;
  15764. if (typeof AbortController !== "undefined") {
  15765. this._abortController = new AbortController();
  15766. }
  15767. this._headers = createHeaders(this._stream.httpHeaders);
  15768. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  15769. const url = source.url;
  15770. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15771. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15772. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15773. }
  15774. this._readCapability.resolve();
  15775. this._reader = response.body.getReader();
  15776. }).catch(this._readCapability.reject);
  15777. this.onProgress = null;
  15778. }
  15779. get isStreamingSupported() {
  15780. return this._isStreamingSupported;
  15781. }
  15782. async read() {
  15783. await this._readCapability.promise;
  15784. const {
  15785. value,
  15786. done
  15787. } = await this._reader.read();
  15788. if (done) {
  15789. return {
  15790. value,
  15791. done
  15792. };
  15793. }
  15794. this._loaded += value.byteLength;
  15795. if (this.onProgress) {
  15796. this.onProgress({
  15797. loaded: this._loaded
  15798. });
  15799. }
  15800. const buffer = new Uint8Array(value).buffer;
  15801. return {
  15802. value: buffer,
  15803. done: false
  15804. };
  15805. }
  15806. cancel(reason) {
  15807. if (this._reader) {
  15808. this._reader.cancel(reason);
  15809. }
  15810. if (this._abortController) {
  15811. this._abortController.abort();
  15812. }
  15813. }
  15814. }
  15815. /***/ })
  15816. /******/ ]);
  15817. /************************************************************************/
  15818. /******/ // The module cache
  15819. /******/ var __webpack_module_cache__ = {};
  15820. /******/
  15821. /******/ // The require function
  15822. /******/ function __w_pdfjs_require__(moduleId) {
  15823. /******/ // Check if module is in cache
  15824. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  15825. /******/ if (cachedModule !== undefined) {
  15826. /******/ return cachedModule.exports;
  15827. /******/ }
  15828. /******/ // Create a new module (and put it into the cache)
  15829. /******/ var module = __webpack_module_cache__[moduleId] = {
  15830. /******/ // no module.id needed
  15831. /******/ // no module.loaded needed
  15832. /******/ exports: {}
  15833. /******/ };
  15834. /******/
  15835. /******/ // Execute the module function
  15836. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  15837. /******/
  15838. /******/ // Return the exports of the module
  15839. /******/ return module.exports;
  15840. /******/ }
  15841. /******/
  15842. /************************************************************************/
  15843. var __webpack_exports__ = {};
  15844. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  15845. (() => {
  15846. var exports = __webpack_exports__;
  15847. Object.defineProperty(exports, "__esModule", ({
  15848. value: true
  15849. }));
  15850. Object.defineProperty(exports, "AnnotationEditorLayer", ({
  15851. enumerable: true,
  15852. get: function () {
  15853. return _annotation_editor_layer.AnnotationEditorLayer;
  15854. }
  15855. }));
  15856. Object.defineProperty(exports, "AnnotationEditorParamsType", ({
  15857. enumerable: true,
  15858. get: function () {
  15859. return _util.AnnotationEditorParamsType;
  15860. }
  15861. }));
  15862. Object.defineProperty(exports, "AnnotationEditorType", ({
  15863. enumerable: true,
  15864. get: function () {
  15865. return _util.AnnotationEditorType;
  15866. }
  15867. }));
  15868. Object.defineProperty(exports, "AnnotationEditorUIManager", ({
  15869. enumerable: true,
  15870. get: function () {
  15871. return _tools.AnnotationEditorUIManager;
  15872. }
  15873. }));
  15874. Object.defineProperty(exports, "AnnotationLayer", ({
  15875. enumerable: true,
  15876. get: function () {
  15877. return _annotation_layer.AnnotationLayer;
  15878. }
  15879. }));
  15880. Object.defineProperty(exports, "AnnotationMode", ({
  15881. enumerable: true,
  15882. get: function () {
  15883. return _util.AnnotationMode;
  15884. }
  15885. }));
  15886. Object.defineProperty(exports, "CMapCompressionType", ({
  15887. enumerable: true,
  15888. get: function () {
  15889. return _util.CMapCompressionType;
  15890. }
  15891. }));
  15892. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  15893. enumerable: true,
  15894. get: function () {
  15895. return _worker_options.GlobalWorkerOptions;
  15896. }
  15897. }));
  15898. Object.defineProperty(exports, "InvalidPDFException", ({
  15899. enumerable: true,
  15900. get: function () {
  15901. return _util.InvalidPDFException;
  15902. }
  15903. }));
  15904. Object.defineProperty(exports, "LoopbackPort", ({
  15905. enumerable: true,
  15906. get: function () {
  15907. return _api.LoopbackPort;
  15908. }
  15909. }));
  15910. Object.defineProperty(exports, "MissingPDFException", ({
  15911. enumerable: true,
  15912. get: function () {
  15913. return _util.MissingPDFException;
  15914. }
  15915. }));
  15916. Object.defineProperty(exports, "OPS", ({
  15917. enumerable: true,
  15918. get: function () {
  15919. return _util.OPS;
  15920. }
  15921. }));
  15922. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  15923. enumerable: true,
  15924. get: function () {
  15925. return _api.PDFDataRangeTransport;
  15926. }
  15927. }));
  15928. Object.defineProperty(exports, "PDFDateString", ({
  15929. enumerable: true,
  15930. get: function () {
  15931. return _display_utils.PDFDateString;
  15932. }
  15933. }));
  15934. Object.defineProperty(exports, "PDFWorker", ({
  15935. enumerable: true,
  15936. get: function () {
  15937. return _api.PDFWorker;
  15938. }
  15939. }));
  15940. Object.defineProperty(exports, "PasswordResponses", ({
  15941. enumerable: true,
  15942. get: function () {
  15943. return _util.PasswordResponses;
  15944. }
  15945. }));
  15946. Object.defineProperty(exports, "PermissionFlag", ({
  15947. enumerable: true,
  15948. get: function () {
  15949. return _util.PermissionFlag;
  15950. }
  15951. }));
  15952. Object.defineProperty(exports, "PixelsPerInch", ({
  15953. enumerable: true,
  15954. get: function () {
  15955. return _display_utils.PixelsPerInch;
  15956. }
  15957. }));
  15958. Object.defineProperty(exports, "RenderingCancelledException", ({
  15959. enumerable: true,
  15960. get: function () {
  15961. return _display_utils.RenderingCancelledException;
  15962. }
  15963. }));
  15964. Object.defineProperty(exports, "SVGGraphics", ({
  15965. enumerable: true,
  15966. get: function () {
  15967. return _svg.SVGGraphics;
  15968. }
  15969. }));
  15970. Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  15971. enumerable: true,
  15972. get: function () {
  15973. return _util.UNSUPPORTED_FEATURES;
  15974. }
  15975. }));
  15976. Object.defineProperty(exports, "UnexpectedResponseException", ({
  15977. enumerable: true,
  15978. get: function () {
  15979. return _util.UnexpectedResponseException;
  15980. }
  15981. }));
  15982. Object.defineProperty(exports, "Util", ({
  15983. enumerable: true,
  15984. get: function () {
  15985. return _util.Util;
  15986. }
  15987. }));
  15988. Object.defineProperty(exports, "VerbosityLevel", ({
  15989. enumerable: true,
  15990. get: function () {
  15991. return _util.VerbosityLevel;
  15992. }
  15993. }));
  15994. Object.defineProperty(exports, "XfaLayer", ({
  15995. enumerable: true,
  15996. get: function () {
  15997. return _xfa_layer.XfaLayer;
  15998. }
  15999. }));
  16000. Object.defineProperty(exports, "binarySearchFirstItem", ({
  16001. enumerable: true,
  16002. get: function () {
  16003. return _display_utils.binarySearchFirstItem;
  16004. }
  16005. }));
  16006. Object.defineProperty(exports, "build", ({
  16007. enumerable: true,
  16008. get: function () {
  16009. return _api.build;
  16010. }
  16011. }));
  16012. Object.defineProperty(exports, "createPromiseCapability", ({
  16013. enumerable: true,
  16014. get: function () {
  16015. return _util.createPromiseCapability;
  16016. }
  16017. }));
  16018. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  16019. enumerable: true,
  16020. get: function () {
  16021. return _util.createValidAbsoluteUrl;
  16022. }
  16023. }));
  16024. Object.defineProperty(exports, "getDocument", ({
  16025. enumerable: true,
  16026. get: function () {
  16027. return _api.getDocument;
  16028. }
  16029. }));
  16030. Object.defineProperty(exports, "getFilenameFromUrl", ({
  16031. enumerable: true,
  16032. get: function () {
  16033. return _display_utils.getFilenameFromUrl;
  16034. }
  16035. }));
  16036. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  16037. enumerable: true,
  16038. get: function () {
  16039. return _display_utils.getPdfFilenameFromUrl;
  16040. }
  16041. }));
  16042. Object.defineProperty(exports, "getXfaPageViewport", ({
  16043. enumerable: true,
  16044. get: function () {
  16045. return _display_utils.getXfaPageViewport;
  16046. }
  16047. }));
  16048. Object.defineProperty(exports, "isPdfFile", ({
  16049. enumerable: true,
  16050. get: function () {
  16051. return _display_utils.isPdfFile;
  16052. }
  16053. }));
  16054. Object.defineProperty(exports, "loadScript", ({
  16055. enumerable: true,
  16056. get: function () {
  16057. return _display_utils.loadScript;
  16058. }
  16059. }));
  16060. Object.defineProperty(exports, "renderTextLayer", ({
  16061. enumerable: true,
  16062. get: function () {
  16063. return _text_layer.renderTextLayer;
  16064. }
  16065. }));
  16066. Object.defineProperty(exports, "shadow", ({
  16067. enumerable: true,
  16068. get: function () {
  16069. return _util.shadow;
  16070. }
  16071. }));
  16072. Object.defineProperty(exports, "version", ({
  16073. enumerable: true,
  16074. get: function () {
  16075. return _api.version;
  16076. }
  16077. }));
  16078. var _util = __w_pdfjs_require__(1);
  16079. var _display_utils = __w_pdfjs_require__(4);
  16080. var _api = __w_pdfjs_require__(6);
  16081. var _annotation_editor_layer = __w_pdfjs_require__(22);
  16082. var _tools = __w_pdfjs_require__(9);
  16083. var _annotation_layer = __w_pdfjs_require__(27);
  16084. var _worker_options = __w_pdfjs_require__(15);
  16085. var _is_node = __w_pdfjs_require__(3);
  16086. var _text_layer = __w_pdfjs_require__(30);
  16087. var _svg = __w_pdfjs_require__(31);
  16088. var _xfa_layer = __w_pdfjs_require__(29);
  16089. const pdfjsVersion = '2.15.349';
  16090. const pdfjsBuild = 'b8aa9c622';
  16091. {
  16092. if (_is_node.isNodeJS) {
  16093. const {
  16094. PDFNodeStream
  16095. } = __w_pdfjs_require__(32);
  16096. (0, _api.setPDFNetworkStreamFactory)(params => {
  16097. return new PDFNodeStream(params);
  16098. });
  16099. } else {
  16100. const {
  16101. PDFNetworkStream
  16102. } = __w_pdfjs_require__(35);
  16103. const {
  16104. PDFFetchStream
  16105. } = __w_pdfjs_require__(36);
  16106. (0, _api.setPDFNetworkStreamFactory)(params => {
  16107. if ((0, _display_utils.isValidFetchUrl)(params.url)) {
  16108. return new PDFFetchStream(params);
  16109. }
  16110. return new PDFNetworkStream(params);
  16111. });
  16112. }
  16113. }
  16114. })();
  16115. /******/ return __webpack_exports__;
  16116. /******/ })()
  16117. ;
  16118. });
  16119. //# sourceMappingURL=pdf.js.map