pdf.js 398 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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. })(this, function() {
  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.addLinkAttributes = addLinkAttributes;
  42. exports.deprecated = deprecated;
  43. exports.getFilenameFromUrl = getFilenameFromUrl;
  44. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  45. exports.getXfaPageViewport = getXfaPageViewport;
  46. exports.isDataScheme = isDataScheme;
  47. exports.isPdfFile = isPdfFile;
  48. exports.isValidFetchUrl = isValidFetchUrl;
  49. exports.loadScript = loadScript;
  50. exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PDFDateString = exports.PageViewport = exports.LinkTarget = exports.DOMSVGFactory = exports.DOMStandardFontDataFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = void 0;
  51. var _util = __w_pdfjs_require__(2);
  52. var _base_factory = __w_pdfjs_require__(5);
  53. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  54. const SVG_NS = "http://www.w3.org/2000/svg";
  55. const PixelsPerInch = {
  56. CSS: 96.0,
  57. PDF: 72.0,
  58. get PDF_TO_CSS_UNITS() {
  59. return (0, _util.shadow)(this, "PDF_TO_CSS_UNITS", this.CSS / this.PDF);
  60. }
  61. };
  62. exports.PixelsPerInch = PixelsPerInch;
  63. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  64. constructor({
  65. ownerDocument = globalThis.document
  66. } = {}) {
  67. super();
  68. this._document = ownerDocument;
  69. }
  70. _createCanvas(width, height) {
  71. const canvas = this._document.createElement("canvas");
  72. canvas.width = width;
  73. canvas.height = height;
  74. return canvas;
  75. }
  76. }
  77. exports.DOMCanvasFactory = DOMCanvasFactory;
  78. async function fetchData(url, asTypedArray = false) {
  79. if (isValidFetchUrl(url, document.baseURI)) {
  80. const response = await fetch(url);
  81. if (!response.ok) {
  82. throw new Error(response.statusText);
  83. }
  84. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  85. }
  86. return new Promise((resolve, reject) => {
  87. const request = new XMLHttpRequest();
  88. request.open("GET", url, true);
  89. if (asTypedArray) {
  90. request.responseType = "arraybuffer";
  91. }
  92. request.onreadystatechange = () => {
  93. if (request.readyState !== XMLHttpRequest.DONE) {
  94. return;
  95. }
  96. if (request.status === 200 || request.status === 0) {
  97. let data;
  98. if (asTypedArray && request.response) {
  99. data = new Uint8Array(request.response);
  100. } else if (!asTypedArray && request.responseText) {
  101. data = (0, _util.stringToBytes)(request.responseText);
  102. }
  103. if (data) {
  104. resolve(data);
  105. return;
  106. }
  107. }
  108. reject(new Error(request.statusText));
  109. };
  110. request.send(null);
  111. });
  112. }
  113. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  114. _fetchData(url, compressionType) {
  115. return fetchData(url, this.isCompressed).then(data => {
  116. return {
  117. cMapData: data,
  118. compressionType
  119. };
  120. });
  121. }
  122. }
  123. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  124. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  125. _fetchData(url) {
  126. return fetchData(url, true);
  127. }
  128. }
  129. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  130. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  131. _createSVG(type) {
  132. return document.createElementNS(SVG_NS, type);
  133. }
  134. }
  135. exports.DOMSVGFactory = DOMSVGFactory;
  136. class PageViewport {
  137. constructor({
  138. viewBox,
  139. scale,
  140. rotation,
  141. offsetX = 0,
  142. offsetY = 0,
  143. dontFlip = false
  144. }) {
  145. this.viewBox = viewBox;
  146. this.scale = scale;
  147. this.rotation = rotation;
  148. this.offsetX = offsetX;
  149. this.offsetY = offsetY;
  150. const centerX = (viewBox[2] + viewBox[0]) / 2;
  151. const centerY = (viewBox[3] + viewBox[1]) / 2;
  152. let rotateA, rotateB, rotateC, rotateD;
  153. rotation %= 360;
  154. if (rotation < 0) {
  155. rotation += 360;
  156. }
  157. switch (rotation) {
  158. case 180:
  159. rotateA = -1;
  160. rotateB = 0;
  161. rotateC = 0;
  162. rotateD = 1;
  163. break;
  164. case 90:
  165. rotateA = 0;
  166. rotateB = 1;
  167. rotateC = 1;
  168. rotateD = 0;
  169. break;
  170. case 270:
  171. rotateA = 0;
  172. rotateB = -1;
  173. rotateC = -1;
  174. rotateD = 0;
  175. break;
  176. case 0:
  177. rotateA = 1;
  178. rotateB = 0;
  179. rotateC = 0;
  180. rotateD = -1;
  181. break;
  182. default:
  183. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  184. }
  185. if (dontFlip) {
  186. rotateC = -rotateC;
  187. rotateD = -rotateD;
  188. }
  189. let offsetCanvasX, offsetCanvasY;
  190. let width, height;
  191. if (rotateA === 0) {
  192. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  193. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  194. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  195. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  196. } else {
  197. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  198. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  199. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  200. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  201. }
  202. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  203. this.width = width;
  204. this.height = height;
  205. }
  206. clone({
  207. scale = this.scale,
  208. rotation = this.rotation,
  209. offsetX = this.offsetX,
  210. offsetY = this.offsetY,
  211. dontFlip = false
  212. } = {}) {
  213. return new PageViewport({
  214. viewBox: this.viewBox.slice(),
  215. scale,
  216. rotation,
  217. offsetX,
  218. offsetY,
  219. dontFlip
  220. });
  221. }
  222. convertToViewportPoint(x, y) {
  223. return _util.Util.applyTransform([x, y], this.transform);
  224. }
  225. convertToViewportRectangle(rect) {
  226. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  227. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  228. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  229. }
  230. convertToPdfPoint(x, y) {
  231. return _util.Util.applyInverseTransform([x, y], this.transform);
  232. }
  233. }
  234. exports.PageViewport = PageViewport;
  235. class RenderingCancelledException extends _util.BaseException {
  236. constructor(msg, type) {
  237. super(msg, "RenderingCancelledException");
  238. this.type = type;
  239. }
  240. }
  241. exports.RenderingCancelledException = RenderingCancelledException;
  242. const LinkTarget = {
  243. NONE: 0,
  244. SELF: 1,
  245. BLANK: 2,
  246. PARENT: 3,
  247. TOP: 4
  248. };
  249. exports.LinkTarget = LinkTarget;
  250. function addLinkAttributes(link, {
  251. url,
  252. target,
  253. rel,
  254. enabled = true
  255. } = {}) {
  256. (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
  257. const urlNullRemoved = (0, _util.removeNullCharacters)(url);
  258. if (enabled) {
  259. link.href = link.title = urlNullRemoved;
  260. } else {
  261. link.href = "";
  262. link.title = `Disabled: ${urlNullRemoved}`;
  263. link.onclick = () => {
  264. return false;
  265. };
  266. }
  267. let targetStr = "";
  268. switch (target) {
  269. case LinkTarget.NONE:
  270. break;
  271. case LinkTarget.SELF:
  272. targetStr = "_self";
  273. break;
  274. case LinkTarget.BLANK:
  275. targetStr = "_blank";
  276. break;
  277. case LinkTarget.PARENT:
  278. targetStr = "_parent";
  279. break;
  280. case LinkTarget.TOP:
  281. targetStr = "_top";
  282. break;
  283. }
  284. link.target = targetStr;
  285. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  286. }
  287. function isDataScheme(url) {
  288. const ii = url.length;
  289. let i = 0;
  290. while (i < ii && url[i].trim() === "") {
  291. i++;
  292. }
  293. return url.substring(i, i + 5).toLowerCase() === "data:";
  294. }
  295. function isPdfFile(filename) {
  296. return typeof filename === "string" && /\.pdf$/i.test(filename);
  297. }
  298. function getFilenameFromUrl(url) {
  299. const anchor = url.indexOf("#");
  300. const query = url.indexOf("?");
  301. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  302. return url.substring(url.lastIndexOf("/", end) + 1, end);
  303. }
  304. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  305. if (typeof url !== "string") {
  306. return defaultFilename;
  307. }
  308. if (isDataScheme(url)) {
  309. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  310. return defaultFilename;
  311. }
  312. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  313. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  314. const splitURI = reURI.exec(url);
  315. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  316. if (suggestedFilename) {
  317. suggestedFilename = suggestedFilename[0];
  318. if (suggestedFilename.includes("%")) {
  319. try {
  320. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  321. } catch (ex) {}
  322. }
  323. }
  324. return suggestedFilename || defaultFilename;
  325. }
  326. class StatTimer {
  327. constructor() {
  328. this.started = Object.create(null);
  329. this.times = [];
  330. }
  331. time(name) {
  332. if (name in this.started) {
  333. (0, _util.warn)(`Timer is already running for ${name}`);
  334. }
  335. this.started[name] = Date.now();
  336. }
  337. timeEnd(name) {
  338. if (!(name in this.started)) {
  339. (0, _util.warn)(`Timer has not been started for ${name}`);
  340. }
  341. this.times.push({
  342. name,
  343. start: this.started[name],
  344. end: Date.now()
  345. });
  346. delete this.started[name];
  347. }
  348. toString() {
  349. const outBuf = [];
  350. let longest = 0;
  351. for (const time of this.times) {
  352. const name = time.name;
  353. if (name.length > longest) {
  354. longest = name.length;
  355. }
  356. }
  357. for (const time of this.times) {
  358. const duration = time.end - time.start;
  359. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  360. }
  361. return outBuf.join("");
  362. }
  363. }
  364. exports.StatTimer = StatTimer;
  365. function isValidFetchUrl(url, baseUrl) {
  366. try {
  367. const {
  368. protocol
  369. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  370. return protocol === "http:" || protocol === "https:";
  371. } catch (ex) {
  372. return false;
  373. }
  374. }
  375. function loadScript(src, removeScriptElement = false) {
  376. return new Promise((resolve, reject) => {
  377. const script = document.createElement("script");
  378. script.src = src;
  379. script.onload = function (evt) {
  380. if (removeScriptElement) {
  381. script.remove();
  382. }
  383. resolve(evt);
  384. };
  385. script.onerror = function () {
  386. reject(new Error(`Cannot load script at: ${script.src}`));
  387. };
  388. (document.head || document.documentElement).appendChild(script);
  389. });
  390. }
  391. function deprecated(details) {
  392. console.log("Deprecated API usage: " + details);
  393. }
  394. let pdfDateStringRegex;
  395. class PDFDateString {
  396. static toDateObject(input) {
  397. if (!input || !(0, _util.isString)(input)) {
  398. return null;
  399. }
  400. if (!pdfDateStringRegex) {
  401. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  402. }
  403. const matches = pdfDateStringRegex.exec(input);
  404. if (!matches) {
  405. return null;
  406. }
  407. const year = parseInt(matches[1], 10);
  408. let month = parseInt(matches[2], 10);
  409. month = month >= 1 && month <= 12 ? month - 1 : 0;
  410. let day = parseInt(matches[3], 10);
  411. day = day >= 1 && day <= 31 ? day : 1;
  412. let hour = parseInt(matches[4], 10);
  413. hour = hour >= 0 && hour <= 23 ? hour : 0;
  414. let minute = parseInt(matches[5], 10);
  415. minute = minute >= 0 && minute <= 59 ? minute : 0;
  416. let second = parseInt(matches[6], 10);
  417. second = second >= 0 && second <= 59 ? second : 0;
  418. const universalTimeRelation = matches[7] || "Z";
  419. let offsetHour = parseInt(matches[8], 10);
  420. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  421. let offsetMinute = parseInt(matches[9], 10) || 0;
  422. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  423. if (universalTimeRelation === "-") {
  424. hour += offsetHour;
  425. minute += offsetMinute;
  426. } else if (universalTimeRelation === "+") {
  427. hour -= offsetHour;
  428. minute -= offsetMinute;
  429. }
  430. return new Date(Date.UTC(year, month, day, hour, minute, second));
  431. }
  432. }
  433. exports.PDFDateString = PDFDateString;
  434. function getXfaPageViewport(xfaPage, {
  435. scale = 1,
  436. rotation = 0
  437. }) {
  438. const {
  439. width,
  440. height
  441. } = xfaPage.attributes.style;
  442. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  443. return new PageViewport({
  444. viewBox,
  445. scale,
  446. rotation
  447. });
  448. }
  449. /***/ }),
  450. /* 2 */
  451. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  452. Object.defineProperty(exports, "__esModule", ({
  453. value: true
  454. }));
  455. exports.arrayByteLength = arrayByteLength;
  456. exports.arraysToBytes = arraysToBytes;
  457. exports.assert = assert;
  458. exports.bytesToString = bytesToString;
  459. exports.createObjectURL = createObjectURL;
  460. exports.createPromiseCapability = createPromiseCapability;
  461. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  462. exports.escapeString = escapeString;
  463. exports.getModificationDate = getModificationDate;
  464. exports.getVerbosityLevel = getVerbosityLevel;
  465. exports.info = info;
  466. exports.isArrayBuffer = isArrayBuffer;
  467. exports.isArrayEqual = isArrayEqual;
  468. exports.isAscii = isAscii;
  469. exports.isBool = isBool;
  470. exports.isNum = isNum;
  471. exports.isSameOrigin = isSameOrigin;
  472. exports.isString = isString;
  473. exports.objectFromMap = objectFromMap;
  474. exports.objectSize = objectSize;
  475. exports.removeNullCharacters = removeNullCharacters;
  476. exports.setVerbosityLevel = setVerbosityLevel;
  477. exports.shadow = shadow;
  478. exports.string32 = string32;
  479. exports.stringToBytes = stringToBytes;
  480. exports.stringToPDFString = stringToPDFString;
  481. exports.stringToUTF16BEString = stringToUTF16BEString;
  482. exports.stringToUTF8String = stringToUTF8String;
  483. exports.unreachable = unreachable;
  484. exports.utf8StringToString = utf8StringToString;
  485. exports.warn = warn;
  486. exports.VerbosityLevel = exports.Util = exports.UNSUPPORTED_FEATURES = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.IsLittleEndianCached = exports.IsEvalSupportedCached = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = 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.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
  487. __w_pdfjs_require__(3);
  488. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  489. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  490. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  491. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  492. const RenderingIntentFlag = {
  493. ANY: 0x01,
  494. DISPLAY: 0x02,
  495. PRINT: 0x04,
  496. ANNOTATIONS_FORMS: 0x10,
  497. ANNOTATIONS_STORAGE: 0x20,
  498. ANNOTATIONS_DISABLE: 0x40,
  499. OPLIST: 0x100
  500. };
  501. exports.RenderingIntentFlag = RenderingIntentFlag;
  502. const AnnotationMode = {
  503. DISABLE: 0,
  504. ENABLE: 1,
  505. ENABLE_FORMS: 2,
  506. ENABLE_STORAGE: 3
  507. };
  508. exports.AnnotationMode = AnnotationMode;
  509. const PermissionFlag = {
  510. PRINT: 0x04,
  511. MODIFY_CONTENTS: 0x08,
  512. COPY: 0x10,
  513. MODIFY_ANNOTATIONS: 0x20,
  514. FILL_INTERACTIVE_FORMS: 0x100,
  515. COPY_FOR_ACCESSIBILITY: 0x200,
  516. ASSEMBLE: 0x400,
  517. PRINT_HIGH_QUALITY: 0x800
  518. };
  519. exports.PermissionFlag = PermissionFlag;
  520. const TextRenderingMode = {
  521. FILL: 0,
  522. STROKE: 1,
  523. FILL_STROKE: 2,
  524. INVISIBLE: 3,
  525. FILL_ADD_TO_PATH: 4,
  526. STROKE_ADD_TO_PATH: 5,
  527. FILL_STROKE_ADD_TO_PATH: 6,
  528. ADD_TO_PATH: 7,
  529. FILL_STROKE_MASK: 3,
  530. ADD_TO_PATH_FLAG: 4
  531. };
  532. exports.TextRenderingMode = TextRenderingMode;
  533. const ImageKind = {
  534. GRAYSCALE_1BPP: 1,
  535. RGB_24BPP: 2,
  536. RGBA_32BPP: 3
  537. };
  538. exports.ImageKind = ImageKind;
  539. const AnnotationType = {
  540. TEXT: 1,
  541. LINK: 2,
  542. FREETEXT: 3,
  543. LINE: 4,
  544. SQUARE: 5,
  545. CIRCLE: 6,
  546. POLYGON: 7,
  547. POLYLINE: 8,
  548. HIGHLIGHT: 9,
  549. UNDERLINE: 10,
  550. SQUIGGLY: 11,
  551. STRIKEOUT: 12,
  552. STAMP: 13,
  553. CARET: 14,
  554. INK: 15,
  555. POPUP: 16,
  556. FILEATTACHMENT: 17,
  557. SOUND: 18,
  558. MOVIE: 19,
  559. WIDGET: 20,
  560. SCREEN: 21,
  561. PRINTERMARK: 22,
  562. TRAPNET: 23,
  563. WATERMARK: 24,
  564. THREED: 25,
  565. REDACT: 26
  566. };
  567. exports.AnnotationType = AnnotationType;
  568. const AnnotationStateModelType = {
  569. MARKED: "Marked",
  570. REVIEW: "Review"
  571. };
  572. exports.AnnotationStateModelType = AnnotationStateModelType;
  573. const AnnotationMarkedState = {
  574. MARKED: "Marked",
  575. UNMARKED: "Unmarked"
  576. };
  577. exports.AnnotationMarkedState = AnnotationMarkedState;
  578. const AnnotationReviewState = {
  579. ACCEPTED: "Accepted",
  580. REJECTED: "Rejected",
  581. CANCELLED: "Cancelled",
  582. COMPLETED: "Completed",
  583. NONE: "None"
  584. };
  585. exports.AnnotationReviewState = AnnotationReviewState;
  586. const AnnotationReplyType = {
  587. GROUP: "Group",
  588. REPLY: "R"
  589. };
  590. exports.AnnotationReplyType = AnnotationReplyType;
  591. const AnnotationFlag = {
  592. INVISIBLE: 0x01,
  593. HIDDEN: 0x02,
  594. PRINT: 0x04,
  595. NOZOOM: 0x08,
  596. NOROTATE: 0x10,
  597. NOVIEW: 0x20,
  598. READONLY: 0x40,
  599. LOCKED: 0x80,
  600. TOGGLENOVIEW: 0x100,
  601. LOCKEDCONTENTS: 0x200
  602. };
  603. exports.AnnotationFlag = AnnotationFlag;
  604. const AnnotationFieldFlag = {
  605. READONLY: 0x0000001,
  606. REQUIRED: 0x0000002,
  607. NOEXPORT: 0x0000004,
  608. MULTILINE: 0x0001000,
  609. PASSWORD: 0x0002000,
  610. NOTOGGLETOOFF: 0x0004000,
  611. RADIO: 0x0008000,
  612. PUSHBUTTON: 0x0010000,
  613. COMBO: 0x0020000,
  614. EDIT: 0x0040000,
  615. SORT: 0x0080000,
  616. FILESELECT: 0x0100000,
  617. MULTISELECT: 0x0200000,
  618. DONOTSPELLCHECK: 0x0400000,
  619. DONOTSCROLL: 0x0800000,
  620. COMB: 0x1000000,
  621. RICHTEXT: 0x2000000,
  622. RADIOSINUNISON: 0x2000000,
  623. COMMITONSELCHANGE: 0x4000000
  624. };
  625. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  626. const AnnotationBorderStyleType = {
  627. SOLID: 1,
  628. DASHED: 2,
  629. BEVELED: 3,
  630. INSET: 4,
  631. UNDERLINE: 5
  632. };
  633. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  634. const AnnotationActionEventType = {
  635. E: "Mouse Enter",
  636. X: "Mouse Exit",
  637. D: "Mouse Down",
  638. U: "Mouse Up",
  639. Fo: "Focus",
  640. Bl: "Blur",
  641. PO: "PageOpen",
  642. PC: "PageClose",
  643. PV: "PageVisible",
  644. PI: "PageInvisible",
  645. K: "Keystroke",
  646. F: "Format",
  647. V: "Validate",
  648. C: "Calculate"
  649. };
  650. exports.AnnotationActionEventType = AnnotationActionEventType;
  651. const DocumentActionEventType = {
  652. WC: "WillClose",
  653. WS: "WillSave",
  654. DS: "DidSave",
  655. WP: "WillPrint",
  656. DP: "DidPrint"
  657. };
  658. exports.DocumentActionEventType = DocumentActionEventType;
  659. const PageActionEventType = {
  660. O: "PageOpen",
  661. C: "PageClose"
  662. };
  663. exports.PageActionEventType = PageActionEventType;
  664. const StreamType = {
  665. UNKNOWN: "UNKNOWN",
  666. FLATE: "FLATE",
  667. LZW: "LZW",
  668. DCT: "DCT",
  669. JPX: "JPX",
  670. JBIG: "JBIG",
  671. A85: "A85",
  672. AHX: "AHX",
  673. CCF: "CCF",
  674. RLX: "RLX"
  675. };
  676. exports.StreamType = StreamType;
  677. const FontType = {
  678. UNKNOWN: "UNKNOWN",
  679. TYPE1: "TYPE1",
  680. TYPE1STANDARD: "TYPE1STANDARD",
  681. TYPE1C: "TYPE1C",
  682. CIDFONTTYPE0: "CIDFONTTYPE0",
  683. CIDFONTTYPE0C: "CIDFONTTYPE0C",
  684. TRUETYPE: "TRUETYPE",
  685. CIDFONTTYPE2: "CIDFONTTYPE2",
  686. TYPE3: "TYPE3",
  687. OPENTYPE: "OPENTYPE",
  688. TYPE0: "TYPE0",
  689. MMTYPE1: "MMTYPE1"
  690. };
  691. exports.FontType = FontType;
  692. const VerbosityLevel = {
  693. ERRORS: 0,
  694. WARNINGS: 1,
  695. INFOS: 5
  696. };
  697. exports.VerbosityLevel = VerbosityLevel;
  698. const CMapCompressionType = {
  699. NONE: 0,
  700. BINARY: 1,
  701. STREAM: 2
  702. };
  703. exports.CMapCompressionType = CMapCompressionType;
  704. const OPS = {
  705. dependency: 1,
  706. setLineWidth: 2,
  707. setLineCap: 3,
  708. setLineJoin: 4,
  709. setMiterLimit: 5,
  710. setDash: 6,
  711. setRenderingIntent: 7,
  712. setFlatness: 8,
  713. setGState: 9,
  714. save: 10,
  715. restore: 11,
  716. transform: 12,
  717. moveTo: 13,
  718. lineTo: 14,
  719. curveTo: 15,
  720. curveTo2: 16,
  721. curveTo3: 17,
  722. closePath: 18,
  723. rectangle: 19,
  724. stroke: 20,
  725. closeStroke: 21,
  726. fill: 22,
  727. eoFill: 23,
  728. fillStroke: 24,
  729. eoFillStroke: 25,
  730. closeFillStroke: 26,
  731. closeEOFillStroke: 27,
  732. endPath: 28,
  733. clip: 29,
  734. eoClip: 30,
  735. beginText: 31,
  736. endText: 32,
  737. setCharSpacing: 33,
  738. setWordSpacing: 34,
  739. setHScale: 35,
  740. setLeading: 36,
  741. setFont: 37,
  742. setTextRenderingMode: 38,
  743. setTextRise: 39,
  744. moveText: 40,
  745. setLeadingMoveText: 41,
  746. setTextMatrix: 42,
  747. nextLine: 43,
  748. showText: 44,
  749. showSpacedText: 45,
  750. nextLineShowText: 46,
  751. nextLineSetSpacingShowText: 47,
  752. setCharWidth: 48,
  753. setCharWidthAndBounds: 49,
  754. setStrokeColorSpace: 50,
  755. setFillColorSpace: 51,
  756. setStrokeColor: 52,
  757. setStrokeColorN: 53,
  758. setFillColor: 54,
  759. setFillColorN: 55,
  760. setStrokeGray: 56,
  761. setFillGray: 57,
  762. setStrokeRGBColor: 58,
  763. setFillRGBColor: 59,
  764. setStrokeCMYKColor: 60,
  765. setFillCMYKColor: 61,
  766. shadingFill: 62,
  767. beginInlineImage: 63,
  768. beginImageData: 64,
  769. endInlineImage: 65,
  770. paintXObject: 66,
  771. markPoint: 67,
  772. markPointProps: 68,
  773. beginMarkedContent: 69,
  774. beginMarkedContentProps: 70,
  775. endMarkedContent: 71,
  776. beginCompat: 72,
  777. endCompat: 73,
  778. paintFormXObjectBegin: 74,
  779. paintFormXObjectEnd: 75,
  780. beginGroup: 76,
  781. endGroup: 77,
  782. beginAnnotations: 78,
  783. endAnnotations: 79,
  784. beginAnnotation: 80,
  785. endAnnotation: 81,
  786. paintJpegXObject: 82,
  787. paintImageMaskXObject: 83,
  788. paintImageMaskXObjectGroup: 84,
  789. paintImageXObject: 85,
  790. paintInlineImageXObject: 86,
  791. paintInlineImageXObjectGroup: 87,
  792. paintImageXObjectRepeat: 88,
  793. paintImageMaskXObjectRepeat: 89,
  794. paintSolidColorImageMask: 90,
  795. constructPath: 91
  796. };
  797. exports.OPS = OPS;
  798. const UNSUPPORTED_FEATURES = {
  799. unknown: "unknown",
  800. forms: "forms",
  801. javaScript: "javaScript",
  802. signatures: "signatures",
  803. smask: "smask",
  804. shadingPattern: "shadingPattern",
  805. font: "font",
  806. errorTilingPattern: "errorTilingPattern",
  807. errorExtGState: "errorExtGState",
  808. errorXObject: "errorXObject",
  809. errorFontLoadType3: "errorFontLoadType3",
  810. errorFontState: "errorFontState",
  811. errorFontMissing: "errorFontMissing",
  812. errorFontTranslate: "errorFontTranslate",
  813. errorColorSpace: "errorColorSpace",
  814. errorOperatorList: "errorOperatorList",
  815. errorFontToUnicode: "errorFontToUnicode",
  816. errorFontLoadNative: "errorFontLoadNative",
  817. errorFontBuildPath: "errorFontBuildPath",
  818. errorFontGetPath: "errorFontGetPath",
  819. errorMarkedContent: "errorMarkedContent",
  820. errorContentSubStream: "errorContentSubStream"
  821. };
  822. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  823. const PasswordResponses = {
  824. NEED_PASSWORD: 1,
  825. INCORRECT_PASSWORD: 2
  826. };
  827. exports.PasswordResponses = PasswordResponses;
  828. let verbosity = VerbosityLevel.WARNINGS;
  829. function setVerbosityLevel(level) {
  830. if (Number.isInteger(level)) {
  831. verbosity = level;
  832. }
  833. }
  834. function getVerbosityLevel() {
  835. return verbosity;
  836. }
  837. function info(msg) {
  838. if (verbosity >= VerbosityLevel.INFOS) {
  839. console.log(`Info: ${msg}`);
  840. }
  841. }
  842. function warn(msg) {
  843. if (verbosity >= VerbosityLevel.WARNINGS) {
  844. console.log(`Warning: ${msg}`);
  845. }
  846. }
  847. function unreachable(msg) {
  848. throw new Error(msg);
  849. }
  850. function assert(cond, msg) {
  851. if (!cond) {
  852. unreachable(msg);
  853. }
  854. }
  855. function isSameOrigin(baseUrl, otherUrl) {
  856. let base;
  857. try {
  858. base = new URL(baseUrl);
  859. if (!base.origin || base.origin === "null") {
  860. return false;
  861. }
  862. } catch (e) {
  863. return false;
  864. }
  865. const other = new URL(otherUrl, base);
  866. return base.origin === other.origin;
  867. }
  868. function _isValidProtocol(url) {
  869. if (!url) {
  870. return false;
  871. }
  872. switch (url.protocol) {
  873. case "http:":
  874. case "https:":
  875. case "ftp:":
  876. case "mailto:":
  877. case "tel:":
  878. return true;
  879. default:
  880. return false;
  881. }
  882. }
  883. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  884. if (!url) {
  885. return null;
  886. }
  887. try {
  888. if (options && typeof url === "string") {
  889. if (options.addDefaultProtocol && url.startsWith("www.")) {
  890. const dots = url.match(/\./g);
  891. if (dots && dots.length >= 2) {
  892. url = `http://${url}`;
  893. }
  894. }
  895. if (options.tryConvertEncoding) {
  896. try {
  897. url = stringToUTF8String(url);
  898. } catch (ex) {}
  899. }
  900. }
  901. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  902. if (_isValidProtocol(absoluteUrl)) {
  903. return absoluteUrl;
  904. }
  905. } catch (ex) {}
  906. return null;
  907. }
  908. function shadow(obj, prop, value) {
  909. Object.defineProperty(obj, prop, {
  910. value,
  911. enumerable: true,
  912. configurable: true,
  913. writable: false
  914. });
  915. return value;
  916. }
  917. const BaseException = function BaseExceptionClosure() {
  918. function BaseException(message, name) {
  919. if (this.constructor === BaseException) {
  920. unreachable("Cannot initialize BaseException.");
  921. }
  922. this.message = message;
  923. this.name = name;
  924. }
  925. BaseException.prototype = new Error();
  926. BaseException.constructor = BaseException;
  927. return BaseException;
  928. }();
  929. exports.BaseException = BaseException;
  930. class PasswordException extends BaseException {
  931. constructor(msg, code) {
  932. super(msg, "PasswordException");
  933. this.code = code;
  934. }
  935. }
  936. exports.PasswordException = PasswordException;
  937. class UnknownErrorException extends BaseException {
  938. constructor(msg, details) {
  939. super(msg, "UnknownErrorException");
  940. this.details = details;
  941. }
  942. }
  943. exports.UnknownErrorException = UnknownErrorException;
  944. class InvalidPDFException extends BaseException {
  945. constructor(msg) {
  946. super(msg, "InvalidPDFException");
  947. }
  948. }
  949. exports.InvalidPDFException = InvalidPDFException;
  950. class MissingPDFException extends BaseException {
  951. constructor(msg) {
  952. super(msg, "MissingPDFException");
  953. }
  954. }
  955. exports.MissingPDFException = MissingPDFException;
  956. class UnexpectedResponseException extends BaseException {
  957. constructor(msg, status) {
  958. super(msg, "UnexpectedResponseException");
  959. this.status = status;
  960. }
  961. }
  962. exports.UnexpectedResponseException = UnexpectedResponseException;
  963. class FormatError extends BaseException {
  964. constructor(msg) {
  965. super(msg, "FormatError");
  966. }
  967. }
  968. exports.FormatError = FormatError;
  969. class AbortException extends BaseException {
  970. constructor(msg) {
  971. super(msg, "AbortException");
  972. }
  973. }
  974. exports.AbortException = AbortException;
  975. const NullCharactersRegExp = /\x00/g;
  976. function removeNullCharacters(str) {
  977. if (typeof str !== "string") {
  978. warn("The argument for removeNullCharacters must be a string.");
  979. return str;
  980. }
  981. return str.replace(NullCharactersRegExp, "");
  982. }
  983. function bytesToString(bytes) {
  984. assert(bytes !== null && typeof bytes === "object" && bytes.length !== undefined, "Invalid argument for bytesToString");
  985. const length = bytes.length;
  986. const MAX_ARGUMENT_COUNT = 8192;
  987. if (length < MAX_ARGUMENT_COUNT) {
  988. return String.fromCharCode.apply(null, bytes);
  989. }
  990. const strBuf = [];
  991. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  992. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  993. const chunk = bytes.subarray(i, chunkEnd);
  994. strBuf.push(String.fromCharCode.apply(null, chunk));
  995. }
  996. return strBuf.join("");
  997. }
  998. function stringToBytes(str) {
  999. assert(typeof str === "string", "Invalid argument for stringToBytes");
  1000. const length = str.length;
  1001. const bytes = new Uint8Array(length);
  1002. for (let i = 0; i < length; ++i) {
  1003. bytes[i] = str.charCodeAt(i) & 0xff;
  1004. }
  1005. return bytes;
  1006. }
  1007. function arrayByteLength(arr) {
  1008. if (arr.length !== undefined) {
  1009. return arr.length;
  1010. }
  1011. assert(arr.byteLength !== undefined, "arrayByteLength - invalid argument.");
  1012. return arr.byteLength;
  1013. }
  1014. function arraysToBytes(arr) {
  1015. const length = arr.length;
  1016. if (length === 1 && arr[0] instanceof Uint8Array) {
  1017. return arr[0];
  1018. }
  1019. let resultLength = 0;
  1020. for (let i = 0; i < length; i++) {
  1021. resultLength += arrayByteLength(arr[i]);
  1022. }
  1023. let pos = 0;
  1024. const data = new Uint8Array(resultLength);
  1025. for (let i = 0; i < length; i++) {
  1026. let item = arr[i];
  1027. if (!(item instanceof Uint8Array)) {
  1028. if (typeof item === "string") {
  1029. item = stringToBytes(item);
  1030. } else {
  1031. item = new Uint8Array(item);
  1032. }
  1033. }
  1034. const itemLength = item.byteLength;
  1035. data.set(item, pos);
  1036. pos += itemLength;
  1037. }
  1038. return data;
  1039. }
  1040. function string32(value) {
  1041. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  1042. }
  1043. function objectSize(obj) {
  1044. return Object.keys(obj).length;
  1045. }
  1046. function objectFromMap(map) {
  1047. const obj = Object.create(null);
  1048. for (const [key, value] of map) {
  1049. obj[key] = value;
  1050. }
  1051. return obj;
  1052. }
  1053. function isLittleEndian() {
  1054. const buffer8 = new Uint8Array(4);
  1055. buffer8[0] = 1;
  1056. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  1057. return view32[0] === 1;
  1058. }
  1059. const IsLittleEndianCached = {
  1060. get value() {
  1061. return shadow(this, "value", isLittleEndian());
  1062. }
  1063. };
  1064. exports.IsLittleEndianCached = IsLittleEndianCached;
  1065. function isEvalSupported() {
  1066. try {
  1067. new Function("");
  1068. return true;
  1069. } catch (e) {
  1070. return false;
  1071. }
  1072. }
  1073. const IsEvalSupportedCached = {
  1074. get value() {
  1075. return shadow(this, "value", isEvalSupported());
  1076. }
  1077. };
  1078. exports.IsEvalSupportedCached = IsEvalSupportedCached;
  1079. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  1080. class Util {
  1081. static makeHexColor(r, g, b) {
  1082. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  1083. }
  1084. static transform(m1, m2) {
  1085. 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]];
  1086. }
  1087. static applyTransform(p, m) {
  1088. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  1089. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  1090. return [xt, yt];
  1091. }
  1092. static applyInverseTransform(p, m) {
  1093. const d = m[0] * m[3] - m[1] * m[2];
  1094. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  1095. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  1096. return [xt, yt];
  1097. }
  1098. static getAxialAlignedBoundingBox(r, m) {
  1099. const p1 = Util.applyTransform(r, m);
  1100. const p2 = Util.applyTransform(r.slice(2, 4), m);
  1101. const p3 = Util.applyTransform([r[0], r[3]], m);
  1102. const p4 = Util.applyTransform([r[2], r[1]], m);
  1103. 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])];
  1104. }
  1105. static inverseTransform(m) {
  1106. const d = m[0] * m[3] - m[1] * m[2];
  1107. 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];
  1108. }
  1109. static apply3dTransform(m, v) {
  1110. 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]];
  1111. }
  1112. static singularValueDecompose2dScale(m) {
  1113. const transpose = [m[0], m[2], m[1], m[3]];
  1114. const a = m[0] * transpose[0] + m[1] * transpose[2];
  1115. const b = m[0] * transpose[1] + m[1] * transpose[3];
  1116. const c = m[2] * transpose[0] + m[3] * transpose[2];
  1117. const d = m[2] * transpose[1] + m[3] * transpose[3];
  1118. const first = (a + d) / 2;
  1119. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  1120. const sx = first + second || 1;
  1121. const sy = first - second || 1;
  1122. return [Math.sqrt(sx), Math.sqrt(sy)];
  1123. }
  1124. static normalizeRect(rect) {
  1125. const r = rect.slice(0);
  1126. if (rect[0] > rect[2]) {
  1127. r[0] = rect[2];
  1128. r[2] = rect[0];
  1129. }
  1130. if (rect[1] > rect[3]) {
  1131. r[1] = rect[3];
  1132. r[3] = rect[1];
  1133. }
  1134. return r;
  1135. }
  1136. static intersect(rect1, rect2) {
  1137. function compare(a, b) {
  1138. return a - b;
  1139. }
  1140. const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
  1141. const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare);
  1142. const result = [];
  1143. rect1 = Util.normalizeRect(rect1);
  1144. rect2 = Util.normalizeRect(rect2);
  1145. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  1146. result[0] = orderedX[1];
  1147. result[2] = orderedX[2];
  1148. } else {
  1149. return null;
  1150. }
  1151. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  1152. result[1] = orderedY[1];
  1153. result[3] = orderedY[2];
  1154. } else {
  1155. return null;
  1156. }
  1157. return result;
  1158. }
  1159. }
  1160. exports.Util = Util;
  1161. 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];
  1162. function stringToPDFString(str) {
  1163. const length = str.length,
  1164. strBuf = [];
  1165. if (str[0] === "\xFE" && str[1] === "\xFF") {
  1166. for (let i = 2; i < length; i += 2) {
  1167. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1168. }
  1169. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  1170. for (let i = 2; i < length; i += 2) {
  1171. strBuf.push(String.fromCharCode(str.charCodeAt(i + 1) << 8 | str.charCodeAt(i)));
  1172. }
  1173. } else {
  1174. for (let i = 0; i < length; ++i) {
  1175. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  1176. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1177. }
  1178. }
  1179. return strBuf.join("");
  1180. }
  1181. function escapeString(str) {
  1182. return str.replace(/([()\\\n\r])/g, match => {
  1183. if (match === "\n") {
  1184. return "\\n";
  1185. } else if (match === "\r") {
  1186. return "\\r";
  1187. }
  1188. return `\\${match}`;
  1189. });
  1190. }
  1191. function isAscii(str) {
  1192. return /^[\x00-\x7F]*$/.test(str);
  1193. }
  1194. function stringToUTF16BEString(str) {
  1195. const buf = ["\xFE\xFF"];
  1196. for (let i = 0, ii = str.length; i < ii; i++) {
  1197. const char = str.charCodeAt(i);
  1198. buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
  1199. }
  1200. return buf.join("");
  1201. }
  1202. function stringToUTF8String(str) {
  1203. return decodeURIComponent(escape(str));
  1204. }
  1205. function utf8StringToString(str) {
  1206. return unescape(encodeURIComponent(str));
  1207. }
  1208. function isBool(v) {
  1209. return typeof v === "boolean";
  1210. }
  1211. function isNum(v) {
  1212. return typeof v === "number";
  1213. }
  1214. function isString(v) {
  1215. return typeof v === "string";
  1216. }
  1217. function isArrayBuffer(v) {
  1218. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  1219. }
  1220. function isArrayEqual(arr1, arr2) {
  1221. if (arr1.length !== arr2.length) {
  1222. return false;
  1223. }
  1224. for (let i = 0, ii = arr1.length; i < ii; i++) {
  1225. if (arr1[i] !== arr2[i]) {
  1226. return false;
  1227. }
  1228. }
  1229. return true;
  1230. }
  1231. function getModificationDate(date = new Date()) {
  1232. 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")];
  1233. return buffer.join("");
  1234. }
  1235. function createPromiseCapability() {
  1236. const capability = Object.create(null);
  1237. let isSettled = false;
  1238. Object.defineProperty(capability, "settled", {
  1239. get() {
  1240. return isSettled;
  1241. }
  1242. });
  1243. capability.promise = new Promise(function (resolve, reject) {
  1244. capability.resolve = function (data) {
  1245. isSettled = true;
  1246. resolve(data);
  1247. };
  1248. capability.reject = function (reason) {
  1249. isSettled = true;
  1250. reject(reason);
  1251. };
  1252. });
  1253. return capability;
  1254. }
  1255. function createObjectURL(data, contentType = "", forceDataSchema = false) {
  1256. if (URL.createObjectURL && !forceDataSchema) {
  1257. return URL.createObjectURL(new Blob([data], {
  1258. type: contentType
  1259. }));
  1260. }
  1261. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1262. let buffer = `data:${contentType};base64,`;
  1263. for (let i = 0, ii = data.length; i < ii; i += 3) {
  1264. const b1 = data[i] & 0xff;
  1265. const b2 = data[i + 1] & 0xff;
  1266. const b3 = data[i + 2] & 0xff;
  1267. const d1 = b1 >> 2,
  1268. d2 = (b1 & 3) << 4 | b2 >> 4;
  1269. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  1270. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  1271. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1272. }
  1273. return buffer;
  1274. }
  1275. /***/ }),
  1276. /* 3 */
  1277. /***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
  1278. var _is_node = __w_pdfjs_require__(4);
  1279. ;
  1280. /***/ }),
  1281. /* 4 */
  1282. /***/ ((__unused_webpack_module, exports) => {
  1283. Object.defineProperty(exports, "__esModule", ({
  1284. value: true
  1285. }));
  1286. exports.isNodeJS = void 0;
  1287. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  1288. exports.isNodeJS = isNodeJS;
  1289. /***/ }),
  1290. /* 5 */
  1291. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1292. Object.defineProperty(exports, "__esModule", ({
  1293. value: true
  1294. }));
  1295. exports.BaseSVGFactory = exports.BaseStandardFontDataFactory = exports.BaseCMapReaderFactory = exports.BaseCanvasFactory = void 0;
  1296. var _util = __w_pdfjs_require__(2);
  1297. class BaseCanvasFactory {
  1298. constructor() {
  1299. if (this.constructor === BaseCanvasFactory) {
  1300. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  1301. }
  1302. }
  1303. create(width, height) {
  1304. if (width <= 0 || height <= 0) {
  1305. throw new Error("Invalid canvas size");
  1306. }
  1307. const canvas = this._createCanvas(width, height);
  1308. return {
  1309. canvas,
  1310. context: canvas.getContext("2d")
  1311. };
  1312. }
  1313. reset(canvasAndContext, width, height) {
  1314. if (!canvasAndContext.canvas) {
  1315. throw new Error("Canvas is not specified");
  1316. }
  1317. if (width <= 0 || height <= 0) {
  1318. throw new Error("Invalid canvas size");
  1319. }
  1320. canvasAndContext.canvas.width = width;
  1321. canvasAndContext.canvas.height = height;
  1322. }
  1323. destroy(canvasAndContext) {
  1324. if (!canvasAndContext.canvas) {
  1325. throw new Error("Canvas is not specified");
  1326. }
  1327. canvasAndContext.canvas.width = 0;
  1328. canvasAndContext.canvas.height = 0;
  1329. canvasAndContext.canvas = null;
  1330. canvasAndContext.context = null;
  1331. }
  1332. _createCanvas(width, height) {
  1333. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  1334. }
  1335. }
  1336. exports.BaseCanvasFactory = BaseCanvasFactory;
  1337. class BaseCMapReaderFactory {
  1338. constructor({
  1339. baseUrl = null,
  1340. isCompressed = false
  1341. }) {
  1342. if (this.constructor === BaseCMapReaderFactory) {
  1343. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  1344. }
  1345. this.baseUrl = baseUrl;
  1346. this.isCompressed = isCompressed;
  1347. }
  1348. async fetch({
  1349. name
  1350. }) {
  1351. if (!this.baseUrl) {
  1352. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  1353. }
  1354. if (!name) {
  1355. throw new Error("CMap name must be specified.");
  1356. }
  1357. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  1358. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  1359. return this._fetchData(url, compressionType).catch(reason => {
  1360. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  1361. });
  1362. }
  1363. _fetchData(url, compressionType) {
  1364. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  1365. }
  1366. }
  1367. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  1368. class BaseStandardFontDataFactory {
  1369. constructor({
  1370. baseUrl = null
  1371. }) {
  1372. if (this.constructor === BaseStandardFontDataFactory) {
  1373. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  1374. }
  1375. this.baseUrl = baseUrl;
  1376. }
  1377. async fetch({
  1378. filename
  1379. }) {
  1380. if (!this.baseUrl) {
  1381. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  1382. }
  1383. if (!filename) {
  1384. throw new Error("Font filename must be specified.");
  1385. }
  1386. const url = `${this.baseUrl}${filename}`;
  1387. return this._fetchData(url).catch(reason => {
  1388. throw new Error(`Unable to load font data at: ${url}`);
  1389. });
  1390. }
  1391. _fetchData(url) {
  1392. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  1393. }
  1394. }
  1395. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  1396. class BaseSVGFactory {
  1397. constructor() {
  1398. if (this.constructor === BaseSVGFactory) {
  1399. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  1400. }
  1401. }
  1402. create(width, height) {
  1403. if (width <= 0 || height <= 0) {
  1404. throw new Error("Invalid SVG dimensions");
  1405. }
  1406. const svg = this._createSVG("svg:svg");
  1407. svg.setAttribute("version", "1.1");
  1408. svg.setAttribute("width", `${width}px`);
  1409. svg.setAttribute("height", `${height}px`);
  1410. svg.setAttribute("preserveAspectRatio", "none");
  1411. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  1412. return svg;
  1413. }
  1414. createElement(type) {
  1415. if (typeof type !== "string") {
  1416. throw new Error("Invalid SVG element type");
  1417. }
  1418. return this._createSVG(type);
  1419. }
  1420. _createSVG(type) {
  1421. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  1422. }
  1423. }
  1424. exports.BaseSVGFactory = BaseSVGFactory;
  1425. /***/ }),
  1426. /* 6 */
  1427. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1428. Object.defineProperty(exports, "__esModule", ({
  1429. value: true
  1430. }));
  1431. exports.getDocument = getDocument;
  1432. exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
  1433. exports.version = exports.RenderTask = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCMapReaderFactory = exports.DefaultCanvasFactory = exports.build = void 0;
  1434. var _util = __w_pdfjs_require__(2);
  1435. var _display_utils = __w_pdfjs_require__(1);
  1436. var _font_loader = __w_pdfjs_require__(7);
  1437. var _node_utils = __w_pdfjs_require__(8);
  1438. var _annotation_storage = __w_pdfjs_require__(9);
  1439. var _canvas = __w_pdfjs_require__(10);
  1440. var _worker_options = __w_pdfjs_require__(12);
  1441. var _is_node = __w_pdfjs_require__(4);
  1442. var _message_handler = __w_pdfjs_require__(13);
  1443. var _metadata = __w_pdfjs_require__(14);
  1444. var _optional_content_config = __w_pdfjs_require__(15);
  1445. var _transport_stream = __w_pdfjs_require__(16);
  1446. var _xfa_text = __w_pdfjs_require__(17);
  1447. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  1448. const RENDERING_CANCELLED_TIMEOUT = 100;
  1449. const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
  1450. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  1451. const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
  1452. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  1453. const DefaultStandardFontDataFactory = _is_node.isNodeJS ? _node_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory;
  1454. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  1455. let createPDFNetworkStream;
  1456. function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
  1457. createPDFNetworkStream = pdfNetworkStreamFactory;
  1458. }
  1459. function getDocument(src) {
  1460. const task = new PDFDocumentLoadingTask();
  1461. let source;
  1462. if (typeof src === "string" || src instanceof URL) {
  1463. source = {
  1464. url: src
  1465. };
  1466. } else if ((0, _util.isArrayBuffer)(src)) {
  1467. source = {
  1468. data: src
  1469. };
  1470. } else if (src instanceof PDFDataRangeTransport) {
  1471. source = {
  1472. range: src
  1473. };
  1474. } else {
  1475. if (typeof src !== "object") {
  1476. throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
  1477. }
  1478. if (!src.url && !src.data && !src.range) {
  1479. throw new Error("Invalid parameter object: need either .data, .range or .url");
  1480. }
  1481. source = src;
  1482. }
  1483. const params = Object.create(null);
  1484. let rangeTransport = null,
  1485. worker = null;
  1486. for (const key in source) {
  1487. const value = source[key];
  1488. switch (key) {
  1489. case "url":
  1490. if (typeof window !== "undefined") {
  1491. try {
  1492. params[key] = new URL(value, window.location).href;
  1493. continue;
  1494. } catch (ex) {
  1495. (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
  1496. }
  1497. } else if (typeof value === "string" || value instanceof URL) {
  1498. params[key] = value.toString();
  1499. continue;
  1500. }
  1501. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1502. case "range":
  1503. rangeTransport = value;
  1504. continue;
  1505. case "worker":
  1506. worker = value;
  1507. continue;
  1508. case "data":
  1509. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
  1510. params[key] = new Uint8Array(value);
  1511. } else if (value instanceof Uint8Array) {
  1512. break;
  1513. } else if (typeof value === "string") {
  1514. params[key] = (0, _util.stringToBytes)(value);
  1515. } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
  1516. params[key] = new Uint8Array(value);
  1517. } else if ((0, _util.isArrayBuffer)(value)) {
  1518. params[key] = new Uint8Array(value);
  1519. } else {
  1520. throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
  1521. }
  1522. continue;
  1523. }
  1524. params[key] = value;
  1525. }
  1526. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  1527. params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
  1528. params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
  1529. params.ignoreErrors = params.stopAtErrors !== true;
  1530. params.fontExtraProperties = params.fontExtraProperties === true;
  1531. params.pdfBug = params.pdfBug === true;
  1532. params.enableXfa = params.enableXfa === true;
  1533. if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
  1534. params.docBaseUrl = null;
  1535. }
  1536. if (!Number.isInteger(params.maxImageSize)) {
  1537. params.maxImageSize = -1;
  1538. }
  1539. if (typeof params.useWorkerFetch !== "boolean") {
  1540. params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
  1541. }
  1542. if (typeof params.isEvalSupported !== "boolean") {
  1543. params.isEvalSupported = true;
  1544. }
  1545. if (typeof params.disableFontFace !== "boolean") {
  1546. params.disableFontFace = _is_node.isNodeJS;
  1547. }
  1548. if (typeof params.useSystemFonts !== "boolean") {
  1549. params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
  1550. }
  1551. if (typeof params.ownerDocument === "undefined") {
  1552. params.ownerDocument = globalThis.document;
  1553. }
  1554. if (typeof params.disableRange !== "boolean") {
  1555. params.disableRange = false;
  1556. }
  1557. if (typeof params.disableStream !== "boolean") {
  1558. params.disableStream = false;
  1559. }
  1560. if (typeof params.disableAutoFetch !== "boolean") {
  1561. params.disableAutoFetch = false;
  1562. }
  1563. (0, _util.setVerbosityLevel)(params.verbosity);
  1564. if (!worker) {
  1565. const workerParams = {
  1566. verbosity: params.verbosity,
  1567. port: _worker_options.GlobalWorkerOptions.workerPort
  1568. };
  1569. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  1570. task._worker = worker;
  1571. }
  1572. const docId = task.docId;
  1573. worker.promise.then(function () {
  1574. if (task.destroyed) {
  1575. throw new Error("Loading aborted");
  1576. }
  1577. const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
  1578. const networkStreamPromise = new Promise(function (resolve) {
  1579. let networkStream;
  1580. if (rangeTransport) {
  1581. networkStream = new _transport_stream.PDFDataTransportStream({
  1582. length: params.length,
  1583. initialData: params.initialData,
  1584. progressiveDone: params.progressiveDone,
  1585. contentDispositionFilename: params.contentDispositionFilename,
  1586. disableRange: params.disableRange,
  1587. disableStream: params.disableStream
  1588. }, rangeTransport);
  1589. } else if (!params.data) {
  1590. networkStream = createPDFNetworkStream({
  1591. url: params.url,
  1592. length: params.length,
  1593. httpHeaders: params.httpHeaders,
  1594. withCredentials: params.withCredentials,
  1595. rangeChunkSize: params.rangeChunkSize,
  1596. disableRange: params.disableRange,
  1597. disableStream: params.disableStream
  1598. });
  1599. }
  1600. resolve(networkStream);
  1601. });
  1602. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1603. if (task.destroyed) {
  1604. throw new Error("Loading aborted");
  1605. }
  1606. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1607. messageHandler.postMessageTransfers = worker.postMessageTransfers;
  1608. const transport = new WorkerTransport(messageHandler, task, networkStream, params);
  1609. task._transport = transport;
  1610. messageHandler.send("Ready", null);
  1611. });
  1612. }).catch(task._capability.reject);
  1613. return task;
  1614. }
  1615. async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  1616. if (worker.destroyed) {
  1617. throw new Error("Worker was destroyed");
  1618. }
  1619. if (pdfDataRangeTransport) {
  1620. source.length = pdfDataRangeTransport.length;
  1621. source.initialData = pdfDataRangeTransport.initialData;
  1622. source.progressiveDone = pdfDataRangeTransport.progressiveDone;
  1623. source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
  1624. }
  1625. const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
  1626. docId,
  1627. apiVersion: '2.11.338',
  1628. source: {
  1629. data: source.data,
  1630. url: source.url,
  1631. password: source.password,
  1632. disableAutoFetch: source.disableAutoFetch,
  1633. rangeChunkSize: source.rangeChunkSize,
  1634. length: source.length
  1635. },
  1636. maxImageSize: source.maxImageSize,
  1637. disableFontFace: source.disableFontFace,
  1638. postMessageTransfers: worker.postMessageTransfers,
  1639. docBaseUrl: source.docBaseUrl,
  1640. ignoreErrors: source.ignoreErrors,
  1641. isEvalSupported: source.isEvalSupported,
  1642. fontExtraProperties: source.fontExtraProperties,
  1643. enableXfa: source.enableXfa,
  1644. useSystemFonts: source.useSystemFonts,
  1645. cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
  1646. standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
  1647. });
  1648. if (worker.destroyed) {
  1649. throw new Error("Worker was destroyed");
  1650. }
  1651. return workerId;
  1652. }
  1653. class PDFDocumentLoadingTask {
  1654. static get idCounters() {
  1655. return (0, _util.shadow)(this, "idCounters", {
  1656. doc: 0
  1657. });
  1658. }
  1659. constructor() {
  1660. this._capability = (0, _util.createPromiseCapability)();
  1661. this._transport = null;
  1662. this._worker = null;
  1663. this.docId = `d${PDFDocumentLoadingTask.idCounters.doc++}`;
  1664. this.destroyed = false;
  1665. this.onPassword = null;
  1666. this.onProgress = null;
  1667. this.onUnsupportedFeature = null;
  1668. }
  1669. get promise() {
  1670. return this._capability.promise;
  1671. }
  1672. async destroy() {
  1673. this.destroyed = true;
  1674. await this._transport?.destroy();
  1675. this._transport = null;
  1676. if (this._worker) {
  1677. this._worker.destroy();
  1678. this._worker = null;
  1679. }
  1680. }
  1681. }
  1682. exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
  1683. class PDFDataRangeTransport {
  1684. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1685. this.length = length;
  1686. this.initialData = initialData;
  1687. this.progressiveDone = progressiveDone;
  1688. this.contentDispositionFilename = contentDispositionFilename;
  1689. this._rangeListeners = [];
  1690. this._progressListeners = [];
  1691. this._progressiveReadListeners = [];
  1692. this._progressiveDoneListeners = [];
  1693. this._readyCapability = (0, _util.createPromiseCapability)();
  1694. }
  1695. addRangeListener(listener) {
  1696. this._rangeListeners.push(listener);
  1697. }
  1698. addProgressListener(listener) {
  1699. this._progressListeners.push(listener);
  1700. }
  1701. addProgressiveReadListener(listener) {
  1702. this._progressiveReadListeners.push(listener);
  1703. }
  1704. addProgressiveDoneListener(listener) {
  1705. this._progressiveDoneListeners.push(listener);
  1706. }
  1707. onDataRange(begin, chunk) {
  1708. for (const listener of this._rangeListeners) {
  1709. listener(begin, chunk);
  1710. }
  1711. }
  1712. onDataProgress(loaded, total) {
  1713. this._readyCapability.promise.then(() => {
  1714. for (const listener of this._progressListeners) {
  1715. listener(loaded, total);
  1716. }
  1717. });
  1718. }
  1719. onDataProgressiveRead(chunk) {
  1720. this._readyCapability.promise.then(() => {
  1721. for (const listener of this._progressiveReadListeners) {
  1722. listener(chunk);
  1723. }
  1724. });
  1725. }
  1726. onDataProgressiveDone() {
  1727. this._readyCapability.promise.then(() => {
  1728. for (const listener of this._progressiveDoneListeners) {
  1729. listener();
  1730. }
  1731. });
  1732. }
  1733. transportReady() {
  1734. this._readyCapability.resolve();
  1735. }
  1736. requestDataRange(begin, end) {
  1737. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1738. }
  1739. abort() {}
  1740. }
  1741. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1742. class PDFDocumentProxy {
  1743. constructor(pdfInfo, transport) {
  1744. this._pdfInfo = pdfInfo;
  1745. this._transport = transport;
  1746. Object.defineProperty(this, "fingerprint", {
  1747. get() {
  1748. (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
  1749. return this.fingerprints[0];
  1750. }
  1751. });
  1752. }
  1753. get annotationStorage() {
  1754. return this._transport.annotationStorage;
  1755. }
  1756. get numPages() {
  1757. return this._pdfInfo.numPages;
  1758. }
  1759. get fingerprints() {
  1760. return this._pdfInfo.fingerprints;
  1761. }
  1762. get isPureXfa() {
  1763. return !!this._transport._htmlForXfa;
  1764. }
  1765. get allXfaHtml() {
  1766. return this._transport._htmlForXfa;
  1767. }
  1768. getPage(pageNumber) {
  1769. return this._transport.getPage(pageNumber);
  1770. }
  1771. getPageIndex(ref) {
  1772. return this._transport.getPageIndex(ref);
  1773. }
  1774. getDestinations() {
  1775. return this._transport.getDestinations();
  1776. }
  1777. getDestination(id) {
  1778. return this._transport.getDestination(id);
  1779. }
  1780. getPageLabels() {
  1781. return this._transport.getPageLabels();
  1782. }
  1783. getPageLayout() {
  1784. return this._transport.getPageLayout();
  1785. }
  1786. getPageMode() {
  1787. return this._transport.getPageMode();
  1788. }
  1789. getViewerPreferences() {
  1790. return this._transport.getViewerPreferences();
  1791. }
  1792. getOpenAction() {
  1793. return this._transport.getOpenAction();
  1794. }
  1795. getAttachments() {
  1796. return this._transport.getAttachments();
  1797. }
  1798. getJavaScript() {
  1799. return this._transport.getJavaScript();
  1800. }
  1801. getJSActions() {
  1802. return this._transport.getDocJSActions();
  1803. }
  1804. getOutline() {
  1805. return this._transport.getOutline();
  1806. }
  1807. getOptionalContentConfig() {
  1808. return this._transport.getOptionalContentConfig();
  1809. }
  1810. getPermissions() {
  1811. return this._transport.getPermissions();
  1812. }
  1813. getMetadata() {
  1814. return this._transport.getMetadata();
  1815. }
  1816. getMarkInfo() {
  1817. return this._transport.getMarkInfo();
  1818. }
  1819. getData() {
  1820. return this._transport.getData();
  1821. }
  1822. getDownloadInfo() {
  1823. return this._transport.downloadInfoCapability.promise;
  1824. }
  1825. getStats() {
  1826. return this._transport.getStats();
  1827. }
  1828. cleanup(keepLoadedFonts = false) {
  1829. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1830. }
  1831. destroy() {
  1832. return this.loadingTask.destroy();
  1833. }
  1834. get loadingParams() {
  1835. return this._transport.loadingParams;
  1836. }
  1837. get loadingTask() {
  1838. return this._transport.loadingTask;
  1839. }
  1840. saveDocument() {
  1841. if (this._transport.annotationStorage.size <= 0) {
  1842. (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  1843. }
  1844. return this._transport.saveDocument();
  1845. }
  1846. getFieldObjects() {
  1847. return this._transport.getFieldObjects();
  1848. }
  1849. hasJSActions() {
  1850. return this._transport.hasJSActions();
  1851. }
  1852. getCalculationOrderIds() {
  1853. return this._transport.getCalculationOrderIds();
  1854. }
  1855. }
  1856. exports.PDFDocumentProxy = PDFDocumentProxy;
  1857. class PDFPageProxy {
  1858. constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
  1859. this._pageIndex = pageIndex;
  1860. this._pageInfo = pageInfo;
  1861. this._ownerDocument = ownerDocument;
  1862. this._transport = transport;
  1863. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1864. this._pdfBug = pdfBug;
  1865. this.commonObjs = transport.commonObjs;
  1866. this.objs = new PDFObjects();
  1867. this.cleanupAfterRender = false;
  1868. this.pendingCleanup = false;
  1869. this._intentStates = new Map();
  1870. this._annotationPromises = new Map();
  1871. this.destroyed = false;
  1872. }
  1873. get pageNumber() {
  1874. return this._pageIndex + 1;
  1875. }
  1876. get rotate() {
  1877. return this._pageInfo.rotate;
  1878. }
  1879. get ref() {
  1880. return this._pageInfo.ref;
  1881. }
  1882. get userUnit() {
  1883. return this._pageInfo.userUnit;
  1884. }
  1885. get view() {
  1886. return this._pageInfo.view;
  1887. }
  1888. getViewport({
  1889. scale,
  1890. rotation = this.rotate,
  1891. offsetX = 0,
  1892. offsetY = 0,
  1893. dontFlip = false
  1894. } = {}) {
  1895. return new _display_utils.PageViewport({
  1896. viewBox: this.view,
  1897. scale,
  1898. rotation,
  1899. offsetX,
  1900. offsetY,
  1901. dontFlip
  1902. });
  1903. }
  1904. getAnnotations({
  1905. intent = "display"
  1906. } = {}) {
  1907. const intentArgs = this._transport.getRenderingIntent(intent);
  1908. let promise = this._annotationPromises.get(intentArgs.cacheKey);
  1909. if (!promise) {
  1910. promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  1911. this._annotationPromises.set(intentArgs.cacheKey, promise);
  1912. promise = promise.then(annotations => {
  1913. for (const annotation of annotations) {
  1914. if (annotation.titleObj !== undefined) {
  1915. Object.defineProperty(annotation, "title", {
  1916. get() {
  1917. (0, _display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead.");
  1918. return annotation.titleObj.str;
  1919. }
  1920. });
  1921. }
  1922. if (annotation.contentsObj !== undefined) {
  1923. Object.defineProperty(annotation, "contents", {
  1924. get() {
  1925. (0, _display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead.");
  1926. return annotation.contentsObj.str;
  1927. }
  1928. });
  1929. }
  1930. }
  1931. return annotations;
  1932. });
  1933. }
  1934. return promise;
  1935. }
  1936. getJSActions() {
  1937. return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
  1938. }
  1939. async getXfa() {
  1940. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  1941. }
  1942. render({
  1943. canvasContext,
  1944. viewport,
  1945. intent = "display",
  1946. annotationMode = _util.AnnotationMode.ENABLE,
  1947. transform = null,
  1948. imageLayer = null,
  1949. canvasFactory = null,
  1950. background = null,
  1951. optionalContentConfigPromise = null
  1952. }) {
  1953. if (arguments[0]?.renderInteractiveForms !== undefined) {
  1954. (0, _display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, " + "please use the `annotationMode`-option instead.");
  1955. if (arguments[0].renderInteractiveForms === true && annotationMode === _util.AnnotationMode.ENABLE) {
  1956. annotationMode = _util.AnnotationMode.ENABLE_FORMS;
  1957. }
  1958. }
  1959. if (arguments[0]?.includeAnnotationStorage !== undefined) {
  1960. (0, _display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, " + "please use the `annotationMode`-option instead.");
  1961. if (arguments[0].includeAnnotationStorage === true && annotationMode === _util.AnnotationMode.ENABLE) {
  1962. annotationMode = _util.AnnotationMode.ENABLE_STORAGE;
  1963. }
  1964. }
  1965. if (this._stats) {
  1966. this._stats.time("Overall");
  1967. }
  1968. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode);
  1969. this.pendingCleanup = false;
  1970. if (!optionalContentConfigPromise) {
  1971. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1972. }
  1973. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1974. if (!intentState) {
  1975. intentState = Object.create(null);
  1976. this._intentStates.set(intentArgs.cacheKey, intentState);
  1977. }
  1978. if (intentState.streamReaderCancelTimeout) {
  1979. clearTimeout(intentState.streamReaderCancelTimeout);
  1980. intentState.streamReaderCancelTimeout = null;
  1981. }
  1982. const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
  1983. ownerDocument: this._ownerDocument
  1984. });
  1985. const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
  1986. if (!intentState.displayReadyCapability) {
  1987. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  1988. intentState.operatorList = {
  1989. fnArray: [],
  1990. argsArray: [],
  1991. lastChunk: false
  1992. };
  1993. if (this._stats) {
  1994. this._stats.time("Page Request");
  1995. }
  1996. this._pumpOperatorList(intentArgs);
  1997. }
  1998. const complete = error => {
  1999. intentState.renderTasks.delete(internalRenderTask);
  2000. if (this.cleanupAfterRender || intentPrint) {
  2001. this.pendingCleanup = true;
  2002. }
  2003. this._tryCleanup();
  2004. if (error) {
  2005. internalRenderTask.capability.reject(error);
  2006. this._abortOperatorList({
  2007. intentState,
  2008. reason: error instanceof Error ? error : new Error(error)
  2009. });
  2010. } else {
  2011. internalRenderTask.capability.resolve();
  2012. }
  2013. if (this._stats) {
  2014. this._stats.timeEnd("Rendering");
  2015. this._stats.timeEnd("Overall");
  2016. }
  2017. };
  2018. const internalRenderTask = new InternalRenderTask({
  2019. callback: complete,
  2020. params: {
  2021. canvasContext,
  2022. viewport,
  2023. transform,
  2024. imageLayer,
  2025. background
  2026. },
  2027. objs: this.objs,
  2028. commonObjs: this.commonObjs,
  2029. operatorList: intentState.operatorList,
  2030. pageIndex: this._pageIndex,
  2031. canvasFactory: canvasFactoryInstance,
  2032. useRequestAnimationFrame: !intentPrint,
  2033. pdfBug: this._pdfBug
  2034. });
  2035. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  2036. const renderTask = internalRenderTask.task;
  2037. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  2038. if (this.pendingCleanup) {
  2039. complete();
  2040. return;
  2041. }
  2042. if (this._stats) {
  2043. this._stats.time("Rendering");
  2044. }
  2045. internalRenderTask.initializeGraphics({
  2046. transparency,
  2047. optionalContentConfig
  2048. });
  2049. internalRenderTask.operatorListChanged();
  2050. }).catch(complete);
  2051. return renderTask;
  2052. }
  2053. getOperatorList({
  2054. intent = "display",
  2055. annotationMode = _util.AnnotationMode.ENABLE
  2056. } = {}) {
  2057. function operatorListChanged() {
  2058. if (intentState.operatorList.lastChunk) {
  2059. intentState.opListReadCapability.resolve(intentState.operatorList);
  2060. intentState.renderTasks.delete(opListTask);
  2061. }
  2062. }
  2063. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, true);
  2064. let intentState = this._intentStates.get(intentArgs.cacheKey);
  2065. if (!intentState) {
  2066. intentState = Object.create(null);
  2067. this._intentStates.set(intentArgs.cacheKey, intentState);
  2068. }
  2069. let opListTask;
  2070. if (!intentState.opListReadCapability) {
  2071. opListTask = Object.create(null);
  2072. opListTask.operatorListChanged = operatorListChanged;
  2073. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  2074. (intentState.renderTasks ||= new Set()).add(opListTask);
  2075. intentState.operatorList = {
  2076. fnArray: [],
  2077. argsArray: [],
  2078. lastChunk: false
  2079. };
  2080. if (this._stats) {
  2081. this._stats.time("Page Request");
  2082. }
  2083. this._pumpOperatorList(intentArgs);
  2084. }
  2085. return intentState.opListReadCapability.promise;
  2086. }
  2087. streamTextContent({
  2088. normalizeWhitespace = false,
  2089. disableCombineTextItems = false,
  2090. includeMarkedContent = false
  2091. } = {}) {
  2092. const TEXT_CONTENT_CHUNK_SIZE = 100;
  2093. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  2094. pageIndex: this._pageIndex,
  2095. normalizeWhitespace: normalizeWhitespace === true,
  2096. combineTextItems: disableCombineTextItems !== true,
  2097. includeMarkedContent: includeMarkedContent === true
  2098. }, {
  2099. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  2100. size(textContent) {
  2101. return textContent.items.length;
  2102. }
  2103. });
  2104. }
  2105. getTextContent(params = {}) {
  2106. if (this._transport._htmlForXfa) {
  2107. return this.getXfa().then(xfa => {
  2108. return _xfa_text.XfaText.textContent(xfa);
  2109. });
  2110. }
  2111. const readableStream = this.streamTextContent(params);
  2112. return new Promise(function (resolve, reject) {
  2113. function pump() {
  2114. reader.read().then(function ({
  2115. value,
  2116. done
  2117. }) {
  2118. if (done) {
  2119. resolve(textContent);
  2120. return;
  2121. }
  2122. Object.assign(textContent.styles, value.styles);
  2123. textContent.items.push(...value.items);
  2124. pump();
  2125. }, reject);
  2126. }
  2127. const reader = readableStream.getReader();
  2128. const textContent = {
  2129. items: [],
  2130. styles: Object.create(null)
  2131. };
  2132. pump();
  2133. });
  2134. }
  2135. getStructTree() {
  2136. return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
  2137. }
  2138. _destroy() {
  2139. this.destroyed = true;
  2140. this._transport.pageCache[this._pageIndex] = null;
  2141. const waitOn = [];
  2142. for (const intentState of this._intentStates.values()) {
  2143. this._abortOperatorList({
  2144. intentState,
  2145. reason: new Error("Page was destroyed."),
  2146. force: true
  2147. });
  2148. if (intentState.opListReadCapability) {
  2149. continue;
  2150. }
  2151. for (const internalRenderTask of intentState.renderTasks) {
  2152. waitOn.push(internalRenderTask.completed);
  2153. internalRenderTask.cancel();
  2154. }
  2155. }
  2156. this.objs.clear();
  2157. this._annotationPromises.clear();
  2158. this._jsActionsPromise = null;
  2159. this._structTreePromise = null;
  2160. this.pendingCleanup = false;
  2161. return Promise.all(waitOn);
  2162. }
  2163. cleanup(resetStats = false) {
  2164. this.pendingCleanup = true;
  2165. return this._tryCleanup(resetStats);
  2166. }
  2167. _tryCleanup(resetStats = false) {
  2168. if (!this.pendingCleanup) {
  2169. return false;
  2170. }
  2171. for (const {
  2172. renderTasks,
  2173. operatorList
  2174. } of this._intentStates.values()) {
  2175. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  2176. return false;
  2177. }
  2178. }
  2179. this._intentStates.clear();
  2180. this.objs.clear();
  2181. this._annotationPromises.clear();
  2182. this._jsActionsPromise = null;
  2183. this._structTreePromise = null;
  2184. if (resetStats && this._stats) {
  2185. this._stats = new _display_utils.StatTimer();
  2186. }
  2187. this.pendingCleanup = false;
  2188. return true;
  2189. }
  2190. _startRenderPage(transparency, cacheKey) {
  2191. const intentState = this._intentStates.get(cacheKey);
  2192. if (!intentState) {
  2193. return;
  2194. }
  2195. if (this._stats) {
  2196. this._stats.timeEnd("Page Request");
  2197. }
  2198. if (intentState.displayReadyCapability) {
  2199. intentState.displayReadyCapability.resolve(transparency);
  2200. }
  2201. }
  2202. _renderPageChunk(operatorListChunk, intentState) {
  2203. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2204. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2205. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  2206. }
  2207. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2208. for (const internalRenderTask of intentState.renderTasks) {
  2209. internalRenderTask.operatorListChanged();
  2210. }
  2211. if (operatorListChunk.lastChunk) {
  2212. this._tryCleanup();
  2213. }
  2214. }
  2215. _pumpOperatorList({
  2216. renderingIntent,
  2217. cacheKey
  2218. }) {
  2219. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  2220. pageIndex: this._pageIndex,
  2221. intent: renderingIntent,
  2222. cacheKey,
  2223. annotationStorage: renderingIntent & _util.RenderingIntentFlag.ANNOTATIONS_STORAGE ? this._transport.annotationStorage.serializable : null
  2224. });
  2225. const reader = readableStream.getReader();
  2226. const intentState = this._intentStates.get(cacheKey);
  2227. intentState.streamReader = reader;
  2228. const pump = () => {
  2229. reader.read().then(({
  2230. value,
  2231. done
  2232. }) => {
  2233. if (done) {
  2234. intentState.streamReader = null;
  2235. return;
  2236. }
  2237. if (this._transport.destroyed) {
  2238. return;
  2239. }
  2240. this._renderPageChunk(value, intentState);
  2241. pump();
  2242. }, reason => {
  2243. intentState.streamReader = null;
  2244. if (this._transport.destroyed) {
  2245. return;
  2246. }
  2247. if (intentState.operatorList) {
  2248. intentState.operatorList.lastChunk = true;
  2249. for (const internalRenderTask of intentState.renderTasks) {
  2250. internalRenderTask.operatorListChanged();
  2251. }
  2252. this._tryCleanup();
  2253. }
  2254. if (intentState.displayReadyCapability) {
  2255. intentState.displayReadyCapability.reject(reason);
  2256. } else if (intentState.opListReadCapability) {
  2257. intentState.opListReadCapability.reject(reason);
  2258. } else {
  2259. throw reason;
  2260. }
  2261. });
  2262. };
  2263. pump();
  2264. }
  2265. _abortOperatorList({
  2266. intentState,
  2267. reason,
  2268. force = false
  2269. }) {
  2270. if (!intentState.streamReader) {
  2271. return;
  2272. }
  2273. if (!force) {
  2274. if (intentState.renderTasks.size > 0) {
  2275. return;
  2276. }
  2277. if (reason instanceof _display_utils.RenderingCancelledException) {
  2278. intentState.streamReaderCancelTimeout = setTimeout(() => {
  2279. this._abortOperatorList({
  2280. intentState,
  2281. reason,
  2282. force: true
  2283. });
  2284. intentState.streamReaderCancelTimeout = null;
  2285. }, RENDERING_CANCELLED_TIMEOUT);
  2286. return;
  2287. }
  2288. }
  2289. intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
  2290. intentState.streamReader = null;
  2291. if (this._transport.destroyed) {
  2292. return;
  2293. }
  2294. for (const [curCacheKey, curIntentState] of this._intentStates) {
  2295. if (curIntentState === intentState) {
  2296. this._intentStates.delete(curCacheKey);
  2297. break;
  2298. }
  2299. }
  2300. this.cleanup();
  2301. }
  2302. get stats() {
  2303. return this._stats;
  2304. }
  2305. }
  2306. exports.PDFPageProxy = PDFPageProxy;
  2307. class LoopbackPort {
  2308. constructor() {
  2309. this._listeners = [];
  2310. this._deferred = Promise.resolve(undefined);
  2311. }
  2312. postMessage(obj, transfers) {
  2313. function cloneValue(value) {
  2314. if (typeof value === "function" || typeof value === "symbol" || value instanceof URL) {
  2315. throw new Error(`LoopbackPort.postMessage - cannot clone: ${value?.toString()}`);
  2316. }
  2317. if (typeof value !== "object" || value === null) {
  2318. return value;
  2319. }
  2320. if (cloned.has(value)) {
  2321. return cloned.get(value);
  2322. }
  2323. let buffer, result;
  2324. if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) {
  2325. if (transfers?.includes(buffer)) {
  2326. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  2327. } else {
  2328. result = new value.constructor(value);
  2329. }
  2330. cloned.set(value, result);
  2331. return result;
  2332. }
  2333. if (value instanceof Map) {
  2334. result = new Map();
  2335. cloned.set(value, result);
  2336. for (const [key, val] of value) {
  2337. result.set(key, cloneValue(val));
  2338. }
  2339. return result;
  2340. }
  2341. if (value instanceof Set) {
  2342. result = new Set();
  2343. cloned.set(value, result);
  2344. for (const val of value) {
  2345. result.add(cloneValue(val));
  2346. }
  2347. return result;
  2348. }
  2349. result = Array.isArray(value) ? [] : Object.create(null);
  2350. cloned.set(value, result);
  2351. for (const i in value) {
  2352. let desc,
  2353. p = value;
  2354. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  2355. p = Object.getPrototypeOf(p);
  2356. }
  2357. if (typeof desc.value === "undefined") {
  2358. continue;
  2359. }
  2360. if (typeof desc.value === "function" && !value.hasOwnProperty?.(i)) {
  2361. continue;
  2362. }
  2363. result[i] = cloneValue(desc.value);
  2364. }
  2365. return result;
  2366. }
  2367. const cloned = new WeakMap();
  2368. const event = {
  2369. data: cloneValue(obj)
  2370. };
  2371. this._deferred.then(() => {
  2372. for (const listener of this._listeners) {
  2373. listener.call(this, event);
  2374. }
  2375. });
  2376. }
  2377. addEventListener(name, listener) {
  2378. this._listeners.push(listener);
  2379. }
  2380. removeEventListener(name, listener) {
  2381. const i = this._listeners.indexOf(listener);
  2382. this._listeners.splice(i, 1);
  2383. }
  2384. terminate() {
  2385. this._listeners.length = 0;
  2386. }
  2387. }
  2388. exports.LoopbackPort = LoopbackPort;
  2389. const PDFWorkerUtil = {
  2390. isWorkerDisabled: false,
  2391. fallbackWorkerSrc: null,
  2392. fakeWorkerId: 0
  2393. };
  2394. {
  2395. if (_is_node.isNodeJS && typeof require === "function") {
  2396. PDFWorkerUtil.isWorkerDisabled = true;
  2397. PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  2398. } else if (typeof document === "object") {
  2399. const pdfjsFilePath = document?.currentScript?.src;
  2400. if (pdfjsFilePath) {
  2401. PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  2402. }
  2403. }
  2404. PDFWorkerUtil.createCDNWrapper = function (url) {
  2405. const wrapper = `importScripts("${url}");`;
  2406. return URL.createObjectURL(new Blob([wrapper]));
  2407. };
  2408. }
  2409. class PDFWorker {
  2410. static get _workerPorts() {
  2411. return (0, _util.shadow)(this, "_workerPorts", new WeakMap());
  2412. }
  2413. constructor({
  2414. name = null,
  2415. port = null,
  2416. verbosity = (0, _util.getVerbosityLevel)()
  2417. } = {}) {
  2418. if (port && PDFWorker._workerPorts.has(port)) {
  2419. throw new Error("Cannot use more than one PDFWorker per port.");
  2420. }
  2421. this.name = name;
  2422. this.destroyed = false;
  2423. this.postMessageTransfers = true;
  2424. this.verbosity = verbosity;
  2425. this._readyCapability = (0, _util.createPromiseCapability)();
  2426. this._port = null;
  2427. this._webWorker = null;
  2428. this._messageHandler = null;
  2429. if (port) {
  2430. PDFWorker._workerPorts.set(port, this);
  2431. this._initializeFromPort(port);
  2432. return;
  2433. }
  2434. this._initialize();
  2435. }
  2436. get promise() {
  2437. return this._readyCapability.promise;
  2438. }
  2439. get port() {
  2440. return this._port;
  2441. }
  2442. get messageHandler() {
  2443. return this._messageHandler;
  2444. }
  2445. _initializeFromPort(port) {
  2446. this._port = port;
  2447. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  2448. this._messageHandler.on("ready", function () {});
  2449. this._readyCapability.resolve();
  2450. }
  2451. _initialize() {
  2452. if (typeof Worker !== "undefined" && !PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
  2453. let workerSrc = PDFWorker.workerSrc;
  2454. try {
  2455. if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) {
  2456. workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
  2457. }
  2458. const worker = new Worker(workerSrc);
  2459. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  2460. const terminateEarly = () => {
  2461. worker.removeEventListener("error", onWorkerError);
  2462. messageHandler.destroy();
  2463. worker.terminate();
  2464. if (this.destroyed) {
  2465. this._readyCapability.reject(new Error("Worker was destroyed"));
  2466. } else {
  2467. this._setupFakeWorker();
  2468. }
  2469. };
  2470. const onWorkerError = () => {
  2471. if (!this._webWorker) {
  2472. terminateEarly();
  2473. }
  2474. };
  2475. worker.addEventListener("error", onWorkerError);
  2476. messageHandler.on("test", data => {
  2477. worker.removeEventListener("error", onWorkerError);
  2478. if (this.destroyed) {
  2479. terminateEarly();
  2480. return;
  2481. }
  2482. if (data) {
  2483. this._messageHandler = messageHandler;
  2484. this._port = worker;
  2485. this._webWorker = worker;
  2486. if (!data.supportTransfers) {
  2487. this.postMessageTransfers = false;
  2488. }
  2489. this._readyCapability.resolve();
  2490. messageHandler.send("configure", {
  2491. verbosity: this.verbosity
  2492. });
  2493. } else {
  2494. this._setupFakeWorker();
  2495. messageHandler.destroy();
  2496. worker.terminate();
  2497. }
  2498. });
  2499. messageHandler.on("ready", data => {
  2500. worker.removeEventListener("error", onWorkerError);
  2501. if (this.destroyed) {
  2502. terminateEarly();
  2503. return;
  2504. }
  2505. try {
  2506. sendTest();
  2507. } catch (e) {
  2508. this._setupFakeWorker();
  2509. }
  2510. });
  2511. const sendTest = () => {
  2512. const testObj = new Uint8Array([this.postMessageTransfers ? 255 : 0]);
  2513. try {
  2514. messageHandler.send("test", testObj, [testObj.buffer]);
  2515. } catch (ex) {
  2516. (0, _util.warn)("Cannot use postMessage transfers.");
  2517. testObj[0] = 0;
  2518. messageHandler.send("test", testObj);
  2519. }
  2520. };
  2521. sendTest();
  2522. return;
  2523. } catch (e) {
  2524. (0, _util.info)("The worker has been disabled.");
  2525. }
  2526. }
  2527. this._setupFakeWorker();
  2528. }
  2529. _setupFakeWorker() {
  2530. if (!PDFWorkerUtil.isWorkerDisabled) {
  2531. (0, _util.warn)("Setting up fake worker.");
  2532. PDFWorkerUtil.isWorkerDisabled = true;
  2533. }
  2534. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  2535. if (this.destroyed) {
  2536. this._readyCapability.reject(new Error("Worker was destroyed"));
  2537. return;
  2538. }
  2539. const port = new LoopbackPort();
  2540. this._port = port;
  2541. const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
  2542. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  2543. WorkerMessageHandler.setup(workerHandler, port);
  2544. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  2545. this._messageHandler = messageHandler;
  2546. this._readyCapability.resolve();
  2547. messageHandler.send("configure", {
  2548. verbosity: this.verbosity
  2549. });
  2550. }).catch(reason => {
  2551. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  2552. });
  2553. }
  2554. destroy() {
  2555. this.destroyed = true;
  2556. if (this._webWorker) {
  2557. this._webWorker.terminate();
  2558. this._webWorker = null;
  2559. }
  2560. PDFWorker._workerPorts.delete(this._port);
  2561. this._port = null;
  2562. if (this._messageHandler) {
  2563. this._messageHandler.destroy();
  2564. this._messageHandler = null;
  2565. }
  2566. }
  2567. static fromPort(params) {
  2568. if (!params?.port) {
  2569. throw new Error("PDFWorker.fromPort - invalid method signature.");
  2570. }
  2571. if (this._workerPorts.has(params.port)) {
  2572. return this._workerPorts.get(params.port);
  2573. }
  2574. return new PDFWorker(params);
  2575. }
  2576. static get workerSrc() {
  2577. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  2578. return _worker_options.GlobalWorkerOptions.workerSrc;
  2579. }
  2580. if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
  2581. if (!_is_node.isNodeJS) {
  2582. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  2583. }
  2584. return PDFWorkerUtil.fallbackWorkerSrc;
  2585. }
  2586. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  2587. }
  2588. static get _mainThreadWorkerMessageHandler() {
  2589. try {
  2590. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  2591. } catch (ex) {
  2592. return null;
  2593. }
  2594. }
  2595. static get _setupFakeWorkerGlobal() {
  2596. const loader = async () => {
  2597. const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
  2598. if (mainWorkerMessageHandler) {
  2599. return mainWorkerMessageHandler;
  2600. }
  2601. if (_is_node.isNodeJS && typeof require === "function") {
  2602. const worker = eval("require")(this.workerSrc);
  2603. return worker.WorkerMessageHandler;
  2604. }
  2605. await (0, _display_utils.loadScript)(this.workerSrc);
  2606. return window.pdfjsWorker.WorkerMessageHandler;
  2607. };
  2608. return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  2609. }
  2610. }
  2611. exports.PDFWorker = PDFWorker;
  2612. {
  2613. PDFWorker.getWorkerSrc = function () {
  2614. (0, _display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead.");
  2615. return this.workerSrc;
  2616. };
  2617. }
  2618. class WorkerTransport {
  2619. constructor(messageHandler, loadingTask, networkStream, params) {
  2620. this.messageHandler = messageHandler;
  2621. this.loadingTask = loadingTask;
  2622. this.commonObjs = new PDFObjects();
  2623. this.fontLoader = new _font_loader.FontLoader({
  2624. docId: loadingTask.docId,
  2625. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2626. ownerDocument: params.ownerDocument,
  2627. styleElement: params.styleElement
  2628. });
  2629. this._params = params;
  2630. if (!params.useWorkerFetch) {
  2631. this.CMapReaderFactory = new params.CMapReaderFactory({
  2632. baseUrl: params.cMapUrl,
  2633. isCompressed: params.cMapPacked
  2634. });
  2635. this.StandardFontDataFactory = new params.StandardFontDataFactory({
  2636. baseUrl: params.standardFontDataUrl
  2637. });
  2638. }
  2639. this.destroyed = false;
  2640. this.destroyCapability = null;
  2641. this._passwordCapability = null;
  2642. this._networkStream = networkStream;
  2643. this._fullReader = null;
  2644. this._lastProgress = null;
  2645. this.pageCache = [];
  2646. this.pagePromises = [];
  2647. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  2648. this.setupMessageHandler();
  2649. }
  2650. get annotationStorage() {
  2651. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2652. }
  2653. getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, isOpList = false) {
  2654. let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
  2655. let lastModified = "";
  2656. switch (intent) {
  2657. case "any":
  2658. renderingIntent = _util.RenderingIntentFlag.ANY;
  2659. break;
  2660. case "display":
  2661. break;
  2662. case "print":
  2663. renderingIntent = _util.RenderingIntentFlag.PRINT;
  2664. break;
  2665. default:
  2666. (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
  2667. }
  2668. switch (annotationMode) {
  2669. case _util.AnnotationMode.DISABLE:
  2670. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
  2671. break;
  2672. case _util.AnnotationMode.ENABLE:
  2673. break;
  2674. case _util.AnnotationMode.ENABLE_FORMS:
  2675. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
  2676. break;
  2677. case _util.AnnotationMode.ENABLE_STORAGE:
  2678. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
  2679. lastModified = this.annotationStorage.lastModified;
  2680. break;
  2681. default:
  2682. (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  2683. }
  2684. if (isOpList) {
  2685. renderingIntent += _util.RenderingIntentFlag.OPLIST;
  2686. }
  2687. return {
  2688. renderingIntent,
  2689. cacheKey: `${renderingIntent}_${lastModified}`
  2690. };
  2691. }
  2692. destroy() {
  2693. if (this.destroyCapability) {
  2694. return this.destroyCapability.promise;
  2695. }
  2696. this.destroyed = true;
  2697. this.destroyCapability = (0, _util.createPromiseCapability)();
  2698. if (this._passwordCapability) {
  2699. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2700. }
  2701. const waitOn = [];
  2702. for (const page of this.pageCache) {
  2703. if (page) {
  2704. waitOn.push(page._destroy());
  2705. }
  2706. }
  2707. this.pageCache.length = 0;
  2708. this.pagePromises.length = 0;
  2709. if (this.hasOwnProperty("annotationStorage")) {
  2710. this.annotationStorage.resetModified();
  2711. }
  2712. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2713. waitOn.push(terminated);
  2714. Promise.all(waitOn).then(() => {
  2715. this.commonObjs.clear();
  2716. this.fontLoader.clear();
  2717. this._getFieldObjectsPromise = null;
  2718. this._hasJSActionsPromise = null;
  2719. if (this._networkStream) {
  2720. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2721. }
  2722. if (this.messageHandler) {
  2723. this.messageHandler.destroy();
  2724. this.messageHandler = null;
  2725. }
  2726. this.destroyCapability.resolve();
  2727. }, this.destroyCapability.reject);
  2728. return this.destroyCapability.promise;
  2729. }
  2730. setupMessageHandler() {
  2731. const {
  2732. messageHandler,
  2733. loadingTask
  2734. } = this;
  2735. messageHandler.on("GetReader", (data, sink) => {
  2736. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2737. this._fullReader = this._networkStream.getFullReader();
  2738. this._fullReader.onProgress = evt => {
  2739. this._lastProgress = {
  2740. loaded: evt.loaded,
  2741. total: evt.total
  2742. };
  2743. };
  2744. sink.onPull = () => {
  2745. this._fullReader.read().then(function ({
  2746. value,
  2747. done
  2748. }) {
  2749. if (done) {
  2750. sink.close();
  2751. return;
  2752. }
  2753. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
  2754. sink.enqueue(new Uint8Array(value), 1, [value]);
  2755. }).catch(reason => {
  2756. sink.error(reason);
  2757. });
  2758. };
  2759. sink.onCancel = reason => {
  2760. this._fullReader.cancel(reason);
  2761. sink.ready.catch(readyReason => {
  2762. if (this.destroyed) {
  2763. return;
  2764. }
  2765. throw readyReason;
  2766. });
  2767. };
  2768. });
  2769. messageHandler.on("ReaderHeadersReady", data => {
  2770. const headersCapability = (0, _util.createPromiseCapability)();
  2771. const fullReader = this._fullReader;
  2772. fullReader.headersReady.then(() => {
  2773. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2774. if (this._lastProgress && loadingTask.onProgress) {
  2775. loadingTask.onProgress(this._lastProgress);
  2776. }
  2777. fullReader.onProgress = evt => {
  2778. if (loadingTask.onProgress) {
  2779. loadingTask.onProgress({
  2780. loaded: evt.loaded,
  2781. total: evt.total
  2782. });
  2783. }
  2784. };
  2785. }
  2786. headersCapability.resolve({
  2787. isStreamingSupported: fullReader.isStreamingSupported,
  2788. isRangeSupported: fullReader.isRangeSupported,
  2789. contentLength: fullReader.contentLength
  2790. });
  2791. }, headersCapability.reject);
  2792. return headersCapability.promise;
  2793. });
  2794. messageHandler.on("GetRangeReader", (data, sink) => {
  2795. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2796. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2797. if (!rangeReader) {
  2798. sink.close();
  2799. return;
  2800. }
  2801. sink.onPull = () => {
  2802. rangeReader.read().then(function ({
  2803. value,
  2804. done
  2805. }) {
  2806. if (done) {
  2807. sink.close();
  2808. return;
  2809. }
  2810. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
  2811. sink.enqueue(new Uint8Array(value), 1, [value]);
  2812. }).catch(reason => {
  2813. sink.error(reason);
  2814. });
  2815. };
  2816. sink.onCancel = reason => {
  2817. rangeReader.cancel(reason);
  2818. sink.ready.catch(readyReason => {
  2819. if (this.destroyed) {
  2820. return;
  2821. }
  2822. throw readyReason;
  2823. });
  2824. };
  2825. });
  2826. messageHandler.on("GetDoc", ({
  2827. pdfInfo
  2828. }) => {
  2829. this._numPages = pdfInfo.numPages;
  2830. this._htmlForXfa = pdfInfo.htmlForXfa;
  2831. delete pdfInfo.htmlForXfa;
  2832. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2833. });
  2834. messageHandler.on("DocException", function (ex) {
  2835. let reason;
  2836. switch (ex.name) {
  2837. case "PasswordException":
  2838. reason = new _util.PasswordException(ex.message, ex.code);
  2839. break;
  2840. case "InvalidPDFException":
  2841. reason = new _util.InvalidPDFException(ex.message);
  2842. break;
  2843. case "MissingPDFException":
  2844. reason = new _util.MissingPDFException(ex.message);
  2845. break;
  2846. case "UnexpectedResponseException":
  2847. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2848. break;
  2849. case "UnknownErrorException":
  2850. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2851. break;
  2852. default:
  2853. (0, _util.unreachable)("DocException - expected a valid Error.");
  2854. }
  2855. loadingTask._capability.reject(reason);
  2856. });
  2857. messageHandler.on("PasswordRequest", exception => {
  2858. this._passwordCapability = (0, _util.createPromiseCapability)();
  2859. if (loadingTask.onPassword) {
  2860. const updatePassword = password => {
  2861. this._passwordCapability.resolve({
  2862. password
  2863. });
  2864. };
  2865. try {
  2866. loadingTask.onPassword(updatePassword, exception.code);
  2867. } catch (ex) {
  2868. this._passwordCapability.reject(ex);
  2869. }
  2870. } else {
  2871. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2872. }
  2873. return this._passwordCapability.promise;
  2874. });
  2875. messageHandler.on("DataLoaded", data => {
  2876. if (loadingTask.onProgress) {
  2877. loadingTask.onProgress({
  2878. loaded: data.length,
  2879. total: data.length
  2880. });
  2881. }
  2882. this.downloadInfoCapability.resolve(data);
  2883. });
  2884. messageHandler.on("StartRenderPage", data => {
  2885. if (this.destroyed) {
  2886. return;
  2887. }
  2888. const page = this.pageCache[data.pageIndex];
  2889. page._startRenderPage(data.transparency, data.cacheKey);
  2890. });
  2891. messageHandler.on("commonobj", data => {
  2892. if (this.destroyed) {
  2893. return;
  2894. }
  2895. const [id, type, exportedData] = data;
  2896. if (this.commonObjs.has(id)) {
  2897. return;
  2898. }
  2899. switch (type) {
  2900. case "Font":
  2901. const params = this._params;
  2902. if ("error" in exportedData) {
  2903. const exportedError = exportedData.error;
  2904. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2905. this.commonObjs.resolve(id, exportedError);
  2906. break;
  2907. }
  2908. let fontRegistry = null;
  2909. if (params.pdfBug && globalThis.FontInspector?.enabled) {
  2910. fontRegistry = {
  2911. registerFont(font, url) {
  2912. globalThis.FontInspector.fontAdded(font, url);
  2913. }
  2914. };
  2915. }
  2916. const font = new _font_loader.FontFaceObject(exportedData, {
  2917. isEvalSupported: params.isEvalSupported,
  2918. disableFontFace: params.disableFontFace,
  2919. ignoreErrors: params.ignoreErrors,
  2920. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2921. fontRegistry
  2922. });
  2923. this.fontLoader.bind(font).catch(reason => {
  2924. return messageHandler.sendWithPromise("FontFallback", {
  2925. id
  2926. });
  2927. }).finally(() => {
  2928. if (!params.fontExtraProperties && font.data) {
  2929. font.data = null;
  2930. }
  2931. this.commonObjs.resolve(id, font);
  2932. });
  2933. break;
  2934. case "FontPath":
  2935. case "Image":
  2936. this.commonObjs.resolve(id, exportedData);
  2937. break;
  2938. default:
  2939. throw new Error(`Got unknown common object type ${type}`);
  2940. }
  2941. });
  2942. messageHandler.on("obj", data => {
  2943. if (this.destroyed) {
  2944. return undefined;
  2945. }
  2946. const [id, pageIndex, type, imageData] = data;
  2947. const pageProxy = this.pageCache[pageIndex];
  2948. if (pageProxy.objs.has(id)) {
  2949. return undefined;
  2950. }
  2951. switch (type) {
  2952. case "Image":
  2953. pageProxy.objs.resolve(id, imageData);
  2954. const MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2955. if (imageData?.data?.length > MAX_IMAGE_SIZE_TO_STORE) {
  2956. pageProxy.cleanupAfterRender = true;
  2957. }
  2958. break;
  2959. case "Pattern":
  2960. pageProxy.objs.resolve(id, imageData);
  2961. break;
  2962. default:
  2963. throw new Error(`Got unknown object type ${type}`);
  2964. }
  2965. return undefined;
  2966. });
  2967. messageHandler.on("DocProgress", data => {
  2968. if (this.destroyed) {
  2969. return;
  2970. }
  2971. if (loadingTask.onProgress) {
  2972. loadingTask.onProgress({
  2973. loaded: data.loaded,
  2974. total: data.total
  2975. });
  2976. }
  2977. });
  2978. messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
  2979. messageHandler.on("FetchBuiltInCMap", data => {
  2980. if (this.destroyed) {
  2981. return Promise.reject(new Error("Worker was destroyed."));
  2982. }
  2983. if (!this.CMapReaderFactory) {
  2984. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  2985. }
  2986. return this.CMapReaderFactory.fetch(data);
  2987. });
  2988. messageHandler.on("FetchStandardFontData", data => {
  2989. if (this.destroyed) {
  2990. return Promise.reject(new Error("Worker was destroyed."));
  2991. }
  2992. if (!this.StandardFontDataFactory) {
  2993. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  2994. }
  2995. return this.StandardFontDataFactory.fetch(data);
  2996. });
  2997. }
  2998. _onUnsupportedFeature({
  2999. featureId
  3000. }) {
  3001. if (this.destroyed) {
  3002. return;
  3003. }
  3004. if (this.loadingTask.onUnsupportedFeature) {
  3005. this.loadingTask.onUnsupportedFeature(featureId);
  3006. }
  3007. }
  3008. getData() {
  3009. return this.messageHandler.sendWithPromise("GetData", null);
  3010. }
  3011. getPage(pageNumber) {
  3012. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  3013. return Promise.reject(new Error("Invalid page request"));
  3014. }
  3015. const pageIndex = pageNumber - 1;
  3016. if (pageIndex in this.pagePromises) {
  3017. return this.pagePromises[pageIndex];
  3018. }
  3019. const promise = this.messageHandler.sendWithPromise("GetPage", {
  3020. pageIndex
  3021. }).then(pageInfo => {
  3022. if (this.destroyed) {
  3023. throw new Error("Transport destroyed");
  3024. }
  3025. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
  3026. this.pageCache[pageIndex] = page;
  3027. return page;
  3028. });
  3029. this.pagePromises[pageIndex] = promise;
  3030. return promise;
  3031. }
  3032. getPageIndex(ref) {
  3033. return this.messageHandler.sendWithPromise("GetPageIndex", {
  3034. ref
  3035. });
  3036. }
  3037. getAnnotations(pageIndex, intent) {
  3038. return this.messageHandler.sendWithPromise("GetAnnotations", {
  3039. pageIndex,
  3040. intent
  3041. });
  3042. }
  3043. saveDocument() {
  3044. return this.messageHandler.sendWithPromise("SaveDocument", {
  3045. isPureXfa: !!this._htmlForXfa,
  3046. numPages: this._numPages,
  3047. annotationStorage: this.annotationStorage.serializable,
  3048. filename: this._fullReader?.filename ?? null
  3049. }).finally(() => {
  3050. this.annotationStorage.resetModified();
  3051. });
  3052. }
  3053. getFieldObjects() {
  3054. return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
  3055. }
  3056. hasJSActions() {
  3057. return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
  3058. }
  3059. getCalculationOrderIds() {
  3060. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  3061. }
  3062. getDestinations() {
  3063. return this.messageHandler.sendWithPromise("GetDestinations", null);
  3064. }
  3065. getDestination(id) {
  3066. if (typeof id !== "string") {
  3067. return Promise.reject(new Error("Invalid destination request."));
  3068. }
  3069. return this.messageHandler.sendWithPromise("GetDestination", {
  3070. id
  3071. });
  3072. }
  3073. getPageLabels() {
  3074. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  3075. }
  3076. getPageLayout() {
  3077. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  3078. }
  3079. getPageMode() {
  3080. return this.messageHandler.sendWithPromise("GetPageMode", null);
  3081. }
  3082. getViewerPreferences() {
  3083. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  3084. }
  3085. getOpenAction() {
  3086. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  3087. }
  3088. getAttachments() {
  3089. return this.messageHandler.sendWithPromise("GetAttachments", null);
  3090. }
  3091. getJavaScript() {
  3092. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  3093. }
  3094. getDocJSActions() {
  3095. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  3096. }
  3097. getPageJSActions(pageIndex) {
  3098. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  3099. pageIndex
  3100. });
  3101. }
  3102. getStructTree(pageIndex) {
  3103. return this.messageHandler.sendWithPromise("GetStructTree", {
  3104. pageIndex
  3105. });
  3106. }
  3107. getOutline() {
  3108. return this.messageHandler.sendWithPromise("GetOutline", null);
  3109. }
  3110. getOptionalContentConfig() {
  3111. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  3112. return new _optional_content_config.OptionalContentConfig(results);
  3113. });
  3114. }
  3115. getPermissions() {
  3116. return this.messageHandler.sendWithPromise("GetPermissions", null);
  3117. }
  3118. getMetadata() {
  3119. return this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
  3120. return {
  3121. info: results[0],
  3122. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  3123. contentDispositionFilename: this._fullReader?.filename ?? null,
  3124. contentLength: this._fullReader?.contentLength ?? null
  3125. };
  3126. });
  3127. }
  3128. getMarkInfo() {
  3129. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  3130. }
  3131. getStats() {
  3132. return this.messageHandler.sendWithPromise("GetStats", null);
  3133. }
  3134. async startCleanup(keepLoadedFonts = false) {
  3135. await this.messageHandler.sendWithPromise("Cleanup", null);
  3136. if (this.destroyed) {
  3137. return;
  3138. }
  3139. for (let i = 0, ii = this.pageCache.length; i < ii; i++) {
  3140. const page = this.pageCache[i];
  3141. if (!page) {
  3142. continue;
  3143. }
  3144. const cleanupSuccessful = page.cleanup();
  3145. if (!cleanupSuccessful) {
  3146. throw new Error(`startCleanup: Page ${i + 1} is currently rendering.`);
  3147. }
  3148. }
  3149. this.commonObjs.clear();
  3150. if (!keepLoadedFonts) {
  3151. this.fontLoader.clear();
  3152. }
  3153. this._getFieldObjectsPromise = null;
  3154. this._hasJSActionsPromise = null;
  3155. }
  3156. get loadingParams() {
  3157. const params = this._params;
  3158. return (0, _util.shadow)(this, "loadingParams", {
  3159. disableAutoFetch: params.disableAutoFetch,
  3160. enableXfa: params.enableXfa
  3161. });
  3162. }
  3163. }
  3164. class PDFObjects {
  3165. constructor() {
  3166. this._objs = Object.create(null);
  3167. }
  3168. _ensureObj(objId) {
  3169. if (this._objs[objId]) {
  3170. return this._objs[objId];
  3171. }
  3172. return this._objs[objId] = {
  3173. capability: (0, _util.createPromiseCapability)(),
  3174. data: null,
  3175. resolved: false
  3176. };
  3177. }
  3178. get(objId, callback = null) {
  3179. if (callback) {
  3180. this._ensureObj(objId).capability.promise.then(callback);
  3181. return null;
  3182. }
  3183. const obj = this._objs[objId];
  3184. if (!obj || !obj.resolved) {
  3185. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  3186. }
  3187. return obj.data;
  3188. }
  3189. has(objId) {
  3190. const obj = this._objs[objId];
  3191. return obj?.resolved || false;
  3192. }
  3193. resolve(objId, data) {
  3194. const obj = this._ensureObj(objId);
  3195. obj.resolved = true;
  3196. obj.data = data;
  3197. obj.capability.resolve(data);
  3198. }
  3199. clear() {
  3200. this._objs = Object.create(null);
  3201. }
  3202. }
  3203. class RenderTask {
  3204. constructor(internalRenderTask) {
  3205. this._internalRenderTask = internalRenderTask;
  3206. this.onContinue = null;
  3207. }
  3208. get promise() {
  3209. return this._internalRenderTask.capability.promise;
  3210. }
  3211. cancel() {
  3212. this._internalRenderTask.cancel();
  3213. }
  3214. }
  3215. exports.RenderTask = RenderTask;
  3216. class InternalRenderTask {
  3217. static get canvasInUse() {
  3218. return (0, _util.shadow)(this, "canvasInUse", new WeakSet());
  3219. }
  3220. constructor({
  3221. callback,
  3222. params,
  3223. objs,
  3224. commonObjs,
  3225. operatorList,
  3226. pageIndex,
  3227. canvasFactory,
  3228. useRequestAnimationFrame = false,
  3229. pdfBug = false
  3230. }) {
  3231. this.callback = callback;
  3232. this.params = params;
  3233. this.objs = objs;
  3234. this.commonObjs = commonObjs;
  3235. this.operatorListIdx = null;
  3236. this.operatorList = operatorList;
  3237. this._pageIndex = pageIndex;
  3238. this.canvasFactory = canvasFactory;
  3239. this._pdfBug = pdfBug;
  3240. this.running = false;
  3241. this.graphicsReadyCallback = null;
  3242. this.graphicsReady = false;
  3243. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  3244. this.cancelled = false;
  3245. this.capability = (0, _util.createPromiseCapability)();
  3246. this.task = new RenderTask(this);
  3247. this._cancelBound = this.cancel.bind(this);
  3248. this._continueBound = this._continue.bind(this);
  3249. this._scheduleNextBound = this._scheduleNext.bind(this);
  3250. this._nextBound = this._next.bind(this);
  3251. this._canvas = params.canvasContext.canvas;
  3252. }
  3253. get completed() {
  3254. return this.capability.promise.catch(function () {});
  3255. }
  3256. initializeGraphics({
  3257. transparency = false,
  3258. optionalContentConfig
  3259. }) {
  3260. if (this.cancelled) {
  3261. return;
  3262. }
  3263. if (this._canvas) {
  3264. if (InternalRenderTask.canvasInUse.has(this._canvas)) {
  3265. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  3266. }
  3267. InternalRenderTask.canvasInUse.add(this._canvas);
  3268. }
  3269. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  3270. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  3271. this.stepper.init(this.operatorList);
  3272. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  3273. }
  3274. const {
  3275. canvasContext,
  3276. viewport,
  3277. transform,
  3278. imageLayer,
  3279. background
  3280. } = this.params;
  3281. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig);
  3282. this.gfx.beginDrawing({
  3283. transform,
  3284. viewport,
  3285. transparency,
  3286. background
  3287. });
  3288. this.operatorListIdx = 0;
  3289. this.graphicsReady = true;
  3290. if (this.graphicsReadyCallback) {
  3291. this.graphicsReadyCallback();
  3292. }
  3293. }
  3294. cancel(error = null) {
  3295. this.running = false;
  3296. this.cancelled = true;
  3297. if (this.gfx) {
  3298. this.gfx.endDrawing();
  3299. }
  3300. if (this._canvas) {
  3301. InternalRenderTask.canvasInUse.delete(this._canvas);
  3302. }
  3303. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
  3304. }
  3305. operatorListChanged() {
  3306. if (!this.graphicsReady) {
  3307. if (!this.graphicsReadyCallback) {
  3308. this.graphicsReadyCallback = this._continueBound;
  3309. }
  3310. return;
  3311. }
  3312. if (this.stepper) {
  3313. this.stepper.updateOperatorList(this.operatorList);
  3314. }
  3315. if (this.running) {
  3316. return;
  3317. }
  3318. this._continue();
  3319. }
  3320. _continue() {
  3321. this.running = true;
  3322. if (this.cancelled) {
  3323. return;
  3324. }
  3325. if (this.task.onContinue) {
  3326. this.task.onContinue(this._scheduleNextBound);
  3327. } else {
  3328. this._scheduleNext();
  3329. }
  3330. }
  3331. _scheduleNext() {
  3332. if (this._useRequestAnimationFrame) {
  3333. window.requestAnimationFrame(() => {
  3334. this._nextBound().catch(this._cancelBound);
  3335. });
  3336. } else {
  3337. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  3338. }
  3339. }
  3340. async _next() {
  3341. if (this.cancelled) {
  3342. return;
  3343. }
  3344. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  3345. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  3346. this.running = false;
  3347. if (this.operatorList.lastChunk) {
  3348. this.gfx.endDrawing();
  3349. if (this._canvas) {
  3350. InternalRenderTask.canvasInUse.delete(this._canvas);
  3351. }
  3352. this.callback();
  3353. }
  3354. }
  3355. }
  3356. }
  3357. const version = '2.11.338';
  3358. exports.version = version;
  3359. const build = 'dedff3c98';
  3360. exports.build = build;
  3361. /***/ }),
  3362. /* 7 */
  3363. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3364. Object.defineProperty(exports, "__esModule", ({
  3365. value: true
  3366. }));
  3367. exports.FontLoader = exports.FontFaceObject = void 0;
  3368. var _util = __w_pdfjs_require__(2);
  3369. class BaseFontLoader {
  3370. constructor({
  3371. docId,
  3372. onUnsupportedFeature,
  3373. ownerDocument = globalThis.document,
  3374. styleElement = null
  3375. }) {
  3376. if (this.constructor === BaseFontLoader) {
  3377. (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
  3378. }
  3379. this.docId = docId;
  3380. this._onUnsupportedFeature = onUnsupportedFeature;
  3381. this._document = ownerDocument;
  3382. this.nativeFontFaces = [];
  3383. this.styleElement = null;
  3384. }
  3385. addNativeFontFace(nativeFontFace) {
  3386. this.nativeFontFaces.push(nativeFontFace);
  3387. this._document.fonts.add(nativeFontFace);
  3388. }
  3389. insertRule(rule) {
  3390. let styleElement = this.styleElement;
  3391. if (!styleElement) {
  3392. styleElement = this.styleElement = this._document.createElement("style");
  3393. styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
  3394. this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
  3395. }
  3396. const styleSheet = styleElement.sheet;
  3397. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  3398. }
  3399. clear() {
  3400. for (const nativeFontFace of this.nativeFontFaces) {
  3401. this._document.fonts.delete(nativeFontFace);
  3402. }
  3403. this.nativeFontFaces.length = 0;
  3404. if (this.styleElement) {
  3405. this.styleElement.remove();
  3406. this.styleElement = null;
  3407. }
  3408. }
  3409. async bind(font) {
  3410. if (font.attached || font.missingFile) {
  3411. return;
  3412. }
  3413. font.attached = true;
  3414. if (this.isFontLoadingAPISupported) {
  3415. const nativeFontFace = font.createNativeFontFace();
  3416. if (nativeFontFace) {
  3417. this.addNativeFontFace(nativeFontFace);
  3418. try {
  3419. await nativeFontFace.loaded;
  3420. } catch (ex) {
  3421. this._onUnsupportedFeature({
  3422. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  3423. });
  3424. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  3425. font.disableFontFace = true;
  3426. throw ex;
  3427. }
  3428. }
  3429. return;
  3430. }
  3431. const rule = font.createFontFaceRule();
  3432. if (rule) {
  3433. this.insertRule(rule);
  3434. if (this.isSyncFontLoadingSupported) {
  3435. return;
  3436. }
  3437. await new Promise(resolve => {
  3438. const request = this._queueLoadingCallback(resolve);
  3439. this._prepareFontLoadEvent([rule], [font], request);
  3440. });
  3441. }
  3442. }
  3443. _queueLoadingCallback(callback) {
  3444. (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
  3445. }
  3446. get isFontLoadingAPISupported() {
  3447. const hasFonts = !!this._document?.fonts;
  3448. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  3449. }
  3450. get isSyncFontLoadingSupported() {
  3451. (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
  3452. }
  3453. get _loadTestFont() {
  3454. (0, _util.unreachable)("Abstract method `_loadTestFont`.");
  3455. }
  3456. _prepareFontLoadEvent(rules, fontsToLoad, request) {
  3457. (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
  3458. }
  3459. }
  3460. let FontLoader;
  3461. exports.FontLoader = FontLoader;
  3462. {
  3463. exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
  3464. constructor(params) {
  3465. super(params);
  3466. this.loadingContext = {
  3467. requests: [],
  3468. nextRequestId: 0
  3469. };
  3470. this.loadTestFontId = 0;
  3471. }
  3472. get isSyncFontLoadingSupported() {
  3473. let supported = false;
  3474. if (typeof navigator === "undefined") {
  3475. supported = true;
  3476. } else {
  3477. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  3478. if (m?.[1] >= 14) {
  3479. supported = true;
  3480. }
  3481. }
  3482. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  3483. }
  3484. _queueLoadingCallback(callback) {
  3485. function completeRequest() {
  3486. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  3487. request.done = true;
  3488. while (context.requests.length > 0 && context.requests[0].done) {
  3489. const otherRequest = context.requests.shift();
  3490. setTimeout(otherRequest.callback, 0);
  3491. }
  3492. }
  3493. const context = this.loadingContext;
  3494. const request = {
  3495. id: `pdfjs-font-loading-${context.nextRequestId++}`,
  3496. done: false,
  3497. complete: completeRequest,
  3498. callback
  3499. };
  3500. context.requests.push(request);
  3501. return request;
  3502. }
  3503. get _loadTestFont() {
  3504. const getLoadTestFont = function () {
  3505. 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==");
  3506. };
  3507. return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
  3508. }
  3509. _prepareFontLoadEvent(rules, fonts, request) {
  3510. function int32(data, offset) {
  3511. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  3512. }
  3513. function spliceString(s, offset, remove, insert) {
  3514. const chunk1 = s.substring(0, offset);
  3515. const chunk2 = s.substring(offset + remove);
  3516. return chunk1 + insert + chunk2;
  3517. }
  3518. let i, ii;
  3519. const canvas = this._document.createElement("canvas");
  3520. canvas.width = 1;
  3521. canvas.height = 1;
  3522. const ctx = canvas.getContext("2d");
  3523. let called = 0;
  3524. function isFontReady(name, callback) {
  3525. called++;
  3526. if (called > 30) {
  3527. (0, _util.warn)("Load test font never loaded.");
  3528. callback();
  3529. return;
  3530. }
  3531. ctx.font = "30px " + name;
  3532. ctx.fillText(".", 0, 20);
  3533. const imageData = ctx.getImageData(0, 0, 1, 1);
  3534. if (imageData.data[3] > 0) {
  3535. callback();
  3536. return;
  3537. }
  3538. setTimeout(isFontReady.bind(null, name, callback));
  3539. }
  3540. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  3541. let data = this._loadTestFont;
  3542. const COMMENT_OFFSET = 976;
  3543. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  3544. const CFF_CHECKSUM_OFFSET = 16;
  3545. const XXXX_VALUE = 0x58585858;
  3546. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  3547. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  3548. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  3549. }
  3550. if (i < loadTestFontId.length) {
  3551. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  3552. }
  3553. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  3554. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  3555. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  3556. this.insertRule(rule);
  3557. const names = [];
  3558. for (const font of fonts) {
  3559. names.push(font.loadedName);
  3560. }
  3561. names.push(loadTestFontId);
  3562. const div = this._document.createElement("div");
  3563. div.style.visibility = "hidden";
  3564. div.style.width = div.style.height = "10px";
  3565. div.style.position = "absolute";
  3566. div.style.top = div.style.left = "0px";
  3567. for (const name of names) {
  3568. const span = this._document.createElement("span");
  3569. span.textContent = "Hi";
  3570. span.style.fontFamily = name;
  3571. div.appendChild(span);
  3572. }
  3573. this._document.body.appendChild(div);
  3574. isFontReady(loadTestFontId, () => {
  3575. this._document.body.removeChild(div);
  3576. request.complete();
  3577. });
  3578. }
  3579. };
  3580. }
  3581. class FontFaceObject {
  3582. constructor(translatedData, {
  3583. isEvalSupported = true,
  3584. disableFontFace = false,
  3585. ignoreErrors = false,
  3586. onUnsupportedFeature,
  3587. fontRegistry = null
  3588. }) {
  3589. this.compiledGlyphs = Object.create(null);
  3590. for (const i in translatedData) {
  3591. this[i] = translatedData[i];
  3592. }
  3593. this.isEvalSupported = isEvalSupported !== false;
  3594. this.disableFontFace = disableFontFace === true;
  3595. this.ignoreErrors = ignoreErrors === true;
  3596. this._onUnsupportedFeature = onUnsupportedFeature;
  3597. this.fontRegistry = fontRegistry;
  3598. }
  3599. createNativeFontFace() {
  3600. if (!this.data || this.disableFontFace) {
  3601. return null;
  3602. }
  3603. let nativeFontFace;
  3604. if (!this.cssFontInfo) {
  3605. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  3606. } else {
  3607. const css = {
  3608. weight: this.cssFontInfo.fontWeight
  3609. };
  3610. if (this.cssFontInfo.italicAngle) {
  3611. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  3612. }
  3613. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  3614. }
  3615. if (this.fontRegistry) {
  3616. this.fontRegistry.registerFont(this);
  3617. }
  3618. return nativeFontFace;
  3619. }
  3620. createFontFaceRule() {
  3621. if (!this.data || this.disableFontFace) {
  3622. return null;
  3623. }
  3624. const data = (0, _util.bytesToString)(this.data);
  3625. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  3626. let rule;
  3627. if (!this.cssFontInfo) {
  3628. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  3629. } else {
  3630. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  3631. if (this.cssFontInfo.italicAngle) {
  3632. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  3633. }
  3634. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  3635. }
  3636. if (this.fontRegistry) {
  3637. this.fontRegistry.registerFont(this, url);
  3638. }
  3639. return rule;
  3640. }
  3641. getPathGenerator(objs, character) {
  3642. if (this.compiledGlyphs[character] !== undefined) {
  3643. return this.compiledGlyphs[character];
  3644. }
  3645. let cmds;
  3646. try {
  3647. cmds = objs.get(this.loadedName + "_path_" + character);
  3648. } catch (ex) {
  3649. if (!this.ignoreErrors) {
  3650. throw ex;
  3651. }
  3652. this._onUnsupportedFeature({
  3653. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  3654. });
  3655. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  3656. return this.compiledGlyphs[character] = function (c, size) {};
  3657. }
  3658. if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
  3659. const jsBuf = [];
  3660. for (const current of cmds) {
  3661. const args = current.args !== undefined ? current.args.join(",") : "";
  3662. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  3663. }
  3664. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  3665. }
  3666. return this.compiledGlyphs[character] = function (c, size) {
  3667. for (const current of cmds) {
  3668. if (current.cmd === "scale") {
  3669. current.args = [size, -size];
  3670. }
  3671. c[current.cmd].apply(c, current.args);
  3672. }
  3673. };
  3674. }
  3675. }
  3676. exports.FontFaceObject = FontFaceObject;
  3677. /***/ }),
  3678. /* 8 */
  3679. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3680. Object.defineProperty(exports, "__esModule", ({
  3681. value: true
  3682. }));
  3683. exports.NodeStandardFontDataFactory = exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = void 0;
  3684. var _base_factory = __w_pdfjs_require__(5);
  3685. var _is_node = __w_pdfjs_require__(4);
  3686. var _util = __w_pdfjs_require__(2);
  3687. let NodeCanvasFactory = class {
  3688. constructor() {
  3689. (0, _util.unreachable)("Not implemented: NodeCanvasFactory");
  3690. }
  3691. };
  3692. exports.NodeCanvasFactory = NodeCanvasFactory;
  3693. let NodeCMapReaderFactory = class {
  3694. constructor() {
  3695. (0, _util.unreachable)("Not implemented: NodeCMapReaderFactory");
  3696. }
  3697. };
  3698. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  3699. let NodeStandardFontDataFactory = class {
  3700. constructor() {
  3701. (0, _util.unreachable)("Not implemented: NodeStandardFontDataFactory");
  3702. }
  3703. };
  3704. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  3705. if (_is_node.isNodeJS) {
  3706. const fetchData = function (url) {
  3707. return new Promise((resolve, reject) => {
  3708. const fs = require("fs");
  3709. fs.readFile(url, (error, data) => {
  3710. if (error || !data) {
  3711. reject(new Error(error));
  3712. return;
  3713. }
  3714. resolve(new Uint8Array(data));
  3715. });
  3716. });
  3717. };
  3718. exports.NodeCanvasFactory = NodeCanvasFactory = class extends _base_factory.BaseCanvasFactory {
  3719. _createCanvas(width, height) {
  3720. const Canvas = require("canvas");
  3721. return Canvas.createCanvas(width, height);
  3722. }
  3723. };
  3724. exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _base_factory.BaseCMapReaderFactory {
  3725. _fetchData(url, compressionType) {
  3726. return fetchData(url).then(data => {
  3727. return {
  3728. cMapData: data,
  3729. compressionType
  3730. };
  3731. });
  3732. }
  3733. };
  3734. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory = class extends _base_factory.BaseStandardFontDataFactory {
  3735. _fetchData(url) {
  3736. return fetchData(url);
  3737. }
  3738. };
  3739. }
  3740. /***/ }),
  3741. /* 9 */
  3742. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3743. Object.defineProperty(exports, "__esModule", ({
  3744. value: true
  3745. }));
  3746. exports.AnnotationStorage = void 0;
  3747. var _util = __w_pdfjs_require__(2);
  3748. class AnnotationStorage {
  3749. constructor() {
  3750. this._storage = new Map();
  3751. this._timeStamp = Date.now();
  3752. this._modified = false;
  3753. this.onSetModified = null;
  3754. this.onResetModified = null;
  3755. }
  3756. getValue(key, defaultValue) {
  3757. const value = this._storage.get(key);
  3758. if (value === undefined) {
  3759. return defaultValue;
  3760. }
  3761. return Object.assign(defaultValue, value);
  3762. }
  3763. setValue(key, value) {
  3764. const obj = this._storage.get(key);
  3765. let modified = false;
  3766. if (obj !== undefined) {
  3767. for (const [entry, val] of Object.entries(value)) {
  3768. if (obj[entry] !== val) {
  3769. modified = true;
  3770. obj[entry] = val;
  3771. }
  3772. }
  3773. } else {
  3774. modified = true;
  3775. this._storage.set(key, value);
  3776. }
  3777. if (modified) {
  3778. this._timeStamp = Date.now();
  3779. this._setModified();
  3780. }
  3781. }
  3782. getAll() {
  3783. return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
  3784. }
  3785. get size() {
  3786. return this._storage.size;
  3787. }
  3788. _setModified() {
  3789. if (!this._modified) {
  3790. this._modified = true;
  3791. if (typeof this.onSetModified === "function") {
  3792. this.onSetModified();
  3793. }
  3794. }
  3795. }
  3796. resetModified() {
  3797. if (this._modified) {
  3798. this._modified = false;
  3799. if (typeof this.onResetModified === "function") {
  3800. this.onResetModified();
  3801. }
  3802. }
  3803. }
  3804. get serializable() {
  3805. return this._storage.size > 0 ? this._storage : null;
  3806. }
  3807. get lastModified() {
  3808. return this._timeStamp.toString();
  3809. }
  3810. }
  3811. exports.AnnotationStorage = AnnotationStorage;
  3812. /***/ }),
  3813. /* 10 */
  3814. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3815. Object.defineProperty(exports, "__esModule", ({
  3816. value: true
  3817. }));
  3818. exports.CanvasGraphics = void 0;
  3819. var _util = __w_pdfjs_require__(2);
  3820. var _pattern_helper = __w_pdfjs_require__(11);
  3821. var _display_utils = __w_pdfjs_require__(1);
  3822. const MIN_FONT_SIZE = 16;
  3823. const MAX_FONT_SIZE = 100;
  3824. const MAX_GROUP_SIZE = 4096;
  3825. const MAX_CACHED_CANVAS_PATTERNS = 2;
  3826. const EXECUTION_TIME = 15;
  3827. const EXECUTION_STEPS = 10;
  3828. const COMPILE_TYPE3_GLYPHS = true;
  3829. const MAX_SIZE_TO_COMPILE = 1000;
  3830. const FULL_CHUNK_HEIGHT = 16;
  3831. const LINEWIDTH_SCALE_FACTOR = 1.000001;
  3832. function addContextCurrentTransform(ctx) {
  3833. if (ctx.mozCurrentTransform) {
  3834. return;
  3835. }
  3836. ctx._originalSave = ctx.save;
  3837. ctx._originalRestore = ctx.restore;
  3838. ctx._originalRotate = ctx.rotate;
  3839. ctx._originalScale = ctx.scale;
  3840. ctx._originalTranslate = ctx.translate;
  3841. ctx._originalTransform = ctx.transform;
  3842. ctx._originalSetTransform = ctx.setTransform;
  3843. ctx._originalResetTransform = ctx.resetTransform;
  3844. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  3845. ctx._transformStack = [];
  3846. try {
  3847. const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth");
  3848. ctx._setLineWidth = desc.set;
  3849. ctx._getLineWidth = desc.get;
  3850. Object.defineProperty(ctx, "lineWidth", {
  3851. set: function setLineWidth(width) {
  3852. this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR);
  3853. },
  3854. get: function getLineWidth() {
  3855. return this._getLineWidth();
  3856. }
  3857. });
  3858. } catch (_) {}
  3859. Object.defineProperty(ctx, "mozCurrentTransform", {
  3860. get: function getCurrentTransform() {
  3861. return this._transformMatrix;
  3862. }
  3863. });
  3864. Object.defineProperty(ctx, "mozCurrentTransformInverse", {
  3865. get: function getCurrentTransformInverse() {
  3866. const [a, b, c, d, e, f] = this._transformMatrix;
  3867. const ad_bc = a * d - b * c;
  3868. const bc_ad = b * c - a * d;
  3869. 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];
  3870. }
  3871. });
  3872. ctx.save = function ctxSave() {
  3873. const old = this._transformMatrix;
  3874. this._transformStack.push(old);
  3875. this._transformMatrix = old.slice(0, 6);
  3876. this._originalSave();
  3877. };
  3878. ctx.restore = function ctxRestore() {
  3879. const prev = this._transformStack.pop();
  3880. if (prev) {
  3881. this._transformMatrix = prev;
  3882. this._originalRestore();
  3883. }
  3884. };
  3885. ctx.translate = function ctxTranslate(x, y) {
  3886. const m = this._transformMatrix;
  3887. m[4] = m[0] * x + m[2] * y + m[4];
  3888. m[5] = m[1] * x + m[3] * y + m[5];
  3889. this._originalTranslate(x, y);
  3890. };
  3891. ctx.scale = function ctxScale(x, y) {
  3892. const m = this._transformMatrix;
  3893. m[0] *= x;
  3894. m[1] *= x;
  3895. m[2] *= y;
  3896. m[3] *= y;
  3897. this._originalScale(x, y);
  3898. };
  3899. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3900. const m = this._transformMatrix;
  3901. 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]];
  3902. ctx._originalTransform(a, b, c, d, e, f);
  3903. };
  3904. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3905. this._transformMatrix = [a, b, c, d, e, f];
  3906. ctx._originalSetTransform(a, b, c, d, e, f);
  3907. };
  3908. ctx.resetTransform = function ctxResetTransform() {
  3909. this._transformMatrix = [1, 0, 0, 1, 0, 0];
  3910. ctx._originalResetTransform();
  3911. };
  3912. ctx.rotate = function ctxRotate(angle) {
  3913. const cosValue = Math.cos(angle);
  3914. const sinValue = Math.sin(angle);
  3915. const m = this._transformMatrix;
  3916. 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]];
  3917. this._originalRotate(angle);
  3918. };
  3919. }
  3920. class CachedCanvases {
  3921. constructor(canvasFactory) {
  3922. this.canvasFactory = canvasFactory;
  3923. this.cache = Object.create(null);
  3924. }
  3925. getCanvas(id, width, height, trackTransform) {
  3926. let canvasEntry;
  3927. if (this.cache[id] !== undefined) {
  3928. canvasEntry = this.cache[id];
  3929. this.canvasFactory.reset(canvasEntry, width, height);
  3930. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3931. } else {
  3932. canvasEntry = this.canvasFactory.create(width, height);
  3933. this.cache[id] = canvasEntry;
  3934. }
  3935. if (trackTransform) {
  3936. addContextCurrentTransform(canvasEntry.context);
  3937. }
  3938. return canvasEntry;
  3939. }
  3940. clear() {
  3941. for (const id in this.cache) {
  3942. const canvasEntry = this.cache[id];
  3943. this.canvasFactory.destroy(canvasEntry);
  3944. delete this.cache[id];
  3945. }
  3946. }
  3947. }
  3948. class LRUCache {
  3949. constructor(maxSize = 0) {
  3950. this._cache = new Map();
  3951. this._maxSize = maxSize;
  3952. }
  3953. has(key) {
  3954. return this._cache.has(key);
  3955. }
  3956. get(key) {
  3957. if (this._cache.has(key)) {
  3958. const value = this._cache.get(key);
  3959. this._cache.delete(key);
  3960. this._cache.set(key, value);
  3961. }
  3962. return this._cache.get(key);
  3963. }
  3964. set(key, value) {
  3965. if (this._maxSize <= 0) {
  3966. return;
  3967. }
  3968. if (this._cache.size + 1 > this._maxSize) {
  3969. this._cache.delete(this._cache.keys().next().value);
  3970. }
  3971. this._cache.set(key, value);
  3972. }
  3973. clear() {
  3974. this._cache.clear();
  3975. }
  3976. }
  3977. function compileType3Glyph(imgData) {
  3978. const POINT_TO_PROCESS_LIMIT = 1000;
  3979. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3980. const width = imgData.width,
  3981. height = imgData.height,
  3982. width1 = width + 1;
  3983. let i, ii, j, j0;
  3984. const points = new Uint8Array(width1 * (height + 1));
  3985. const lineSize = width + 7 & ~7,
  3986. data0 = imgData.data;
  3987. const data = new Uint8Array(lineSize * height);
  3988. let pos = 0;
  3989. for (i = 0, ii = data0.length; i < ii; i++) {
  3990. const elem = data0[i];
  3991. let mask = 128;
  3992. while (mask > 0) {
  3993. data[pos++] = elem & mask ? 0 : 255;
  3994. mask >>= 1;
  3995. }
  3996. }
  3997. let count = 0;
  3998. pos = 0;
  3999. if (data[pos] !== 0) {
  4000. points[0] = 1;
  4001. ++count;
  4002. }
  4003. for (j = 1; j < width; j++) {
  4004. if (data[pos] !== data[pos + 1]) {
  4005. points[j] = data[pos] ? 2 : 1;
  4006. ++count;
  4007. }
  4008. pos++;
  4009. }
  4010. if (data[pos] !== 0) {
  4011. points[j] = 2;
  4012. ++count;
  4013. }
  4014. for (i = 1; i < height; i++) {
  4015. pos = i * lineSize;
  4016. j0 = i * width1;
  4017. if (data[pos - lineSize] !== data[pos]) {
  4018. points[j0] = data[pos] ? 1 : 8;
  4019. ++count;
  4020. }
  4021. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  4022. for (j = 1; j < width; j++) {
  4023. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  4024. if (POINT_TYPES[sum]) {
  4025. points[j0 + j] = POINT_TYPES[sum];
  4026. ++count;
  4027. }
  4028. pos++;
  4029. }
  4030. if (data[pos - lineSize] !== data[pos]) {
  4031. points[j0 + j] = data[pos] ? 2 : 4;
  4032. ++count;
  4033. }
  4034. if (count > POINT_TO_PROCESS_LIMIT) {
  4035. return null;
  4036. }
  4037. }
  4038. pos = lineSize * (height - 1);
  4039. j0 = i * width1;
  4040. if (data[pos] !== 0) {
  4041. points[j0] = 8;
  4042. ++count;
  4043. }
  4044. for (j = 1; j < width; j++) {
  4045. if (data[pos] !== data[pos + 1]) {
  4046. points[j0 + j] = data[pos] ? 4 : 8;
  4047. ++count;
  4048. }
  4049. pos++;
  4050. }
  4051. if (data[pos] !== 0) {
  4052. points[j0 + j] = 4;
  4053. ++count;
  4054. }
  4055. if (count > POINT_TO_PROCESS_LIMIT) {
  4056. return null;
  4057. }
  4058. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  4059. const outlines = [];
  4060. for (i = 0; count && i <= height; i++) {
  4061. let p = i * width1;
  4062. const end = p + width;
  4063. while (p < end && !points[p]) {
  4064. p++;
  4065. }
  4066. if (p === end) {
  4067. continue;
  4068. }
  4069. const coords = [p % width1, i];
  4070. const p0 = p;
  4071. let type = points[p];
  4072. do {
  4073. const step = steps[type];
  4074. do {
  4075. p += step;
  4076. } while (!points[p]);
  4077. const pp = points[p];
  4078. if (pp !== 5 && pp !== 10) {
  4079. type = pp;
  4080. points[p] = 0;
  4081. } else {
  4082. type = pp & 0x33 * type >> 4;
  4083. points[p] &= type >> 2 | type << 2;
  4084. }
  4085. coords.push(p % width1, p / width1 | 0);
  4086. if (!points[p]) {
  4087. --count;
  4088. }
  4089. } while (p0 !== p);
  4090. outlines.push(coords);
  4091. --i;
  4092. }
  4093. const drawOutline = function (c) {
  4094. c.save();
  4095. c.scale(1 / width, -1 / height);
  4096. c.translate(0, -height);
  4097. c.beginPath();
  4098. for (let k = 0, kk = outlines.length; k < kk; k++) {
  4099. const o = outlines[k];
  4100. c.moveTo(o[0], o[1]);
  4101. for (let l = 2, ll = o.length; l < ll; l += 2) {
  4102. c.lineTo(o[l], o[l + 1]);
  4103. }
  4104. }
  4105. c.fill();
  4106. c.beginPath();
  4107. c.restore();
  4108. };
  4109. return drawOutline;
  4110. }
  4111. class CanvasExtraState {
  4112. constructor() {
  4113. this.alphaIsShape = false;
  4114. this.fontSize = 0;
  4115. this.fontSizeScale = 1;
  4116. this.textMatrix = _util.IDENTITY_MATRIX;
  4117. this.textMatrixScale = 1;
  4118. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  4119. this.leading = 0;
  4120. this.x = 0;
  4121. this.y = 0;
  4122. this.lineX = 0;
  4123. this.lineY = 0;
  4124. this.charSpacing = 0;
  4125. this.wordSpacing = 0;
  4126. this.textHScale = 1;
  4127. this.textRenderingMode = _util.TextRenderingMode.FILL;
  4128. this.textRise = 0;
  4129. this.fillColor = "#000000";
  4130. this.strokeColor = "#000000";
  4131. this.patternFill = false;
  4132. this.fillAlpha = 1;
  4133. this.strokeAlpha = 1;
  4134. this.lineWidth = 1;
  4135. this.activeSMask = null;
  4136. this.resumeSMaskCtx = null;
  4137. this.transferMaps = null;
  4138. }
  4139. clone() {
  4140. return Object.create(this);
  4141. }
  4142. setCurrentPoint(x, y) {
  4143. this.x = x;
  4144. this.y = y;
  4145. }
  4146. }
  4147. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  4148. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  4149. ctx.putImageData(imgData, 0, 0);
  4150. return;
  4151. }
  4152. const height = imgData.height,
  4153. width = imgData.width;
  4154. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  4155. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  4156. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  4157. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  4158. let srcPos = 0,
  4159. destPos;
  4160. const src = imgData.data;
  4161. const dest = chunkImgData.data;
  4162. let i, j, thisChunkHeight, elemsInThisChunk;
  4163. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  4164. if (transferMaps) {
  4165. switch (transferMaps.length) {
  4166. case 1:
  4167. transferMapRed = transferMaps[0];
  4168. transferMapGreen = transferMaps[0];
  4169. transferMapBlue = transferMaps[0];
  4170. transferMapGray = transferMaps[0];
  4171. break;
  4172. case 4:
  4173. transferMapRed = transferMaps[0];
  4174. transferMapGreen = transferMaps[1];
  4175. transferMapBlue = transferMaps[2];
  4176. transferMapGray = transferMaps[3];
  4177. break;
  4178. }
  4179. }
  4180. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  4181. const srcLength = src.byteLength;
  4182. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  4183. const dest32DataLength = dest32.length;
  4184. const fullSrcDiff = width + 7 >> 3;
  4185. let white = 0xffffffff;
  4186. let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff;
  4187. if (transferMapGray) {
  4188. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  4189. [white, black] = [black, white];
  4190. }
  4191. }
  4192. for (i = 0; i < totalChunks; i++) {
  4193. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  4194. destPos = 0;
  4195. for (j = 0; j < thisChunkHeight; j++) {
  4196. const srcDiff = srcLength - srcPos;
  4197. let k = 0;
  4198. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  4199. const kEndUnrolled = kEnd & ~7;
  4200. let mask = 0;
  4201. let srcByte = 0;
  4202. for (; k < kEndUnrolled; k += 8) {
  4203. srcByte = src[srcPos++];
  4204. dest32[destPos++] = srcByte & 128 ? white : black;
  4205. dest32[destPos++] = srcByte & 64 ? white : black;
  4206. dest32[destPos++] = srcByte & 32 ? white : black;
  4207. dest32[destPos++] = srcByte & 16 ? white : black;
  4208. dest32[destPos++] = srcByte & 8 ? white : black;
  4209. dest32[destPos++] = srcByte & 4 ? white : black;
  4210. dest32[destPos++] = srcByte & 2 ? white : black;
  4211. dest32[destPos++] = srcByte & 1 ? white : black;
  4212. }
  4213. for (; k < kEnd; k++) {
  4214. if (mask === 0) {
  4215. srcByte = src[srcPos++];
  4216. mask = 128;
  4217. }
  4218. dest32[destPos++] = srcByte & mask ? white : black;
  4219. mask >>= 1;
  4220. }
  4221. }
  4222. while (destPos < dest32DataLength) {
  4223. dest32[destPos++] = 0;
  4224. }
  4225. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4226. }
  4227. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  4228. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  4229. j = 0;
  4230. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  4231. for (i = 0; i < fullChunks; i++) {
  4232. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  4233. srcPos += elemsInThisChunk;
  4234. if (hasTransferMaps) {
  4235. for (let k = 0; k < elemsInThisChunk; k += 4) {
  4236. if (transferMapRed) {
  4237. dest[k + 0] = transferMapRed[dest[k + 0]];
  4238. }
  4239. if (transferMapGreen) {
  4240. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4241. }
  4242. if (transferMapBlue) {
  4243. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4244. }
  4245. }
  4246. }
  4247. ctx.putImageData(chunkImgData, 0, j);
  4248. j += FULL_CHUNK_HEIGHT;
  4249. }
  4250. if (i < totalChunks) {
  4251. elemsInThisChunk = width * partialChunkHeight * 4;
  4252. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  4253. if (hasTransferMaps) {
  4254. for (let k = 0; k < elemsInThisChunk; k += 4) {
  4255. if (transferMapRed) {
  4256. dest[k + 0] = transferMapRed[dest[k + 0]];
  4257. }
  4258. if (transferMapGreen) {
  4259. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4260. }
  4261. if (transferMapBlue) {
  4262. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4263. }
  4264. }
  4265. }
  4266. ctx.putImageData(chunkImgData, 0, j);
  4267. }
  4268. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  4269. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  4270. thisChunkHeight = FULL_CHUNK_HEIGHT;
  4271. elemsInThisChunk = width * thisChunkHeight;
  4272. for (i = 0; i < totalChunks; i++) {
  4273. if (i >= fullChunks) {
  4274. thisChunkHeight = partialChunkHeight;
  4275. elemsInThisChunk = width * thisChunkHeight;
  4276. }
  4277. destPos = 0;
  4278. for (j = elemsInThisChunk; j--;) {
  4279. dest[destPos++] = src[srcPos++];
  4280. dest[destPos++] = src[srcPos++];
  4281. dest[destPos++] = src[srcPos++];
  4282. dest[destPos++] = 255;
  4283. }
  4284. if (hasTransferMaps) {
  4285. for (let k = 0; k < destPos; k += 4) {
  4286. if (transferMapRed) {
  4287. dest[k + 0] = transferMapRed[dest[k + 0]];
  4288. }
  4289. if (transferMapGreen) {
  4290. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4291. }
  4292. if (transferMapBlue) {
  4293. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4294. }
  4295. }
  4296. }
  4297. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4298. }
  4299. } else {
  4300. throw new Error(`bad image kind: ${imgData.kind}`);
  4301. }
  4302. }
  4303. function putBinaryImageMask(ctx, imgData) {
  4304. const height = imgData.height,
  4305. width = imgData.width;
  4306. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  4307. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  4308. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  4309. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  4310. let srcPos = 0;
  4311. const src = imgData.data;
  4312. const dest = chunkImgData.data;
  4313. for (let i = 0; i < totalChunks; i++) {
  4314. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  4315. let destPos = 3;
  4316. for (let j = 0; j < thisChunkHeight; j++) {
  4317. let elem,
  4318. mask = 0;
  4319. for (let k = 0; k < width; k++) {
  4320. if (!mask) {
  4321. elem = src[srcPos++];
  4322. mask = 128;
  4323. }
  4324. dest[destPos] = elem & mask ? 0 : 255;
  4325. destPos += 4;
  4326. mask >>= 1;
  4327. }
  4328. }
  4329. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4330. }
  4331. }
  4332. function copyCtxState(sourceCtx, destCtx) {
  4333. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  4334. for (let i = 0, ii = properties.length; i < ii; i++) {
  4335. const property = properties[i];
  4336. if (sourceCtx[property] !== undefined) {
  4337. destCtx[property] = sourceCtx[property];
  4338. }
  4339. }
  4340. if (sourceCtx.setLineDash !== undefined) {
  4341. destCtx.setLineDash(sourceCtx.getLineDash());
  4342. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  4343. }
  4344. }
  4345. function resetCtxToDefault(ctx) {
  4346. ctx.strokeStyle = "#000000";
  4347. ctx.fillStyle = "#000000";
  4348. ctx.fillRule = "nonzero";
  4349. ctx.globalAlpha = 1;
  4350. ctx.lineWidth = 1;
  4351. ctx.lineCap = "butt";
  4352. ctx.lineJoin = "miter";
  4353. ctx.miterLimit = 10;
  4354. ctx.globalCompositeOperation = "source-over";
  4355. ctx.font = "10px sans-serif";
  4356. if (ctx.setLineDash !== undefined) {
  4357. ctx.setLineDash([]);
  4358. ctx.lineDashOffset = 0;
  4359. }
  4360. }
  4361. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  4362. const length = bytes.length;
  4363. for (let i = 3; i < length; i += 4) {
  4364. const alpha = bytes[i];
  4365. if (alpha === 0) {
  4366. bytes[i - 3] = r0;
  4367. bytes[i - 2] = g0;
  4368. bytes[i - 1] = b0;
  4369. } else if (alpha < 255) {
  4370. const alpha_ = 255 - alpha;
  4371. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  4372. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  4373. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  4374. }
  4375. }
  4376. }
  4377. function composeSMaskAlpha(maskData, layerData, transferMap) {
  4378. const length = maskData.length;
  4379. const scale = 1 / 255;
  4380. for (let i = 3; i < length; i += 4) {
  4381. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  4382. layerData[i] = layerData[i] * alpha * scale | 0;
  4383. }
  4384. }
  4385. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  4386. const length = maskData.length;
  4387. for (let i = 3; i < length; i += 4) {
  4388. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  4389. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  4390. }
  4391. }
  4392. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  4393. const hasBackdrop = !!backdrop;
  4394. const r0 = hasBackdrop ? backdrop[0] : 0;
  4395. const g0 = hasBackdrop ? backdrop[1] : 0;
  4396. const b0 = hasBackdrop ? backdrop[2] : 0;
  4397. let composeFn;
  4398. if (subtype === "Luminosity") {
  4399. composeFn = composeSMaskLuminosity;
  4400. } else {
  4401. composeFn = composeSMaskAlpha;
  4402. }
  4403. const PIXELS_TO_PROCESS = 1048576;
  4404. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  4405. for (let row = 0; row < height; row += chunkSize) {
  4406. const chunkHeight = Math.min(chunkSize, height - row);
  4407. const maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  4408. const layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  4409. if (hasBackdrop) {
  4410. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  4411. }
  4412. composeFn(maskData.data, layerData.data, transferMap);
  4413. maskCtx.putImageData(layerData, 0, row);
  4414. }
  4415. }
  4416. function composeSMask(ctx, smask, layerCtx) {
  4417. const mask = smask.canvas;
  4418. const maskCtx = smask.context;
  4419. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  4420. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, smask.backdrop, smask.transferMap);
  4421. ctx.drawImage(mask, 0, 0);
  4422. }
  4423. function getImageSmoothingEnabled(transform, interpolate) {
  4424. const scale = _util.Util.singularValueDecompose2dScale(transform);
  4425. scale[0] = Math.fround(scale[0]);
  4426. scale[1] = Math.fround(scale[1]);
  4427. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  4428. if (interpolate !== undefined) {
  4429. return interpolate;
  4430. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  4431. return true;
  4432. }
  4433. return false;
  4434. }
  4435. const LINE_CAP_STYLES = ["butt", "round", "square"];
  4436. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  4437. const NORMAL_CLIP = {};
  4438. const EO_CLIP = {};
  4439. class CanvasGraphics {
  4440. constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig) {
  4441. this.ctx = canvasCtx;
  4442. this.current = new CanvasExtraState();
  4443. this.stateStack = [];
  4444. this.pendingClip = null;
  4445. this.pendingEOFill = false;
  4446. this.res = null;
  4447. this.xobjs = null;
  4448. this.commonObjs = commonObjs;
  4449. this.objs = objs;
  4450. this.canvasFactory = canvasFactory;
  4451. this.imageLayer = imageLayer;
  4452. this.groupStack = [];
  4453. this.processingType3 = null;
  4454. this.baseTransform = null;
  4455. this.baseTransformStack = [];
  4456. this.groupLevel = 0;
  4457. this.smaskStack = [];
  4458. this.smaskCounter = 0;
  4459. this.tempSMask = null;
  4460. this.contentVisible = true;
  4461. this.markedContentStack = [];
  4462. this.optionalContentConfig = optionalContentConfig;
  4463. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  4464. this.cachedCanvasPatterns = new LRUCache(MAX_CACHED_CANVAS_PATTERNS);
  4465. this.cachedPatterns = new Map();
  4466. if (canvasCtx) {
  4467. addContextCurrentTransform(canvasCtx);
  4468. }
  4469. this._cachedGetSinglePixelWidth = null;
  4470. }
  4471. beginDrawing({
  4472. transform,
  4473. viewport,
  4474. transparency = false,
  4475. background = null
  4476. }) {
  4477. const width = this.ctx.canvas.width;
  4478. const height = this.ctx.canvas.height;
  4479. this.ctx.save();
  4480. this.ctx.fillStyle = background || "rgb(255, 255, 255)";
  4481. this.ctx.fillRect(0, 0, width, height);
  4482. this.ctx.restore();
  4483. if (transparency) {
  4484. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
  4485. this.compositeCtx = this.ctx;
  4486. this.transparentCanvas = transparentCanvas.canvas;
  4487. this.ctx = transparentCanvas.context;
  4488. this.ctx.save();
  4489. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  4490. }
  4491. this.ctx.save();
  4492. resetCtxToDefault(this.ctx);
  4493. if (transform) {
  4494. this.ctx.transform.apply(this.ctx, transform);
  4495. }
  4496. this.ctx.transform.apply(this.ctx, viewport.transform);
  4497. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  4498. this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]);
  4499. if (this.imageLayer) {
  4500. this.imageLayer.beginLayout();
  4501. }
  4502. }
  4503. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  4504. const argsArray = operatorList.argsArray;
  4505. const fnArray = operatorList.fnArray;
  4506. let i = executionStartIdx || 0;
  4507. const argsArrayLen = argsArray.length;
  4508. if (argsArrayLen === i) {
  4509. return i;
  4510. }
  4511. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  4512. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  4513. let steps = 0;
  4514. const commonObjs = this.commonObjs;
  4515. const objs = this.objs;
  4516. let fnId;
  4517. while (true) {
  4518. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  4519. stepper.breakIt(i, continueCallback);
  4520. return i;
  4521. }
  4522. fnId = fnArray[i];
  4523. if (fnId !== _util.OPS.dependency) {
  4524. this[fnId].apply(this, argsArray[i]);
  4525. } else {
  4526. for (const depObjId of argsArray[i]) {
  4527. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  4528. if (!objsPool.has(depObjId)) {
  4529. objsPool.get(depObjId, continueCallback);
  4530. return i;
  4531. }
  4532. }
  4533. }
  4534. i++;
  4535. if (i === argsArrayLen) {
  4536. return i;
  4537. }
  4538. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  4539. if (Date.now() > endTime) {
  4540. continueCallback();
  4541. return i;
  4542. }
  4543. steps = 0;
  4544. }
  4545. }
  4546. }
  4547. endDrawing() {
  4548. while (this.stateStack.length || this.current.activeSMask !== null) {
  4549. this.restore();
  4550. }
  4551. this.ctx.restore();
  4552. if (this.transparentCanvas) {
  4553. this.ctx = this.compositeCtx;
  4554. this.ctx.save();
  4555. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  4556. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  4557. this.ctx.restore();
  4558. this.transparentCanvas = null;
  4559. }
  4560. this.cachedCanvases.clear();
  4561. this.cachedCanvasPatterns.clear();
  4562. this.cachedPatterns.clear();
  4563. if (this.imageLayer) {
  4564. this.imageLayer.endLayout();
  4565. }
  4566. }
  4567. _scaleImage(img, inverseTransform) {
  4568. const width = img.width;
  4569. const height = img.height;
  4570. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  4571. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  4572. let paintWidth = width,
  4573. paintHeight = height;
  4574. let tmpCanvasId = "prescale1";
  4575. let tmpCanvas, tmpCtx;
  4576. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  4577. let newWidth = paintWidth,
  4578. newHeight = paintHeight;
  4579. if (widthScale > 2 && paintWidth > 1) {
  4580. newWidth = Math.ceil(paintWidth / 2);
  4581. widthScale /= paintWidth / newWidth;
  4582. }
  4583. if (heightScale > 2 && paintHeight > 1) {
  4584. newHeight = Math.ceil(paintHeight / 2);
  4585. heightScale /= paintHeight / newHeight;
  4586. }
  4587. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4588. tmpCtx = tmpCanvas.context;
  4589. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4590. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  4591. img = tmpCanvas.canvas;
  4592. paintWidth = newWidth;
  4593. paintHeight = newHeight;
  4594. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  4595. }
  4596. return {
  4597. img,
  4598. paintWidth,
  4599. paintHeight
  4600. };
  4601. }
  4602. _createMaskCanvas(img) {
  4603. const ctx = this.ctx;
  4604. const width = img.width,
  4605. height = img.height;
  4606. const fillColor = this.current.fillColor;
  4607. const isPatternFill = this.current.patternFill;
  4608. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  4609. const maskCtx = maskCanvas.context;
  4610. putBinaryImageMask(maskCtx, img);
  4611. const objToCanvas = ctx.mozCurrentTransform;
  4612. let maskToCanvas = _util.Util.transform(objToCanvas, [1 / width, 0, 0, -1 / height, 0, 0]);
  4613. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  4614. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  4615. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  4616. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  4617. const drawnWidth = Math.ceil(rect[2] - rect[0]);
  4618. const drawnHeight = Math.ceil(rect[3] - rect[1]);
  4619. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight, true);
  4620. const fillCtx = fillCanvas.context;
  4621. const offsetX = Math.min(cord1[0], cord2[0]);
  4622. const offsetY = Math.min(cord1[1], cord2[1]);
  4623. fillCtx.translate(-offsetX, -offsetY);
  4624. fillCtx.transform.apply(fillCtx, maskToCanvas);
  4625. const scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse);
  4626. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(fillCtx.mozCurrentTransform, img.interpolate);
  4627. fillCtx.drawImage(scaled.img, 0, 0, scaled.img.width, scaled.img.height, 0, 0, width, height);
  4628. fillCtx.globalCompositeOperation = "source-in";
  4629. const inverse = _util.Util.transform(fillCtx.mozCurrentTransformInverse, [1, 0, 0, 1, -offsetX, -offsetY]);
  4630. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, false) : fillColor;
  4631. fillCtx.fillRect(0, 0, width, height);
  4632. return {
  4633. canvas: fillCanvas.canvas,
  4634. offsetX: Math.round(offsetX),
  4635. offsetY: Math.round(offsetY)
  4636. };
  4637. }
  4638. setLineWidth(width) {
  4639. this.current.lineWidth = width;
  4640. this.ctx.lineWidth = width;
  4641. }
  4642. setLineCap(style) {
  4643. this.ctx.lineCap = LINE_CAP_STYLES[style];
  4644. }
  4645. setLineJoin(style) {
  4646. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  4647. }
  4648. setMiterLimit(limit) {
  4649. this.ctx.miterLimit = limit;
  4650. }
  4651. setDash(dashArray, dashPhase) {
  4652. const ctx = this.ctx;
  4653. if (ctx.setLineDash !== undefined) {
  4654. ctx.setLineDash(dashArray);
  4655. ctx.lineDashOffset = dashPhase;
  4656. }
  4657. }
  4658. setRenderingIntent(intent) {}
  4659. setFlatness(flatness) {}
  4660. setGState(states) {
  4661. for (let i = 0, ii = states.length; i < ii; i++) {
  4662. const state = states[i];
  4663. const key = state[0];
  4664. const value = state[1];
  4665. switch (key) {
  4666. case "LW":
  4667. this.setLineWidth(value);
  4668. break;
  4669. case "LC":
  4670. this.setLineCap(value);
  4671. break;
  4672. case "LJ":
  4673. this.setLineJoin(value);
  4674. break;
  4675. case "ML":
  4676. this.setMiterLimit(value);
  4677. break;
  4678. case "D":
  4679. this.setDash(value[0], value[1]);
  4680. break;
  4681. case "RI":
  4682. this.setRenderingIntent(value);
  4683. break;
  4684. case "FL":
  4685. this.setFlatness(value);
  4686. break;
  4687. case "Font":
  4688. this.setFont(value[0], value[1]);
  4689. break;
  4690. case "CA":
  4691. this.current.strokeAlpha = state[1];
  4692. break;
  4693. case "ca":
  4694. this.current.fillAlpha = state[1];
  4695. this.ctx.globalAlpha = state[1];
  4696. break;
  4697. case "BM":
  4698. this.ctx.globalCompositeOperation = value;
  4699. break;
  4700. case "SMask":
  4701. if (this.current.activeSMask) {
  4702. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  4703. this.suspendSMaskGroup();
  4704. } else {
  4705. this.endSMaskGroup();
  4706. }
  4707. }
  4708. this.current.activeSMask = value ? this.tempSMask : null;
  4709. if (this.current.activeSMask) {
  4710. this.beginSMaskGroup();
  4711. }
  4712. this.tempSMask = null;
  4713. break;
  4714. case "TR":
  4715. this.current.transferMaps = value;
  4716. }
  4717. }
  4718. }
  4719. beginSMaskGroup() {
  4720. const activeSMask = this.current.activeSMask;
  4721. const drawnWidth = activeSMask.canvas.width;
  4722. const drawnHeight = activeSMask.canvas.height;
  4723. const cacheId = "smaskGroupAt" + this.groupLevel;
  4724. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  4725. const currentCtx = this.ctx;
  4726. const currentTransform = currentCtx.mozCurrentTransform;
  4727. this.ctx.save();
  4728. const groupCtx = scratchCanvas.context;
  4729. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  4730. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  4731. groupCtx.transform.apply(groupCtx, currentTransform);
  4732. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  4733. copyCtxState(currentCtx, groupCtx);
  4734. this.ctx = groupCtx;
  4735. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  4736. this.groupStack.push(currentCtx);
  4737. this.groupLevel++;
  4738. }
  4739. suspendSMaskGroup() {
  4740. const groupCtx = this.ctx;
  4741. this.groupLevel--;
  4742. this.ctx = this.groupStack.pop();
  4743. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4744. this.ctx.restore();
  4745. this.ctx.save();
  4746. copyCtxState(groupCtx, this.ctx);
  4747. this.current.resumeSMaskCtx = groupCtx;
  4748. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  4749. this.ctx.transform.apply(this.ctx, deltaTransform);
  4750. groupCtx.save();
  4751. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  4752. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  4753. groupCtx.restore();
  4754. }
  4755. resumeSMaskGroup() {
  4756. const groupCtx = this.current.resumeSMaskCtx;
  4757. const currentCtx = this.ctx;
  4758. this.ctx = groupCtx;
  4759. this.groupStack.push(currentCtx);
  4760. this.groupLevel++;
  4761. }
  4762. endSMaskGroup() {
  4763. const groupCtx = this.ctx;
  4764. this.groupLevel--;
  4765. this.ctx = this.groupStack.pop();
  4766. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4767. this.ctx.restore();
  4768. copyCtxState(groupCtx, this.ctx);
  4769. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  4770. this.ctx.transform.apply(this.ctx, deltaTransform);
  4771. }
  4772. save() {
  4773. this.ctx.save();
  4774. const old = this.current;
  4775. this.stateStack.push(old);
  4776. this.current = old.clone();
  4777. this.current.resumeSMaskCtx = null;
  4778. }
  4779. restore() {
  4780. if (this.current.resumeSMaskCtx) {
  4781. this.resumeSMaskGroup();
  4782. }
  4783. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  4784. this.endSMaskGroup();
  4785. }
  4786. if (this.stateStack.length !== 0) {
  4787. this.current = this.stateStack.pop();
  4788. this.ctx.restore();
  4789. this.pendingClip = null;
  4790. this._cachedGetSinglePixelWidth = null;
  4791. } else {
  4792. this.current.activeSMask = null;
  4793. }
  4794. }
  4795. transform(a, b, c, d, e, f) {
  4796. this.ctx.transform(a, b, c, d, e, f);
  4797. this._cachedGetSinglePixelWidth = null;
  4798. }
  4799. constructPath(ops, args) {
  4800. const ctx = this.ctx;
  4801. const current = this.current;
  4802. let x = current.x,
  4803. y = current.y;
  4804. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  4805. switch (ops[i] | 0) {
  4806. case _util.OPS.rectangle:
  4807. x = args[j++];
  4808. y = args[j++];
  4809. const width = args[j++];
  4810. const height = args[j++];
  4811. const xw = x + width;
  4812. const yh = y + height;
  4813. ctx.moveTo(x, y);
  4814. if (width === 0 || height === 0) {
  4815. ctx.lineTo(xw, yh);
  4816. } else {
  4817. ctx.lineTo(xw, y);
  4818. ctx.lineTo(xw, yh);
  4819. ctx.lineTo(x, yh);
  4820. }
  4821. ctx.closePath();
  4822. break;
  4823. case _util.OPS.moveTo:
  4824. x = args[j++];
  4825. y = args[j++];
  4826. ctx.moveTo(x, y);
  4827. break;
  4828. case _util.OPS.lineTo:
  4829. x = args[j++];
  4830. y = args[j++];
  4831. ctx.lineTo(x, y);
  4832. break;
  4833. case _util.OPS.curveTo:
  4834. x = args[j + 4];
  4835. y = args[j + 5];
  4836. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  4837. j += 6;
  4838. break;
  4839. case _util.OPS.curveTo2:
  4840. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  4841. x = args[j + 2];
  4842. y = args[j + 3];
  4843. j += 4;
  4844. break;
  4845. case _util.OPS.curveTo3:
  4846. x = args[j + 2];
  4847. y = args[j + 3];
  4848. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  4849. j += 4;
  4850. break;
  4851. case _util.OPS.closePath:
  4852. ctx.closePath();
  4853. break;
  4854. }
  4855. }
  4856. current.setCurrentPoint(x, y);
  4857. }
  4858. closePath() {
  4859. this.ctx.closePath();
  4860. }
  4861. stroke(consumePath) {
  4862. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  4863. const ctx = this.ctx;
  4864. const strokeColor = this.current.strokeColor;
  4865. ctx.globalAlpha = this.current.strokeAlpha;
  4866. if (this.contentVisible) {
  4867. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  4868. const lineWidth = this.getSinglePixelWidth();
  4869. ctx.save();
  4870. ctx.strokeStyle = strokeColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse);
  4871. ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
  4872. ctx.stroke();
  4873. ctx.restore();
  4874. } else {
  4875. const lineWidth = this.getSinglePixelWidth();
  4876. if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) {
  4877. ctx.save();
  4878. ctx.resetTransform();
  4879. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  4880. ctx.stroke();
  4881. ctx.restore();
  4882. } else {
  4883. ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
  4884. ctx.stroke();
  4885. }
  4886. }
  4887. }
  4888. if (consumePath) {
  4889. this.consumePath();
  4890. }
  4891. ctx.globalAlpha = this.current.fillAlpha;
  4892. }
  4893. closeStroke() {
  4894. this.closePath();
  4895. this.stroke();
  4896. }
  4897. fill(consumePath) {
  4898. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  4899. const ctx = this.ctx;
  4900. const fillColor = this.current.fillColor;
  4901. const isPatternFill = this.current.patternFill;
  4902. let needRestore = false;
  4903. if (isPatternFill) {
  4904. ctx.save();
  4905. ctx.fillStyle = fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse);
  4906. needRestore = true;
  4907. }
  4908. if (this.contentVisible) {
  4909. if (this.pendingEOFill) {
  4910. ctx.fill("evenodd");
  4911. this.pendingEOFill = false;
  4912. } else {
  4913. ctx.fill();
  4914. }
  4915. }
  4916. if (needRestore) {
  4917. ctx.restore();
  4918. }
  4919. if (consumePath) {
  4920. this.consumePath();
  4921. }
  4922. }
  4923. eoFill() {
  4924. this.pendingEOFill = true;
  4925. this.fill();
  4926. }
  4927. fillStroke() {
  4928. this.fill(false);
  4929. this.stroke(false);
  4930. this.consumePath();
  4931. }
  4932. eoFillStroke() {
  4933. this.pendingEOFill = true;
  4934. this.fillStroke();
  4935. }
  4936. closeFillStroke() {
  4937. this.closePath();
  4938. this.fillStroke();
  4939. }
  4940. closeEOFillStroke() {
  4941. this.pendingEOFill = true;
  4942. this.closePath();
  4943. this.fillStroke();
  4944. }
  4945. endPath() {
  4946. this.consumePath();
  4947. }
  4948. clip() {
  4949. this.pendingClip = NORMAL_CLIP;
  4950. }
  4951. eoClip() {
  4952. this.pendingClip = EO_CLIP;
  4953. }
  4954. beginText() {
  4955. this.current.textMatrix = _util.IDENTITY_MATRIX;
  4956. this.current.textMatrixScale = 1;
  4957. this.current.x = this.current.lineX = 0;
  4958. this.current.y = this.current.lineY = 0;
  4959. }
  4960. endText() {
  4961. const paths = this.pendingTextPaths;
  4962. const ctx = this.ctx;
  4963. if (paths === undefined) {
  4964. ctx.beginPath();
  4965. return;
  4966. }
  4967. ctx.save();
  4968. ctx.beginPath();
  4969. for (let i = 0; i < paths.length; i++) {
  4970. const path = paths[i];
  4971. ctx.setTransform.apply(ctx, path.transform);
  4972. ctx.translate(path.x, path.y);
  4973. path.addToPath(ctx, path.fontSize);
  4974. }
  4975. ctx.restore();
  4976. ctx.clip();
  4977. ctx.beginPath();
  4978. delete this.pendingTextPaths;
  4979. }
  4980. setCharSpacing(spacing) {
  4981. this.current.charSpacing = spacing;
  4982. }
  4983. setWordSpacing(spacing) {
  4984. this.current.wordSpacing = spacing;
  4985. }
  4986. setHScale(scale) {
  4987. this.current.textHScale = scale / 100;
  4988. }
  4989. setLeading(leading) {
  4990. this.current.leading = -leading;
  4991. }
  4992. setFont(fontRefName, size) {
  4993. const fontObj = this.commonObjs.get(fontRefName);
  4994. const current = this.current;
  4995. if (!fontObj) {
  4996. throw new Error(`Can't find font for ${fontRefName}`);
  4997. }
  4998. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  4999. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  5000. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  5001. }
  5002. if (size < 0) {
  5003. size = -size;
  5004. current.fontDirection = -1;
  5005. } else {
  5006. current.fontDirection = 1;
  5007. }
  5008. this.current.font = fontObj;
  5009. this.current.fontSize = size;
  5010. if (fontObj.isType3Font) {
  5011. return;
  5012. }
  5013. const name = fontObj.loadedName || "sans-serif";
  5014. let bold = "normal";
  5015. if (fontObj.black) {
  5016. bold = "900";
  5017. } else if (fontObj.bold) {
  5018. bold = "bold";
  5019. }
  5020. const italic = fontObj.italic ? "italic" : "normal";
  5021. const typeface = `"${name}", ${fontObj.fallbackName}`;
  5022. let browserFontSize = size;
  5023. if (size < MIN_FONT_SIZE) {
  5024. browserFontSize = MIN_FONT_SIZE;
  5025. } else if (size > MAX_FONT_SIZE) {
  5026. browserFontSize = MAX_FONT_SIZE;
  5027. }
  5028. this.current.fontSizeScale = size / browserFontSize;
  5029. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  5030. }
  5031. setTextRenderingMode(mode) {
  5032. this.current.textRenderingMode = mode;
  5033. }
  5034. setTextRise(rise) {
  5035. this.current.textRise = rise;
  5036. }
  5037. moveText(x, y) {
  5038. this.current.x = this.current.lineX += x;
  5039. this.current.y = this.current.lineY += y;
  5040. }
  5041. setLeadingMoveText(x, y) {
  5042. this.setLeading(-y);
  5043. this.moveText(x, y);
  5044. }
  5045. setTextMatrix(a, b, c, d, e, f) {
  5046. this.current.textMatrix = [a, b, c, d, e, f];
  5047. this.current.textMatrixScale = Math.hypot(a, b);
  5048. this.current.x = this.current.lineX = 0;
  5049. this.current.y = this.current.lineY = 0;
  5050. }
  5051. nextLine() {
  5052. this.moveText(0, this.current.leading);
  5053. }
  5054. paintChar(character, x, y, patternTransform, resetLineWidthToOne) {
  5055. const ctx = this.ctx;
  5056. const current = this.current;
  5057. const font = current.font;
  5058. const textRenderingMode = current.textRenderingMode;
  5059. const fontSize = current.fontSize / current.fontSizeScale;
  5060. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  5061. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  5062. const patternFill = current.patternFill && !font.missingFile;
  5063. let addToPath;
  5064. if (font.disableFontFace || isAddToPathSet || patternFill) {
  5065. addToPath = font.getPathGenerator(this.commonObjs, character);
  5066. }
  5067. if (font.disableFontFace || patternFill) {
  5068. ctx.save();
  5069. ctx.translate(x, y);
  5070. ctx.beginPath();
  5071. addToPath(ctx, fontSize);
  5072. if (patternTransform) {
  5073. ctx.setTransform.apply(ctx, patternTransform);
  5074. }
  5075. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  5076. ctx.fill();
  5077. }
  5078. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  5079. if (resetLineWidthToOne) {
  5080. ctx.resetTransform();
  5081. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  5082. }
  5083. ctx.stroke();
  5084. }
  5085. ctx.restore();
  5086. } else {
  5087. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  5088. ctx.fillText(character, x, y);
  5089. }
  5090. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  5091. if (resetLineWidthToOne) {
  5092. ctx.save();
  5093. ctx.moveTo(x, y);
  5094. ctx.resetTransform();
  5095. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  5096. ctx.strokeText(character, 0, 0);
  5097. ctx.restore();
  5098. } else {
  5099. ctx.strokeText(character, x, y);
  5100. }
  5101. }
  5102. }
  5103. if (isAddToPathSet) {
  5104. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  5105. paths.push({
  5106. transform: ctx.mozCurrentTransform,
  5107. x,
  5108. y,
  5109. fontSize,
  5110. addToPath
  5111. });
  5112. }
  5113. }
  5114. get isFontSubpixelAAEnabled() {
  5115. const {
  5116. context: ctx
  5117. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  5118. ctx.scale(1.5, 1);
  5119. ctx.fillText("I", 0, 10);
  5120. const data = ctx.getImageData(0, 0, 10, 10).data;
  5121. let enabled = false;
  5122. for (let i = 3; i < data.length; i += 4) {
  5123. if (data[i] > 0 && data[i] < 255) {
  5124. enabled = true;
  5125. break;
  5126. }
  5127. }
  5128. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  5129. }
  5130. showText(glyphs) {
  5131. const current = this.current;
  5132. const font = current.font;
  5133. if (font.isType3Font) {
  5134. return this.showType3Text(glyphs);
  5135. }
  5136. const fontSize = current.fontSize;
  5137. if (fontSize === 0) {
  5138. return undefined;
  5139. }
  5140. const ctx = this.ctx;
  5141. const fontSizeScale = current.fontSizeScale;
  5142. const charSpacing = current.charSpacing;
  5143. const wordSpacing = current.wordSpacing;
  5144. const fontDirection = current.fontDirection;
  5145. const textHScale = current.textHScale * fontDirection;
  5146. const glyphsLength = glyphs.length;
  5147. const vertical = font.vertical;
  5148. const spacingDir = vertical ? 1 : -1;
  5149. const defaultVMetrics = font.defaultVMetrics;
  5150. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  5151. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  5152. ctx.save();
  5153. let patternTransform;
  5154. if (current.patternFill) {
  5155. ctx.save();
  5156. const pattern = current.fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse);
  5157. patternTransform = ctx.mozCurrentTransform;
  5158. ctx.restore();
  5159. ctx.fillStyle = pattern;
  5160. }
  5161. ctx.transform.apply(ctx, current.textMatrix);
  5162. ctx.translate(current.x, current.y + current.textRise);
  5163. if (fontDirection > 0) {
  5164. ctx.scale(textHScale, -1);
  5165. } else {
  5166. ctx.scale(textHScale, 1);
  5167. }
  5168. let lineWidth = current.lineWidth;
  5169. let resetLineWidthToOne = false;
  5170. const scale = current.textMatrixScale;
  5171. if (scale === 0 || lineWidth === 0) {
  5172. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  5173. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  5174. this._cachedGetSinglePixelWidth = null;
  5175. lineWidth = this.getSinglePixelWidth();
  5176. resetLineWidthToOne = lineWidth < 0;
  5177. }
  5178. } else {
  5179. lineWidth /= scale;
  5180. }
  5181. if (fontSizeScale !== 1.0) {
  5182. ctx.scale(fontSizeScale, fontSizeScale);
  5183. lineWidth /= fontSizeScale;
  5184. }
  5185. ctx.lineWidth = lineWidth;
  5186. let x = 0,
  5187. i;
  5188. for (i = 0; i < glyphsLength; ++i) {
  5189. const glyph = glyphs[i];
  5190. if ((0, _util.isNum)(glyph)) {
  5191. x += spacingDir * glyph * fontSize / 1000;
  5192. continue;
  5193. }
  5194. let restoreNeeded = false;
  5195. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  5196. const character = glyph.fontChar;
  5197. const accent = glyph.accent;
  5198. let scaledX, scaledY;
  5199. let width = glyph.width;
  5200. if (vertical) {
  5201. const vmetric = glyph.vmetric || defaultVMetrics;
  5202. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  5203. const vy = vmetric[2] * widthAdvanceScale;
  5204. width = vmetric ? -vmetric[0] : width;
  5205. scaledX = vx / fontSizeScale;
  5206. scaledY = (x + vy) / fontSizeScale;
  5207. } else {
  5208. scaledX = x / fontSizeScale;
  5209. scaledY = 0;
  5210. }
  5211. if (font.remeasure && width > 0) {
  5212. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  5213. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  5214. const characterScaleX = width / measuredWidth;
  5215. restoreNeeded = true;
  5216. ctx.save();
  5217. ctx.scale(characterScaleX, 1);
  5218. scaledX /= characterScaleX;
  5219. } else if (width !== measuredWidth) {
  5220. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  5221. }
  5222. }
  5223. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  5224. if (simpleFillText && !accent) {
  5225. ctx.fillText(character, scaledX, scaledY);
  5226. } else {
  5227. this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne);
  5228. if (accent) {
  5229. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  5230. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  5231. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne);
  5232. }
  5233. }
  5234. }
  5235. let charWidth;
  5236. if (vertical) {
  5237. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  5238. } else {
  5239. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  5240. }
  5241. x += charWidth;
  5242. if (restoreNeeded) {
  5243. ctx.restore();
  5244. }
  5245. }
  5246. if (vertical) {
  5247. current.y -= x;
  5248. } else {
  5249. current.x += x * textHScale;
  5250. }
  5251. ctx.restore();
  5252. return undefined;
  5253. }
  5254. showType3Text(glyphs) {
  5255. const ctx = this.ctx;
  5256. const current = this.current;
  5257. const font = current.font;
  5258. const fontSize = current.fontSize;
  5259. const fontDirection = current.fontDirection;
  5260. const spacingDir = font.vertical ? 1 : -1;
  5261. const charSpacing = current.charSpacing;
  5262. const wordSpacing = current.wordSpacing;
  5263. const textHScale = current.textHScale * fontDirection;
  5264. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  5265. const glyphsLength = glyphs.length;
  5266. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  5267. let i, glyph, width, spacingLength;
  5268. if (isTextInvisible || fontSize === 0) {
  5269. return;
  5270. }
  5271. this._cachedGetSinglePixelWidth = null;
  5272. ctx.save();
  5273. ctx.transform.apply(ctx, current.textMatrix);
  5274. ctx.translate(current.x, current.y);
  5275. ctx.scale(textHScale, fontDirection);
  5276. for (i = 0; i < glyphsLength; ++i) {
  5277. glyph = glyphs[i];
  5278. if ((0, _util.isNum)(glyph)) {
  5279. spacingLength = spacingDir * glyph * fontSize / 1000;
  5280. this.ctx.translate(spacingLength, 0);
  5281. current.x += spacingLength * textHScale;
  5282. continue;
  5283. }
  5284. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  5285. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  5286. if (!operatorList) {
  5287. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  5288. continue;
  5289. }
  5290. if (this.contentVisible) {
  5291. this.processingType3 = glyph;
  5292. this.save();
  5293. ctx.scale(fontSize, fontSize);
  5294. ctx.transform.apply(ctx, fontMatrix);
  5295. this.executeOperatorList(operatorList);
  5296. this.restore();
  5297. }
  5298. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  5299. width = transformed[0] * fontSize + spacing;
  5300. ctx.translate(width, 0);
  5301. current.x += width * textHScale;
  5302. }
  5303. ctx.restore();
  5304. this.processingType3 = null;
  5305. }
  5306. setCharWidth(xWidth, yWidth) {}
  5307. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  5308. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  5309. this.clip();
  5310. this.endPath();
  5311. }
  5312. getColorN_Pattern(IR) {
  5313. let pattern;
  5314. if (IR[0] === "TilingPattern") {
  5315. const color = IR[1];
  5316. const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  5317. const canvasGraphicsFactory = {
  5318. createCanvasGraphics: ctx => {
  5319. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
  5320. }
  5321. };
  5322. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  5323. } else {
  5324. pattern = this._getPattern(IR[1], IR[2]);
  5325. }
  5326. return pattern;
  5327. }
  5328. setStrokeColorN() {
  5329. this.current.strokeColor = this.getColorN_Pattern(arguments);
  5330. }
  5331. setFillColorN() {
  5332. this.current.fillColor = this.getColorN_Pattern(arguments);
  5333. this.current.patternFill = true;
  5334. }
  5335. setStrokeRGBColor(r, g, b) {
  5336. const color = _util.Util.makeHexColor(r, g, b);
  5337. this.ctx.strokeStyle = color;
  5338. this.current.strokeColor = color;
  5339. }
  5340. setFillRGBColor(r, g, b) {
  5341. const color = _util.Util.makeHexColor(r, g, b);
  5342. this.ctx.fillStyle = color;
  5343. this.current.fillColor = color;
  5344. this.current.patternFill = false;
  5345. }
  5346. _getPattern(objId, matrix = null) {
  5347. let pattern;
  5348. if (this.cachedPatterns.has(objId)) {
  5349. pattern = this.cachedPatterns.get(objId);
  5350. } else {
  5351. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId), this.cachedCanvasPatterns);
  5352. this.cachedPatterns.set(objId, pattern);
  5353. }
  5354. if (matrix) {
  5355. pattern.matrix = matrix;
  5356. }
  5357. return pattern;
  5358. }
  5359. shadingFill(objId) {
  5360. if (!this.contentVisible) {
  5361. return;
  5362. }
  5363. const ctx = this.ctx;
  5364. this.save();
  5365. const pattern = this._getPattern(objId);
  5366. ctx.fillStyle = pattern.getPattern(ctx, this, ctx.mozCurrentTransformInverse, true);
  5367. const inv = ctx.mozCurrentTransformInverse;
  5368. if (inv) {
  5369. const canvas = ctx.canvas;
  5370. const width = canvas.width;
  5371. const height = canvas.height;
  5372. const bl = _util.Util.applyTransform([0, 0], inv);
  5373. const br = _util.Util.applyTransform([0, height], inv);
  5374. const ul = _util.Util.applyTransform([width, 0], inv);
  5375. const ur = _util.Util.applyTransform([width, height], inv);
  5376. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  5377. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  5378. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  5379. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  5380. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  5381. } else {
  5382. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  5383. }
  5384. this.restore();
  5385. }
  5386. beginInlineImage() {
  5387. (0, _util.unreachable)("Should not call beginInlineImage");
  5388. }
  5389. beginImageData() {
  5390. (0, _util.unreachable)("Should not call beginImageData");
  5391. }
  5392. paintFormXObjectBegin(matrix, bbox) {
  5393. if (!this.contentVisible) {
  5394. return;
  5395. }
  5396. this.save();
  5397. this.baseTransformStack.push(this.baseTransform);
  5398. if (Array.isArray(matrix) && matrix.length === 6) {
  5399. this.transform.apply(this, matrix);
  5400. }
  5401. this.baseTransform = this.ctx.mozCurrentTransform;
  5402. if (bbox) {
  5403. const width = bbox[2] - bbox[0];
  5404. const height = bbox[3] - bbox[1];
  5405. this.ctx.rect(bbox[0], bbox[1], width, height);
  5406. this.clip();
  5407. this.endPath();
  5408. }
  5409. }
  5410. paintFormXObjectEnd() {
  5411. if (!this.contentVisible) {
  5412. return;
  5413. }
  5414. this.restore();
  5415. this.baseTransform = this.baseTransformStack.pop();
  5416. }
  5417. beginGroup(group) {
  5418. if (!this.contentVisible) {
  5419. return;
  5420. }
  5421. this.save();
  5422. const currentCtx = this.ctx;
  5423. if (!group.isolated) {
  5424. (0, _util.info)("TODO: Support non-isolated groups.");
  5425. }
  5426. if (group.knockout) {
  5427. (0, _util.warn)("Knockout groups not supported.");
  5428. }
  5429. const currentTransform = currentCtx.mozCurrentTransform;
  5430. if (group.matrix) {
  5431. currentCtx.transform.apply(currentCtx, group.matrix);
  5432. }
  5433. if (!group.bbox) {
  5434. throw new Error("Bounding box is required.");
  5435. }
  5436. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  5437. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  5438. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  5439. const offsetX = Math.floor(bounds[0]);
  5440. const offsetY = Math.floor(bounds[1]);
  5441. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  5442. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  5443. let scaleX = 1,
  5444. scaleY = 1;
  5445. if (drawnWidth > MAX_GROUP_SIZE) {
  5446. scaleX = drawnWidth / MAX_GROUP_SIZE;
  5447. drawnWidth = MAX_GROUP_SIZE;
  5448. }
  5449. if (drawnHeight > MAX_GROUP_SIZE) {
  5450. scaleY = drawnHeight / MAX_GROUP_SIZE;
  5451. drawnHeight = MAX_GROUP_SIZE;
  5452. }
  5453. let cacheId = "groupAt" + this.groupLevel;
  5454. if (group.smask) {
  5455. cacheId += "_smask_" + this.smaskCounter++ % 2;
  5456. }
  5457. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  5458. const groupCtx = scratchCanvas.context;
  5459. groupCtx.scale(1 / scaleX, 1 / scaleY);
  5460. groupCtx.translate(-offsetX, -offsetY);
  5461. groupCtx.transform.apply(groupCtx, currentTransform);
  5462. if (group.smask) {
  5463. this.smaskStack.push({
  5464. canvas: scratchCanvas.canvas,
  5465. context: groupCtx,
  5466. offsetX,
  5467. offsetY,
  5468. scaleX,
  5469. scaleY,
  5470. subtype: group.smask.subtype,
  5471. backdrop: group.smask.backdrop,
  5472. transferMap: group.smask.transferMap || null,
  5473. startTransformInverse: null
  5474. });
  5475. } else {
  5476. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  5477. currentCtx.translate(offsetX, offsetY);
  5478. currentCtx.scale(scaleX, scaleY);
  5479. }
  5480. copyCtxState(currentCtx, groupCtx);
  5481. this.ctx = groupCtx;
  5482. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  5483. this.groupStack.push(currentCtx);
  5484. this.groupLevel++;
  5485. this.current.activeSMask = null;
  5486. }
  5487. endGroup(group) {
  5488. if (!this.contentVisible) {
  5489. return;
  5490. }
  5491. this.groupLevel--;
  5492. const groupCtx = this.ctx;
  5493. this.ctx = this.groupStack.pop();
  5494. this.ctx.imageSmoothingEnabled = false;
  5495. if (group.smask) {
  5496. this.tempSMask = this.smaskStack.pop();
  5497. } else {
  5498. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  5499. }
  5500. this.restore();
  5501. }
  5502. beginAnnotations() {
  5503. this.save();
  5504. if (this.baseTransform) {
  5505. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  5506. }
  5507. }
  5508. endAnnotations() {
  5509. this.restore();
  5510. }
  5511. beginAnnotation(id, rect, transform, matrix) {
  5512. this.save();
  5513. resetCtxToDefault(this.ctx);
  5514. this.current = new CanvasExtraState();
  5515. if (Array.isArray(rect) && rect.length === 4) {
  5516. const width = rect[2] - rect[0];
  5517. const height = rect[3] - rect[1];
  5518. this.ctx.rect(rect[0], rect[1], width, height);
  5519. this.clip();
  5520. this.endPath();
  5521. }
  5522. this.transform.apply(this, transform);
  5523. this.transform.apply(this, matrix);
  5524. }
  5525. endAnnotation() {
  5526. this.restore();
  5527. }
  5528. paintImageMaskXObject(img) {
  5529. if (!this.contentVisible) {
  5530. return;
  5531. }
  5532. const ctx = this.ctx;
  5533. const width = img.width,
  5534. height = img.height;
  5535. const glyph = this.processingType3;
  5536. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  5537. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  5538. glyph.compiled = compileType3Glyph({
  5539. data: img.data,
  5540. width,
  5541. height
  5542. });
  5543. } else {
  5544. glyph.compiled = null;
  5545. }
  5546. }
  5547. if (glyph?.compiled) {
  5548. glyph.compiled(ctx);
  5549. return;
  5550. }
  5551. const mask = this._createMaskCanvas(img);
  5552. const maskCanvas = mask.canvas;
  5553. ctx.save();
  5554. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5555. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  5556. ctx.restore();
  5557. }
  5558. paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  5559. if (!this.contentVisible) {
  5560. return;
  5561. }
  5562. const ctx = this.ctx;
  5563. ctx.save();
  5564. const currentTransform = ctx.mozCurrentTransform;
  5565. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  5566. const mask = this._createMaskCanvas(imgData);
  5567. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5568. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  5569. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  5570. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  5571. ctx.drawImage(mask.canvas, x, y);
  5572. }
  5573. ctx.restore();
  5574. }
  5575. paintImageMaskXObjectGroup(images) {
  5576. if (!this.contentVisible) {
  5577. return;
  5578. }
  5579. const ctx = this.ctx;
  5580. const fillColor = this.current.fillColor;
  5581. const isPatternFill = this.current.patternFill;
  5582. for (let i = 0, ii = images.length; i < ii; i++) {
  5583. const image = images[i];
  5584. const width = image.width,
  5585. height = image.height;
  5586. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5587. const maskCtx = maskCanvas.context;
  5588. maskCtx.save();
  5589. putBinaryImageMask(maskCtx, image);
  5590. maskCtx.globalCompositeOperation = "source-in";
  5591. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, ctx.mozCurrentTransformInverse, false) : fillColor;
  5592. maskCtx.fillRect(0, 0, width, height);
  5593. maskCtx.restore();
  5594. ctx.save();
  5595. ctx.transform.apply(ctx, image.transform);
  5596. ctx.scale(1, -1);
  5597. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  5598. ctx.restore();
  5599. }
  5600. }
  5601. paintImageXObject(objId) {
  5602. if (!this.contentVisible) {
  5603. return;
  5604. }
  5605. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  5606. if (!imgData) {
  5607. (0, _util.warn)("Dependent image isn't ready yet");
  5608. return;
  5609. }
  5610. this.paintInlineImageXObject(imgData);
  5611. }
  5612. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  5613. if (!this.contentVisible) {
  5614. return;
  5615. }
  5616. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  5617. if (!imgData) {
  5618. (0, _util.warn)("Dependent image isn't ready yet");
  5619. return;
  5620. }
  5621. const width = imgData.width;
  5622. const height = imgData.height;
  5623. const map = [];
  5624. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  5625. map.push({
  5626. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  5627. x: 0,
  5628. y: 0,
  5629. w: width,
  5630. h: height
  5631. });
  5632. }
  5633. this.paintInlineImageXObjectGroup(imgData, map);
  5634. }
  5635. paintInlineImageXObject(imgData) {
  5636. if (!this.contentVisible) {
  5637. return;
  5638. }
  5639. const width = imgData.width;
  5640. const height = imgData.height;
  5641. const ctx = this.ctx;
  5642. this.save();
  5643. ctx.scale(1 / width, -1 / height);
  5644. let imgToPaint;
  5645. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  5646. imgToPaint = imgData;
  5647. } else {
  5648. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  5649. const tmpCtx = tmpCanvas.context;
  5650. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  5651. imgToPaint = tmpCanvas.canvas;
  5652. }
  5653. const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse);
  5654. ctx.imageSmoothingEnabled = getImageSmoothingEnabled(ctx.mozCurrentTransform, imgData.interpolate);
  5655. ctx.drawImage(scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  5656. if (this.imageLayer) {
  5657. const position = this.getCanvasPosition(0, -height);
  5658. this.imageLayer.appendImage({
  5659. imgData,
  5660. left: position[0],
  5661. top: position[1],
  5662. width: width / ctx.mozCurrentTransformInverse[0],
  5663. height: height / ctx.mozCurrentTransformInverse[3]
  5664. });
  5665. }
  5666. this.restore();
  5667. }
  5668. paintInlineImageXObjectGroup(imgData, map) {
  5669. if (!this.contentVisible) {
  5670. return;
  5671. }
  5672. const ctx = this.ctx;
  5673. const w = imgData.width;
  5674. const h = imgData.height;
  5675. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  5676. const tmpCtx = tmpCanvas.context;
  5677. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  5678. for (let i = 0, ii = map.length; i < ii; i++) {
  5679. const entry = map[i];
  5680. ctx.save();
  5681. ctx.transform.apply(ctx, entry.transform);
  5682. ctx.scale(1, -1);
  5683. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  5684. if (this.imageLayer) {
  5685. const position = this.getCanvasPosition(entry.x, entry.y);
  5686. this.imageLayer.appendImage({
  5687. imgData,
  5688. left: position[0],
  5689. top: position[1],
  5690. width: w,
  5691. height: h
  5692. });
  5693. }
  5694. ctx.restore();
  5695. }
  5696. }
  5697. paintSolidColorImageMask() {
  5698. if (!this.contentVisible) {
  5699. return;
  5700. }
  5701. this.ctx.fillRect(0, 0, 1, 1);
  5702. }
  5703. markPoint(tag) {}
  5704. markPointProps(tag, properties) {}
  5705. beginMarkedContent(tag) {
  5706. this.markedContentStack.push({
  5707. visible: true
  5708. });
  5709. }
  5710. beginMarkedContentProps(tag, properties) {
  5711. if (tag === "OC") {
  5712. this.markedContentStack.push({
  5713. visible: this.optionalContentConfig.isVisible(properties)
  5714. });
  5715. } else {
  5716. this.markedContentStack.push({
  5717. visible: true
  5718. });
  5719. }
  5720. this.contentVisible = this.isContentVisible();
  5721. }
  5722. endMarkedContent() {
  5723. this.markedContentStack.pop();
  5724. this.contentVisible = this.isContentVisible();
  5725. }
  5726. beginCompat() {}
  5727. endCompat() {}
  5728. consumePath() {
  5729. const ctx = this.ctx;
  5730. if (this.pendingClip) {
  5731. if (this.pendingClip === EO_CLIP) {
  5732. ctx.clip("evenodd");
  5733. } else {
  5734. ctx.clip();
  5735. }
  5736. this.pendingClip = null;
  5737. }
  5738. ctx.beginPath();
  5739. }
  5740. getSinglePixelWidth() {
  5741. if (this._cachedGetSinglePixelWidth === null) {
  5742. const m = this.ctx.mozCurrentTransform;
  5743. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  5744. const sqNorm1 = m[0] ** 2 + m[2] ** 2;
  5745. const sqNorm2 = m[1] ** 2 + m[3] ** 2;
  5746. const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet;
  5747. if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) {
  5748. this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight);
  5749. } else if (absDet > Number.EPSILON) {
  5750. this._cachedGetSinglePixelWidth = pixelHeight;
  5751. } else {
  5752. this._cachedGetSinglePixelWidth = 1;
  5753. }
  5754. }
  5755. return this._cachedGetSinglePixelWidth;
  5756. }
  5757. getCanvasPosition(x, y) {
  5758. const transform = this.ctx.mozCurrentTransform;
  5759. return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
  5760. }
  5761. isContentVisible() {
  5762. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  5763. if (!this.markedContentStack[i].visible) {
  5764. return false;
  5765. }
  5766. }
  5767. return true;
  5768. }
  5769. }
  5770. exports.CanvasGraphics = CanvasGraphics;
  5771. for (const op in _util.OPS) {
  5772. if (CanvasGraphics.prototype[op] !== undefined) {
  5773. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  5774. }
  5775. }
  5776. /***/ }),
  5777. /* 11 */
  5778. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5779. Object.defineProperty(exports, "__esModule", ({
  5780. value: true
  5781. }));
  5782. exports.getShadingPattern = getShadingPattern;
  5783. exports.TilingPattern = void 0;
  5784. var _util = __w_pdfjs_require__(2);
  5785. function applyBoundingBox(ctx, bbox) {
  5786. if (!bbox || typeof Path2D === "undefined") {
  5787. return;
  5788. }
  5789. const width = bbox[2] - bbox[0];
  5790. const height = bbox[3] - bbox[1];
  5791. const region = new Path2D();
  5792. region.rect(bbox[0], bbox[1], width, height);
  5793. ctx.clip(region);
  5794. }
  5795. class BaseShadingPattern {
  5796. constructor() {
  5797. if (this.constructor === BaseShadingPattern) {
  5798. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  5799. }
  5800. }
  5801. getPattern() {
  5802. (0, _util.unreachable)("Abstract method `getPattern` called.");
  5803. }
  5804. }
  5805. class RadialAxialShadingPattern extends BaseShadingPattern {
  5806. constructor(IR, cachedCanvasPatterns) {
  5807. super();
  5808. this._type = IR[1];
  5809. this._bbox = IR[2];
  5810. this._colorStops = IR[3];
  5811. this._p0 = IR[4];
  5812. this._p1 = IR[5];
  5813. this._r0 = IR[6];
  5814. this._r1 = IR[7];
  5815. this.matrix = null;
  5816. this.cachedCanvasPatterns = cachedCanvasPatterns;
  5817. }
  5818. _createGradient(ctx) {
  5819. let grad;
  5820. if (this._type === "axial") {
  5821. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  5822. } else if (this._type === "radial") {
  5823. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  5824. }
  5825. for (const colorStop of this._colorStops) {
  5826. grad.addColorStop(colorStop[0], colorStop[1]);
  5827. }
  5828. return grad;
  5829. }
  5830. getPattern(ctx, owner, inverse, shadingFill = false) {
  5831. let pattern;
  5832. if (!shadingFill) {
  5833. if (this.cachedCanvasPatterns.has(this)) {
  5834. pattern = this.cachedCanvasPatterns.get(this);
  5835. } else {
  5836. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", owner.ctx.canvas.width, owner.ctx.canvas.height, true);
  5837. const tmpCtx = tmpCanvas.context;
  5838. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5839. tmpCtx.beginPath();
  5840. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5841. tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
  5842. if (this.matrix) {
  5843. tmpCtx.transform.apply(tmpCtx, this.matrix);
  5844. }
  5845. applyBoundingBox(tmpCtx, this._bbox);
  5846. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  5847. tmpCtx.fill();
  5848. pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
  5849. this.cachedCanvasPatterns.set(this, pattern);
  5850. }
  5851. } else {
  5852. applyBoundingBox(ctx, this._bbox);
  5853. pattern = this._createGradient(ctx);
  5854. }
  5855. if (!shadingFill) {
  5856. const domMatrix = new DOMMatrix(inverse);
  5857. try {
  5858. pattern.setTransform(domMatrix);
  5859. } catch (ex) {
  5860. (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
  5861. }
  5862. }
  5863. return pattern;
  5864. }
  5865. }
  5866. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5867. const coords = context.coords,
  5868. colors = context.colors;
  5869. const bytes = data.data,
  5870. rowSize = data.width * 4;
  5871. let tmp;
  5872. if (coords[p1 + 1] > coords[p2 + 1]) {
  5873. tmp = p1;
  5874. p1 = p2;
  5875. p2 = tmp;
  5876. tmp = c1;
  5877. c1 = c2;
  5878. c2 = tmp;
  5879. }
  5880. if (coords[p2 + 1] > coords[p3 + 1]) {
  5881. tmp = p2;
  5882. p2 = p3;
  5883. p3 = tmp;
  5884. tmp = c2;
  5885. c2 = c3;
  5886. c3 = tmp;
  5887. }
  5888. if (coords[p1 + 1] > coords[p2 + 1]) {
  5889. tmp = p1;
  5890. p1 = p2;
  5891. p2 = tmp;
  5892. tmp = c1;
  5893. c1 = c2;
  5894. c2 = tmp;
  5895. }
  5896. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5897. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5898. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5899. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5900. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5901. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5902. if (y1 >= y3) {
  5903. return;
  5904. }
  5905. const c1r = colors[c1],
  5906. c1g = colors[c1 + 1],
  5907. c1b = colors[c1 + 2];
  5908. const c2r = colors[c2],
  5909. c2g = colors[c2 + 1],
  5910. c2b = colors[c2 + 2];
  5911. const c3r = colors[c3],
  5912. c3g = colors[c3 + 1],
  5913. c3b = colors[c3 + 2];
  5914. const minY = Math.round(y1),
  5915. maxY = Math.round(y3);
  5916. let xa, car, cag, cab;
  5917. let xb, cbr, cbg, cbb;
  5918. for (let y = minY; y <= maxY; y++) {
  5919. if (y < y2) {
  5920. let k;
  5921. if (y < y1) {
  5922. k = 0;
  5923. } else {
  5924. k = (y1 - y) / (y1 - y2);
  5925. }
  5926. xa = x1 - (x1 - x2) * k;
  5927. car = c1r - (c1r - c2r) * k;
  5928. cag = c1g - (c1g - c2g) * k;
  5929. cab = c1b - (c1b - c2b) * k;
  5930. } else {
  5931. let k;
  5932. if (y > y3) {
  5933. k = 1;
  5934. } else if (y2 === y3) {
  5935. k = 0;
  5936. } else {
  5937. k = (y2 - y) / (y2 - y3);
  5938. }
  5939. xa = x2 - (x2 - x3) * k;
  5940. car = c2r - (c2r - c3r) * k;
  5941. cag = c2g - (c2g - c3g) * k;
  5942. cab = c2b - (c2b - c3b) * k;
  5943. }
  5944. let k;
  5945. if (y < y1) {
  5946. k = 0;
  5947. } else if (y > y3) {
  5948. k = 1;
  5949. } else {
  5950. k = (y1 - y) / (y1 - y3);
  5951. }
  5952. xb = x1 - (x1 - x3) * k;
  5953. cbr = c1r - (c1r - c3r) * k;
  5954. cbg = c1g - (c1g - c3g) * k;
  5955. cbb = c1b - (c1b - c3b) * k;
  5956. const x1_ = Math.round(Math.min(xa, xb));
  5957. const x2_ = Math.round(Math.max(xa, xb));
  5958. let j = rowSize * y + x1_ * 4;
  5959. for (let x = x1_; x <= x2_; x++) {
  5960. k = (xa - x) / (xa - xb);
  5961. if (k < 0) {
  5962. k = 0;
  5963. } else if (k > 1) {
  5964. k = 1;
  5965. }
  5966. bytes[j++] = car - (car - cbr) * k | 0;
  5967. bytes[j++] = cag - (cag - cbg) * k | 0;
  5968. bytes[j++] = cab - (cab - cbb) * k | 0;
  5969. bytes[j++] = 255;
  5970. }
  5971. }
  5972. }
  5973. function drawFigure(data, figure, context) {
  5974. const ps = figure.coords;
  5975. const cs = figure.colors;
  5976. let i, ii;
  5977. switch (figure.type) {
  5978. case "lattice":
  5979. const verticesPerRow = figure.verticesPerRow;
  5980. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  5981. const cols = verticesPerRow - 1;
  5982. for (i = 0; i < rows; i++) {
  5983. let q = i * verticesPerRow;
  5984. for (let j = 0; j < cols; j++, q++) {
  5985. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5986. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5987. }
  5988. }
  5989. break;
  5990. case "triangles":
  5991. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5992. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  5993. }
  5994. break;
  5995. default:
  5996. throw new Error("illegal figure");
  5997. }
  5998. }
  5999. class MeshShadingPattern extends BaseShadingPattern {
  6000. constructor(IR) {
  6001. super();
  6002. this._coords = IR[2];
  6003. this._colors = IR[3];
  6004. this._figures = IR[4];
  6005. this._bounds = IR[5];
  6006. this._bbox = IR[7];
  6007. this._background = IR[8];
  6008. this.matrix = null;
  6009. }
  6010. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  6011. const EXPECTED_SCALE = 1.1;
  6012. const MAX_PATTERN_SIZE = 3000;
  6013. const BORDER_SIZE = 2;
  6014. const offsetX = Math.floor(this._bounds[0]);
  6015. const offsetY = Math.floor(this._bounds[1]);
  6016. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  6017. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  6018. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6019. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6020. const scaleX = boundsWidth / width;
  6021. const scaleY = boundsHeight / height;
  6022. const context = {
  6023. coords: this._coords,
  6024. colors: this._colors,
  6025. offsetX: -offsetX,
  6026. offsetY: -offsetY,
  6027. scaleX: 1 / scaleX,
  6028. scaleY: 1 / scaleY
  6029. };
  6030. const paddedWidth = width + BORDER_SIZE * 2;
  6031. const paddedHeight = height + BORDER_SIZE * 2;
  6032. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  6033. const tmpCtx = tmpCanvas.context;
  6034. const data = tmpCtx.createImageData(width, height);
  6035. if (backgroundColor) {
  6036. const bytes = data.data;
  6037. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  6038. bytes[i] = backgroundColor[0];
  6039. bytes[i + 1] = backgroundColor[1];
  6040. bytes[i + 2] = backgroundColor[2];
  6041. bytes[i + 3] = 255;
  6042. }
  6043. }
  6044. for (const figure of this._figures) {
  6045. drawFigure(data, figure, context);
  6046. }
  6047. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6048. const canvas = tmpCanvas.canvas;
  6049. return {
  6050. canvas,
  6051. offsetX: offsetX - BORDER_SIZE * scaleX,
  6052. offsetY: offsetY - BORDER_SIZE * scaleY,
  6053. scaleX,
  6054. scaleY
  6055. };
  6056. }
  6057. getPattern(ctx, owner, inverse, shadingFill = false) {
  6058. applyBoundingBox(ctx, this._bbox);
  6059. let scale;
  6060. if (shadingFill) {
  6061. scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  6062. } else {
  6063. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  6064. if (this.matrix) {
  6065. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  6066. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  6067. }
  6068. }
  6069. const temporaryPatternCanvas = this._createMeshCanvas(scale, shadingFill ? null : this._background, owner.cachedCanvases);
  6070. if (!shadingFill) {
  6071. ctx.setTransform.apply(ctx, owner.baseTransform);
  6072. if (this.matrix) {
  6073. ctx.transform.apply(ctx, this.matrix);
  6074. }
  6075. }
  6076. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6077. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6078. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  6079. }
  6080. }
  6081. class DummyShadingPattern extends BaseShadingPattern {
  6082. getPattern() {
  6083. return "hotpink";
  6084. }
  6085. }
  6086. function getShadingPattern(IR, cachedCanvasPatterns) {
  6087. switch (IR[0]) {
  6088. case "RadialAxial":
  6089. return new RadialAxialShadingPattern(IR, cachedCanvasPatterns);
  6090. case "Mesh":
  6091. return new MeshShadingPattern(IR);
  6092. case "Dummy":
  6093. return new DummyShadingPattern();
  6094. }
  6095. throw new Error(`Unknown IR type: ${IR[0]}`);
  6096. }
  6097. const PaintType = {
  6098. COLORED: 1,
  6099. UNCOLORED: 2
  6100. };
  6101. class TilingPattern {
  6102. static get MAX_PATTERN_SIZE() {
  6103. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  6104. }
  6105. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6106. this.operatorList = IR[2];
  6107. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  6108. this.bbox = IR[4];
  6109. this.xstep = IR[5];
  6110. this.ystep = IR[6];
  6111. this.paintType = IR[7];
  6112. this.tilingType = IR[8];
  6113. this.color = color;
  6114. this.ctx = ctx;
  6115. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6116. this.baseTransform = baseTransform;
  6117. }
  6118. createPatternCanvas(owner) {
  6119. const operatorList = this.operatorList;
  6120. const bbox = this.bbox;
  6121. const xstep = this.xstep;
  6122. const ystep = this.ystep;
  6123. const paintType = this.paintType;
  6124. const tilingType = this.tilingType;
  6125. const color = this.color;
  6126. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  6127. (0, _util.info)("TilingType: " + tilingType);
  6128. const x0 = bbox[0],
  6129. y0 = bbox[1],
  6130. x1 = bbox[2],
  6131. y1 = bbox[3];
  6132. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  6133. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  6134. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  6135. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  6136. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  6137. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  6138. const tmpCtx = tmpCanvas.context;
  6139. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6140. graphics.groupLevel = owner.groupLevel;
  6141. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  6142. let adjustedX0 = x0;
  6143. let adjustedY0 = y0;
  6144. let adjustedX1 = x1;
  6145. let adjustedY1 = y1;
  6146. if (x0 < 0) {
  6147. adjustedX0 = 0;
  6148. adjustedX1 += Math.abs(x0);
  6149. }
  6150. if (y0 < 0) {
  6151. adjustedY0 = 0;
  6152. adjustedY1 += Math.abs(y0);
  6153. }
  6154. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  6155. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  6156. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  6157. graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
  6158. graphics.executeOperatorList(operatorList);
  6159. graphics.endDrawing();
  6160. return {
  6161. canvas: tmpCanvas.canvas,
  6162. scaleX: dimx.scale,
  6163. scaleY: dimy.scale,
  6164. offsetX: adjustedX0,
  6165. offsetY: adjustedY0
  6166. };
  6167. }
  6168. getSizeAndScale(step, realOutputSize, scale) {
  6169. step = Math.abs(step);
  6170. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  6171. let size = Math.ceil(step * scale);
  6172. if (size >= maxSize) {
  6173. size = maxSize;
  6174. } else {
  6175. scale = size / step;
  6176. }
  6177. return {
  6178. scale,
  6179. size
  6180. };
  6181. }
  6182. clipBbox(graphics, x0, y0, x1, y1) {
  6183. const bboxWidth = x1 - x0;
  6184. const bboxHeight = y1 - y0;
  6185. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6186. graphics.clip();
  6187. graphics.endPath();
  6188. }
  6189. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  6190. const context = graphics.ctx,
  6191. current = graphics.current;
  6192. switch (paintType) {
  6193. case PaintType.COLORED:
  6194. const ctx = this.ctx;
  6195. context.fillStyle = ctx.fillStyle;
  6196. context.strokeStyle = ctx.strokeStyle;
  6197. current.fillColor = ctx.fillStyle;
  6198. current.strokeColor = ctx.strokeStyle;
  6199. break;
  6200. case PaintType.UNCOLORED:
  6201. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  6202. context.fillStyle = cssColor;
  6203. context.strokeStyle = cssColor;
  6204. current.fillColor = cssColor;
  6205. current.strokeColor = cssColor;
  6206. break;
  6207. default:
  6208. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  6209. }
  6210. }
  6211. getPattern(ctx, owner, inverse, shadingFill = false) {
  6212. let matrix = inverse;
  6213. if (!shadingFill) {
  6214. matrix = _util.Util.transform(matrix, owner.baseTransform);
  6215. if (this.matrix) {
  6216. matrix = _util.Util.transform(matrix, this.matrix);
  6217. }
  6218. }
  6219. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  6220. let domMatrix = new DOMMatrix(matrix);
  6221. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6222. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  6223. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  6224. try {
  6225. pattern.setTransform(domMatrix);
  6226. } catch (ex) {
  6227. (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
  6228. }
  6229. return pattern;
  6230. }
  6231. }
  6232. exports.TilingPattern = TilingPattern;
  6233. /***/ }),
  6234. /* 12 */
  6235. /***/ ((__unused_webpack_module, exports) => {
  6236. Object.defineProperty(exports, "__esModule", ({
  6237. value: true
  6238. }));
  6239. exports.GlobalWorkerOptions = void 0;
  6240. const GlobalWorkerOptions = Object.create(null);
  6241. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  6242. GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
  6243. GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
  6244. /***/ }),
  6245. /* 13 */
  6246. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6247. Object.defineProperty(exports, "__esModule", ({
  6248. value: true
  6249. }));
  6250. exports.MessageHandler = void 0;
  6251. var _util = __w_pdfjs_require__(2);
  6252. const CallbackKind = {
  6253. UNKNOWN: 0,
  6254. DATA: 1,
  6255. ERROR: 2
  6256. };
  6257. const StreamKind = {
  6258. UNKNOWN: 0,
  6259. CANCEL: 1,
  6260. CANCEL_COMPLETE: 2,
  6261. CLOSE: 3,
  6262. ENQUEUE: 4,
  6263. ERROR: 5,
  6264. PULL: 6,
  6265. PULL_COMPLETE: 7,
  6266. START_COMPLETE: 8
  6267. };
  6268. function wrapReason(reason) {
  6269. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  6270. (0, _util.warn)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  6271. return reason;
  6272. }
  6273. switch (reason.name) {
  6274. case "AbortException":
  6275. return new _util.AbortException(reason.message);
  6276. case "MissingPDFException":
  6277. return new _util.MissingPDFException(reason.message);
  6278. case "PasswordException":
  6279. return new _util.PasswordException(reason.message, reason.code);
  6280. case "UnexpectedResponseException":
  6281. return new _util.UnexpectedResponseException(reason.message, reason.status);
  6282. case "UnknownErrorException":
  6283. return new _util.UnknownErrorException(reason.message, reason.details);
  6284. default:
  6285. return new _util.UnknownErrorException(reason.message, reason.toString());
  6286. }
  6287. }
  6288. class MessageHandler {
  6289. constructor(sourceName, targetName, comObj) {
  6290. this.sourceName = sourceName;
  6291. this.targetName = targetName;
  6292. this.comObj = comObj;
  6293. this.callbackId = 1;
  6294. this.streamId = 1;
  6295. this.postMessageTransfers = true;
  6296. this.streamSinks = Object.create(null);
  6297. this.streamControllers = Object.create(null);
  6298. this.callbackCapabilities = Object.create(null);
  6299. this.actionHandler = Object.create(null);
  6300. this._onComObjOnMessage = event => {
  6301. const data = event.data;
  6302. if (data.targetName !== this.sourceName) {
  6303. return;
  6304. }
  6305. if (data.stream) {
  6306. this._processStreamMessage(data);
  6307. return;
  6308. }
  6309. if (data.callback) {
  6310. const callbackId = data.callbackId;
  6311. const capability = this.callbackCapabilities[callbackId];
  6312. if (!capability) {
  6313. throw new Error(`Cannot resolve callback ${callbackId}`);
  6314. }
  6315. delete this.callbackCapabilities[callbackId];
  6316. if (data.callback === CallbackKind.DATA) {
  6317. capability.resolve(data.data);
  6318. } else if (data.callback === CallbackKind.ERROR) {
  6319. capability.reject(wrapReason(data.reason));
  6320. } else {
  6321. throw new Error("Unexpected callback case");
  6322. }
  6323. return;
  6324. }
  6325. const action = this.actionHandler[data.action];
  6326. if (!action) {
  6327. throw new Error(`Unknown action from worker: ${data.action}`);
  6328. }
  6329. if (data.callbackId) {
  6330. const cbSourceName = this.sourceName;
  6331. const cbTargetName = data.sourceName;
  6332. new Promise(function (resolve) {
  6333. resolve(action(data.data));
  6334. }).then(function (result) {
  6335. comObj.postMessage({
  6336. sourceName: cbSourceName,
  6337. targetName: cbTargetName,
  6338. callback: CallbackKind.DATA,
  6339. callbackId: data.callbackId,
  6340. data: result
  6341. });
  6342. }, function (reason) {
  6343. comObj.postMessage({
  6344. sourceName: cbSourceName,
  6345. targetName: cbTargetName,
  6346. callback: CallbackKind.ERROR,
  6347. callbackId: data.callbackId,
  6348. reason: wrapReason(reason)
  6349. });
  6350. });
  6351. return;
  6352. }
  6353. if (data.streamId) {
  6354. this._createStreamSink(data);
  6355. return;
  6356. }
  6357. action(data.data);
  6358. };
  6359. comObj.addEventListener("message", this._onComObjOnMessage);
  6360. }
  6361. on(actionName, handler) {
  6362. const ah = this.actionHandler;
  6363. if (ah[actionName]) {
  6364. throw new Error(`There is already an actionName called "${actionName}"`);
  6365. }
  6366. ah[actionName] = handler;
  6367. }
  6368. send(actionName, data, transfers) {
  6369. this._postMessage({
  6370. sourceName: this.sourceName,
  6371. targetName: this.targetName,
  6372. action: actionName,
  6373. data
  6374. }, transfers);
  6375. }
  6376. sendWithPromise(actionName, data, transfers) {
  6377. const callbackId = this.callbackId++;
  6378. const capability = (0, _util.createPromiseCapability)();
  6379. this.callbackCapabilities[callbackId] = capability;
  6380. try {
  6381. this._postMessage({
  6382. sourceName: this.sourceName,
  6383. targetName: this.targetName,
  6384. action: actionName,
  6385. callbackId,
  6386. data
  6387. }, transfers);
  6388. } catch (ex) {
  6389. capability.reject(ex);
  6390. }
  6391. return capability.promise;
  6392. }
  6393. sendWithStream(actionName, data, queueingStrategy, transfers) {
  6394. const streamId = this.streamId++,
  6395. sourceName = this.sourceName,
  6396. targetName = this.targetName,
  6397. comObj = this.comObj;
  6398. return new ReadableStream({
  6399. start: controller => {
  6400. const startCapability = (0, _util.createPromiseCapability)();
  6401. this.streamControllers[streamId] = {
  6402. controller,
  6403. startCall: startCapability,
  6404. pullCall: null,
  6405. cancelCall: null,
  6406. isClosed: false
  6407. };
  6408. this._postMessage({
  6409. sourceName,
  6410. targetName,
  6411. action: actionName,
  6412. streamId,
  6413. data,
  6414. desiredSize: controller.desiredSize
  6415. }, transfers);
  6416. return startCapability.promise;
  6417. },
  6418. pull: controller => {
  6419. const pullCapability = (0, _util.createPromiseCapability)();
  6420. this.streamControllers[streamId].pullCall = pullCapability;
  6421. comObj.postMessage({
  6422. sourceName,
  6423. targetName,
  6424. stream: StreamKind.PULL,
  6425. streamId,
  6426. desiredSize: controller.desiredSize
  6427. });
  6428. return pullCapability.promise;
  6429. },
  6430. cancel: reason => {
  6431. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  6432. const cancelCapability = (0, _util.createPromiseCapability)();
  6433. this.streamControllers[streamId].cancelCall = cancelCapability;
  6434. this.streamControllers[streamId].isClosed = true;
  6435. comObj.postMessage({
  6436. sourceName,
  6437. targetName,
  6438. stream: StreamKind.CANCEL,
  6439. streamId,
  6440. reason: wrapReason(reason)
  6441. });
  6442. return cancelCapability.promise;
  6443. }
  6444. }, queueingStrategy);
  6445. }
  6446. _createStreamSink(data) {
  6447. const streamId = data.streamId,
  6448. sourceName = this.sourceName,
  6449. targetName = data.sourceName,
  6450. comObj = this.comObj;
  6451. const self = this,
  6452. action = this.actionHandler[data.action];
  6453. const streamSink = {
  6454. enqueue(chunk, size = 1, transfers) {
  6455. if (this.isCancelled) {
  6456. return;
  6457. }
  6458. const lastDesiredSize = this.desiredSize;
  6459. this.desiredSize -= size;
  6460. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  6461. this.sinkCapability = (0, _util.createPromiseCapability)();
  6462. this.ready = this.sinkCapability.promise;
  6463. }
  6464. self._postMessage({
  6465. sourceName,
  6466. targetName,
  6467. stream: StreamKind.ENQUEUE,
  6468. streamId,
  6469. chunk
  6470. }, transfers);
  6471. },
  6472. close() {
  6473. if (this.isCancelled) {
  6474. return;
  6475. }
  6476. this.isCancelled = true;
  6477. comObj.postMessage({
  6478. sourceName,
  6479. targetName,
  6480. stream: StreamKind.CLOSE,
  6481. streamId
  6482. });
  6483. delete self.streamSinks[streamId];
  6484. },
  6485. error(reason) {
  6486. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  6487. if (this.isCancelled) {
  6488. return;
  6489. }
  6490. this.isCancelled = true;
  6491. comObj.postMessage({
  6492. sourceName,
  6493. targetName,
  6494. stream: StreamKind.ERROR,
  6495. streamId,
  6496. reason: wrapReason(reason)
  6497. });
  6498. },
  6499. sinkCapability: (0, _util.createPromiseCapability)(),
  6500. onPull: null,
  6501. onCancel: null,
  6502. isCancelled: false,
  6503. desiredSize: data.desiredSize,
  6504. ready: null
  6505. };
  6506. streamSink.sinkCapability.resolve();
  6507. streamSink.ready = streamSink.sinkCapability.promise;
  6508. this.streamSinks[streamId] = streamSink;
  6509. new Promise(function (resolve) {
  6510. resolve(action(data.data, streamSink));
  6511. }).then(function () {
  6512. comObj.postMessage({
  6513. sourceName,
  6514. targetName,
  6515. stream: StreamKind.START_COMPLETE,
  6516. streamId,
  6517. success: true
  6518. });
  6519. }, function (reason) {
  6520. comObj.postMessage({
  6521. sourceName,
  6522. targetName,
  6523. stream: StreamKind.START_COMPLETE,
  6524. streamId,
  6525. reason: wrapReason(reason)
  6526. });
  6527. });
  6528. }
  6529. _processStreamMessage(data) {
  6530. const streamId = data.streamId,
  6531. sourceName = this.sourceName,
  6532. targetName = data.sourceName,
  6533. comObj = this.comObj;
  6534. const streamController = this.streamControllers[streamId],
  6535. streamSink = this.streamSinks[streamId];
  6536. switch (data.stream) {
  6537. case StreamKind.START_COMPLETE:
  6538. if (data.success) {
  6539. streamController.startCall.resolve();
  6540. } else {
  6541. streamController.startCall.reject(wrapReason(data.reason));
  6542. }
  6543. break;
  6544. case StreamKind.PULL_COMPLETE:
  6545. if (data.success) {
  6546. streamController.pullCall.resolve();
  6547. } else {
  6548. streamController.pullCall.reject(wrapReason(data.reason));
  6549. }
  6550. break;
  6551. case StreamKind.PULL:
  6552. if (!streamSink) {
  6553. comObj.postMessage({
  6554. sourceName,
  6555. targetName,
  6556. stream: StreamKind.PULL_COMPLETE,
  6557. streamId,
  6558. success: true
  6559. });
  6560. break;
  6561. }
  6562. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  6563. streamSink.sinkCapability.resolve();
  6564. }
  6565. streamSink.desiredSize = data.desiredSize;
  6566. new Promise(function (resolve) {
  6567. resolve(streamSink.onPull && streamSink.onPull());
  6568. }).then(function () {
  6569. comObj.postMessage({
  6570. sourceName,
  6571. targetName,
  6572. stream: StreamKind.PULL_COMPLETE,
  6573. streamId,
  6574. success: true
  6575. });
  6576. }, function (reason) {
  6577. comObj.postMessage({
  6578. sourceName,
  6579. targetName,
  6580. stream: StreamKind.PULL_COMPLETE,
  6581. streamId,
  6582. reason: wrapReason(reason)
  6583. });
  6584. });
  6585. break;
  6586. case StreamKind.ENQUEUE:
  6587. (0, _util.assert)(streamController, "enqueue should have stream controller");
  6588. if (streamController.isClosed) {
  6589. break;
  6590. }
  6591. streamController.controller.enqueue(data.chunk);
  6592. break;
  6593. case StreamKind.CLOSE:
  6594. (0, _util.assert)(streamController, "close should have stream controller");
  6595. if (streamController.isClosed) {
  6596. break;
  6597. }
  6598. streamController.isClosed = true;
  6599. streamController.controller.close();
  6600. this._deleteStreamController(streamController, streamId);
  6601. break;
  6602. case StreamKind.ERROR:
  6603. (0, _util.assert)(streamController, "error should have stream controller");
  6604. streamController.controller.error(wrapReason(data.reason));
  6605. this._deleteStreamController(streamController, streamId);
  6606. break;
  6607. case StreamKind.CANCEL_COMPLETE:
  6608. if (data.success) {
  6609. streamController.cancelCall.resolve();
  6610. } else {
  6611. streamController.cancelCall.reject(wrapReason(data.reason));
  6612. }
  6613. this._deleteStreamController(streamController, streamId);
  6614. break;
  6615. case StreamKind.CANCEL:
  6616. if (!streamSink) {
  6617. break;
  6618. }
  6619. new Promise(function (resolve) {
  6620. resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
  6621. }).then(function () {
  6622. comObj.postMessage({
  6623. sourceName,
  6624. targetName,
  6625. stream: StreamKind.CANCEL_COMPLETE,
  6626. streamId,
  6627. success: true
  6628. });
  6629. }, function (reason) {
  6630. comObj.postMessage({
  6631. sourceName,
  6632. targetName,
  6633. stream: StreamKind.CANCEL_COMPLETE,
  6634. streamId,
  6635. reason: wrapReason(reason)
  6636. });
  6637. });
  6638. streamSink.sinkCapability.reject(wrapReason(data.reason));
  6639. streamSink.isCancelled = true;
  6640. delete this.streamSinks[streamId];
  6641. break;
  6642. default:
  6643. throw new Error("Unexpected stream case");
  6644. }
  6645. }
  6646. async _deleteStreamController(streamController, streamId) {
  6647. await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
  6648. delete this.streamControllers[streamId];
  6649. }
  6650. _postMessage(message, transfers) {
  6651. if (transfers && this.postMessageTransfers) {
  6652. this.comObj.postMessage(message, transfers);
  6653. } else {
  6654. this.comObj.postMessage(message);
  6655. }
  6656. }
  6657. destroy() {
  6658. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  6659. }
  6660. }
  6661. exports.MessageHandler = MessageHandler;
  6662. /***/ }),
  6663. /* 14 */
  6664. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6665. Object.defineProperty(exports, "__esModule", ({
  6666. value: true
  6667. }));
  6668. exports.Metadata = void 0;
  6669. var _util = __w_pdfjs_require__(2);
  6670. class Metadata {
  6671. constructor({
  6672. parsedData,
  6673. rawData
  6674. }) {
  6675. this._metadataMap = parsedData;
  6676. this._data = rawData;
  6677. }
  6678. getRaw() {
  6679. return this._data;
  6680. }
  6681. get(name) {
  6682. return this._metadataMap.get(name) ?? null;
  6683. }
  6684. getAll() {
  6685. return (0, _util.objectFromMap)(this._metadataMap);
  6686. }
  6687. has(name) {
  6688. return this._metadataMap.has(name);
  6689. }
  6690. }
  6691. exports.Metadata = Metadata;
  6692. /***/ }),
  6693. /* 15 */
  6694. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6695. Object.defineProperty(exports, "__esModule", ({
  6696. value: true
  6697. }));
  6698. exports.OptionalContentConfig = void 0;
  6699. var _util = __w_pdfjs_require__(2);
  6700. class OptionalContentGroup {
  6701. constructor(name, intent) {
  6702. this.visible = true;
  6703. this.name = name;
  6704. this.intent = intent;
  6705. }
  6706. }
  6707. class OptionalContentConfig {
  6708. constructor(data) {
  6709. this.name = null;
  6710. this.creator = null;
  6711. this._order = null;
  6712. this._groups = new Map();
  6713. if (data === null) {
  6714. return;
  6715. }
  6716. this.name = data.name;
  6717. this.creator = data.creator;
  6718. this._order = data.order;
  6719. for (const group of data.groups) {
  6720. this._groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  6721. }
  6722. if (data.baseState === "OFF") {
  6723. for (const group of this._groups) {
  6724. group.visible = false;
  6725. }
  6726. }
  6727. for (const on of data.on) {
  6728. this._groups.get(on).visible = true;
  6729. }
  6730. for (const off of data.off) {
  6731. this._groups.get(off).visible = false;
  6732. }
  6733. }
  6734. _evaluateVisibilityExpression(array) {
  6735. const length = array.length;
  6736. if (length < 2) {
  6737. return true;
  6738. }
  6739. const operator = array[0];
  6740. for (let i = 1; i < length; i++) {
  6741. const element = array[i];
  6742. let state;
  6743. if (Array.isArray(element)) {
  6744. state = this._evaluateVisibilityExpression(element);
  6745. } else if (this._groups.has(element)) {
  6746. state = this._groups.get(element).visible;
  6747. } else {
  6748. (0, _util.warn)(`Optional content group not found: ${element}`);
  6749. return true;
  6750. }
  6751. switch (operator) {
  6752. case "And":
  6753. if (!state) {
  6754. return false;
  6755. }
  6756. break;
  6757. case "Or":
  6758. if (state) {
  6759. return true;
  6760. }
  6761. break;
  6762. case "Not":
  6763. return !state;
  6764. default:
  6765. return true;
  6766. }
  6767. }
  6768. return operator === "And";
  6769. }
  6770. isVisible(group) {
  6771. if (this._groups.size === 0) {
  6772. return true;
  6773. }
  6774. if (!group) {
  6775. (0, _util.warn)("Optional content group not defined.");
  6776. return true;
  6777. }
  6778. if (group.type === "OCG") {
  6779. if (!this._groups.has(group.id)) {
  6780. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  6781. return true;
  6782. }
  6783. return this._groups.get(group.id).visible;
  6784. } else if (group.type === "OCMD") {
  6785. if (group.expression) {
  6786. return this._evaluateVisibilityExpression(group.expression);
  6787. }
  6788. if (!group.policy || group.policy === "AnyOn") {
  6789. for (const id of group.ids) {
  6790. if (!this._groups.has(id)) {
  6791. (0, _util.warn)(`Optional content group not found: ${id}`);
  6792. return true;
  6793. }
  6794. if (this._groups.get(id).visible) {
  6795. return true;
  6796. }
  6797. }
  6798. return false;
  6799. } else if (group.policy === "AllOn") {
  6800. for (const id of group.ids) {
  6801. if (!this._groups.has(id)) {
  6802. (0, _util.warn)(`Optional content group not found: ${id}`);
  6803. return true;
  6804. }
  6805. if (!this._groups.get(id).visible) {
  6806. return false;
  6807. }
  6808. }
  6809. return true;
  6810. } else if (group.policy === "AnyOff") {
  6811. for (const id of group.ids) {
  6812. if (!this._groups.has(id)) {
  6813. (0, _util.warn)(`Optional content group not found: ${id}`);
  6814. return true;
  6815. }
  6816. if (!this._groups.get(id).visible) {
  6817. return true;
  6818. }
  6819. }
  6820. return false;
  6821. } else if (group.policy === "AllOff") {
  6822. for (const id of group.ids) {
  6823. if (!this._groups.has(id)) {
  6824. (0, _util.warn)(`Optional content group not found: ${id}`);
  6825. return true;
  6826. }
  6827. if (this._groups.get(id).visible) {
  6828. return false;
  6829. }
  6830. }
  6831. return true;
  6832. }
  6833. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  6834. return true;
  6835. }
  6836. (0, _util.warn)(`Unknown group type ${group.type}.`);
  6837. return true;
  6838. }
  6839. setVisibility(id, visible = true) {
  6840. if (!this._groups.has(id)) {
  6841. (0, _util.warn)(`Optional content group not found: ${id}`);
  6842. return;
  6843. }
  6844. this._groups.get(id).visible = !!visible;
  6845. }
  6846. getOrder() {
  6847. if (!this._groups.size) {
  6848. return null;
  6849. }
  6850. if (this._order) {
  6851. return this._order.slice();
  6852. }
  6853. return Array.from(this._groups.keys());
  6854. }
  6855. getGroups() {
  6856. return this._groups.size > 0 ? (0, _util.objectFromMap)(this._groups) : null;
  6857. }
  6858. getGroup(id) {
  6859. return this._groups.get(id) || null;
  6860. }
  6861. }
  6862. exports.OptionalContentConfig = OptionalContentConfig;
  6863. /***/ }),
  6864. /* 16 */
  6865. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6866. Object.defineProperty(exports, "__esModule", ({
  6867. value: true
  6868. }));
  6869. exports.PDFDataTransportStream = void 0;
  6870. var _util = __w_pdfjs_require__(2);
  6871. var _display_utils = __w_pdfjs_require__(1);
  6872. class PDFDataTransportStream {
  6873. constructor(params, pdfDataRangeTransport) {
  6874. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  6875. this._queuedChunks = [];
  6876. this._progressiveDone = params.progressiveDone || false;
  6877. this._contentDispositionFilename = params.contentDispositionFilename || null;
  6878. const initialData = params.initialData;
  6879. if (initialData?.length > 0) {
  6880. const buffer = new Uint8Array(initialData).buffer;
  6881. this._queuedChunks.push(buffer);
  6882. }
  6883. this._pdfDataRangeTransport = pdfDataRangeTransport;
  6884. this._isStreamingSupported = !params.disableStream;
  6885. this._isRangeSupported = !params.disableRange;
  6886. this._contentLength = params.length;
  6887. this._fullRequestReader = null;
  6888. this._rangeReaders = [];
  6889. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  6890. this._onReceiveData({
  6891. begin,
  6892. chunk
  6893. });
  6894. });
  6895. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  6896. this._onProgress({
  6897. loaded,
  6898. total
  6899. });
  6900. });
  6901. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  6902. this._onReceiveData({
  6903. chunk
  6904. });
  6905. });
  6906. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  6907. this._onProgressiveDone();
  6908. });
  6909. this._pdfDataRangeTransport.transportReady();
  6910. }
  6911. _onReceiveData(args) {
  6912. const buffer = new Uint8Array(args.chunk).buffer;
  6913. if (args.begin === undefined) {
  6914. if (this._fullRequestReader) {
  6915. this._fullRequestReader._enqueue(buffer);
  6916. } else {
  6917. this._queuedChunks.push(buffer);
  6918. }
  6919. } else {
  6920. const found = this._rangeReaders.some(function (rangeReader) {
  6921. if (rangeReader._begin !== args.begin) {
  6922. return false;
  6923. }
  6924. rangeReader._enqueue(buffer);
  6925. return true;
  6926. });
  6927. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  6928. }
  6929. }
  6930. get _progressiveDataLength() {
  6931. return this._fullRequestReader?._loaded ?? 0;
  6932. }
  6933. _onProgress(evt) {
  6934. if (evt.total === undefined) {
  6935. const firstReader = this._rangeReaders[0];
  6936. if (firstReader?.onProgress) {
  6937. firstReader.onProgress({
  6938. loaded: evt.loaded
  6939. });
  6940. }
  6941. } else {
  6942. const fullReader = this._fullRequestReader;
  6943. if (fullReader?.onProgress) {
  6944. fullReader.onProgress({
  6945. loaded: evt.loaded,
  6946. total: evt.total
  6947. });
  6948. }
  6949. }
  6950. }
  6951. _onProgressiveDone() {
  6952. if (this._fullRequestReader) {
  6953. this._fullRequestReader.progressiveDone();
  6954. }
  6955. this._progressiveDone = true;
  6956. }
  6957. _removeRangeReader(reader) {
  6958. const i = this._rangeReaders.indexOf(reader);
  6959. if (i >= 0) {
  6960. this._rangeReaders.splice(i, 1);
  6961. }
  6962. }
  6963. getFullReader() {
  6964. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  6965. const queuedChunks = this._queuedChunks;
  6966. this._queuedChunks = null;
  6967. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  6968. }
  6969. getRangeReader(begin, end) {
  6970. if (end <= this._progressiveDataLength) {
  6971. return null;
  6972. }
  6973. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  6974. this._pdfDataRangeTransport.requestDataRange(begin, end);
  6975. this._rangeReaders.push(reader);
  6976. return reader;
  6977. }
  6978. cancelAllRequests(reason) {
  6979. if (this._fullRequestReader) {
  6980. this._fullRequestReader.cancel(reason);
  6981. }
  6982. for (const reader of this._rangeReaders.slice(0)) {
  6983. reader.cancel(reason);
  6984. }
  6985. this._pdfDataRangeTransport.abort();
  6986. }
  6987. }
  6988. exports.PDFDataTransportStream = PDFDataTransportStream;
  6989. class PDFDataTransportStreamReader {
  6990. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  6991. this._stream = stream;
  6992. this._done = progressiveDone || false;
  6993. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  6994. this._queuedChunks = queuedChunks || [];
  6995. this._loaded = 0;
  6996. for (const chunk of this._queuedChunks) {
  6997. this._loaded += chunk.byteLength;
  6998. }
  6999. this._requests = [];
  7000. this._headersReady = Promise.resolve();
  7001. stream._fullRequestReader = this;
  7002. this.onProgress = null;
  7003. }
  7004. _enqueue(chunk) {
  7005. if (this._done) {
  7006. return;
  7007. }
  7008. if (this._requests.length > 0) {
  7009. const requestCapability = this._requests.shift();
  7010. requestCapability.resolve({
  7011. value: chunk,
  7012. done: false
  7013. });
  7014. } else {
  7015. this._queuedChunks.push(chunk);
  7016. }
  7017. this._loaded += chunk.byteLength;
  7018. }
  7019. get headersReady() {
  7020. return this._headersReady;
  7021. }
  7022. get filename() {
  7023. return this._filename;
  7024. }
  7025. get isRangeSupported() {
  7026. return this._stream._isRangeSupported;
  7027. }
  7028. get isStreamingSupported() {
  7029. return this._stream._isStreamingSupported;
  7030. }
  7031. get contentLength() {
  7032. return this._stream._contentLength;
  7033. }
  7034. async read() {
  7035. if (this._queuedChunks.length > 0) {
  7036. const chunk = this._queuedChunks.shift();
  7037. return {
  7038. value: chunk,
  7039. done: false
  7040. };
  7041. }
  7042. if (this._done) {
  7043. return {
  7044. value: undefined,
  7045. done: true
  7046. };
  7047. }
  7048. const requestCapability = (0, _util.createPromiseCapability)();
  7049. this._requests.push(requestCapability);
  7050. return requestCapability.promise;
  7051. }
  7052. cancel(reason) {
  7053. this._done = true;
  7054. for (const requestCapability of this._requests) {
  7055. requestCapability.resolve({
  7056. value: undefined,
  7057. done: true
  7058. });
  7059. }
  7060. this._requests.length = 0;
  7061. }
  7062. progressiveDone() {
  7063. if (this._done) {
  7064. return;
  7065. }
  7066. this._done = true;
  7067. }
  7068. }
  7069. class PDFDataTransportStreamRangeReader {
  7070. constructor(stream, begin, end) {
  7071. this._stream = stream;
  7072. this._begin = begin;
  7073. this._end = end;
  7074. this._queuedChunk = null;
  7075. this._requests = [];
  7076. this._done = false;
  7077. this.onProgress = null;
  7078. }
  7079. _enqueue(chunk) {
  7080. if (this._done) {
  7081. return;
  7082. }
  7083. if (this._requests.length === 0) {
  7084. this._queuedChunk = chunk;
  7085. } else {
  7086. const requestsCapability = this._requests.shift();
  7087. requestsCapability.resolve({
  7088. value: chunk,
  7089. done: false
  7090. });
  7091. for (const requestCapability of this._requests) {
  7092. requestCapability.resolve({
  7093. value: undefined,
  7094. done: true
  7095. });
  7096. }
  7097. this._requests.length = 0;
  7098. }
  7099. this._done = true;
  7100. this._stream._removeRangeReader(this);
  7101. }
  7102. get isStreamingSupported() {
  7103. return false;
  7104. }
  7105. async read() {
  7106. if (this._queuedChunk) {
  7107. const chunk = this._queuedChunk;
  7108. this._queuedChunk = null;
  7109. return {
  7110. value: chunk,
  7111. done: false
  7112. };
  7113. }
  7114. if (this._done) {
  7115. return {
  7116. value: undefined,
  7117. done: true
  7118. };
  7119. }
  7120. const requestCapability = (0, _util.createPromiseCapability)();
  7121. this._requests.push(requestCapability);
  7122. return requestCapability.promise;
  7123. }
  7124. cancel(reason) {
  7125. this._done = true;
  7126. for (const requestCapability of this._requests) {
  7127. requestCapability.resolve({
  7128. value: undefined,
  7129. done: true
  7130. });
  7131. }
  7132. this._requests.length = 0;
  7133. this._stream._removeRangeReader(this);
  7134. }
  7135. }
  7136. /***/ }),
  7137. /* 17 */
  7138. /***/ ((__unused_webpack_module, exports) => {
  7139. Object.defineProperty(exports, "__esModule", ({
  7140. value: true
  7141. }));
  7142. exports.XfaText = void 0;
  7143. class XfaText {
  7144. static textContent(xfa) {
  7145. const items = [];
  7146. const output = {
  7147. items,
  7148. styles: Object.create(null)
  7149. };
  7150. function walk(node) {
  7151. if (!node) {
  7152. return;
  7153. }
  7154. let str = null;
  7155. const name = node.name;
  7156. if (name === "#text") {
  7157. str = node.value;
  7158. } else if (!XfaText.shouldBuildText(name)) {
  7159. return;
  7160. } else if (node?.attributes?.textContent) {
  7161. str = node.attributes.textContent;
  7162. } else if (node.value) {
  7163. str = node.value;
  7164. }
  7165. if (str !== null) {
  7166. items.push({
  7167. str
  7168. });
  7169. }
  7170. if (!node.children) {
  7171. return;
  7172. }
  7173. for (const child of node.children) {
  7174. walk(child);
  7175. }
  7176. }
  7177. walk(xfa);
  7178. return output;
  7179. }
  7180. static shouldBuildText(name) {
  7181. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  7182. }
  7183. }
  7184. exports.XfaText = XfaText;
  7185. /***/ }),
  7186. /* 18 */
  7187. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7188. Object.defineProperty(exports, "__esModule", ({
  7189. value: true
  7190. }));
  7191. exports.AnnotationLayer = void 0;
  7192. var _util = __w_pdfjs_require__(2);
  7193. var _display_utils = __w_pdfjs_require__(1);
  7194. var _annotation_storage = __w_pdfjs_require__(9);
  7195. var _scripting_utils = __w_pdfjs_require__(19);
  7196. const DEFAULT_TAB_INDEX = 1000;
  7197. const GetElementsByNameSet = new WeakSet();
  7198. class AnnotationElementFactory {
  7199. static create(parameters) {
  7200. const subtype = parameters.data.annotationType;
  7201. switch (subtype) {
  7202. case _util.AnnotationType.LINK:
  7203. return new LinkAnnotationElement(parameters);
  7204. case _util.AnnotationType.TEXT:
  7205. return new TextAnnotationElement(parameters);
  7206. case _util.AnnotationType.WIDGET:
  7207. const fieldType = parameters.data.fieldType;
  7208. switch (fieldType) {
  7209. case "Tx":
  7210. return new TextWidgetAnnotationElement(parameters);
  7211. case "Btn":
  7212. if (parameters.data.radioButton) {
  7213. return new RadioButtonWidgetAnnotationElement(parameters);
  7214. } else if (parameters.data.checkBox) {
  7215. return new CheckboxWidgetAnnotationElement(parameters);
  7216. }
  7217. return new PushButtonWidgetAnnotationElement(parameters);
  7218. case "Ch":
  7219. return new ChoiceWidgetAnnotationElement(parameters);
  7220. }
  7221. return new WidgetAnnotationElement(parameters);
  7222. case _util.AnnotationType.POPUP:
  7223. return new PopupAnnotationElement(parameters);
  7224. case _util.AnnotationType.FREETEXT:
  7225. return new FreeTextAnnotationElement(parameters);
  7226. case _util.AnnotationType.LINE:
  7227. return new LineAnnotationElement(parameters);
  7228. case _util.AnnotationType.SQUARE:
  7229. return new SquareAnnotationElement(parameters);
  7230. case _util.AnnotationType.CIRCLE:
  7231. return new CircleAnnotationElement(parameters);
  7232. case _util.AnnotationType.POLYLINE:
  7233. return new PolylineAnnotationElement(parameters);
  7234. case _util.AnnotationType.CARET:
  7235. return new CaretAnnotationElement(parameters);
  7236. case _util.AnnotationType.INK:
  7237. return new InkAnnotationElement(parameters);
  7238. case _util.AnnotationType.POLYGON:
  7239. return new PolygonAnnotationElement(parameters);
  7240. case _util.AnnotationType.HIGHLIGHT:
  7241. return new HighlightAnnotationElement(parameters);
  7242. case _util.AnnotationType.UNDERLINE:
  7243. return new UnderlineAnnotationElement(parameters);
  7244. case _util.AnnotationType.SQUIGGLY:
  7245. return new SquigglyAnnotationElement(parameters);
  7246. case _util.AnnotationType.STRIKEOUT:
  7247. return new StrikeOutAnnotationElement(parameters);
  7248. case _util.AnnotationType.STAMP:
  7249. return new StampAnnotationElement(parameters);
  7250. case _util.AnnotationType.FILEATTACHMENT:
  7251. return new FileAttachmentAnnotationElement(parameters);
  7252. default:
  7253. return new AnnotationElement(parameters);
  7254. }
  7255. }
  7256. }
  7257. class AnnotationElement {
  7258. constructor(parameters, {
  7259. isRenderable = false,
  7260. ignoreBorder = false,
  7261. createQuadrilaterals = false
  7262. } = {}) {
  7263. this.isRenderable = isRenderable;
  7264. this.data = parameters.data;
  7265. this.layer = parameters.layer;
  7266. this.page = parameters.page;
  7267. this.viewport = parameters.viewport;
  7268. this.linkService = parameters.linkService;
  7269. this.downloadManager = parameters.downloadManager;
  7270. this.imageResourcesPath = parameters.imageResourcesPath;
  7271. this.renderForms = parameters.renderForms;
  7272. this.svgFactory = parameters.svgFactory;
  7273. this.annotationStorage = parameters.annotationStorage;
  7274. this.enableScripting = parameters.enableScripting;
  7275. this.hasJSActions = parameters.hasJSActions;
  7276. this._fieldObjects = parameters.fieldObjects;
  7277. this._mouseState = parameters.mouseState;
  7278. if (isRenderable) {
  7279. this.container = this._createContainer(ignoreBorder);
  7280. }
  7281. if (createQuadrilaterals) {
  7282. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  7283. }
  7284. }
  7285. _createContainer(ignoreBorder = false) {
  7286. const data = this.data,
  7287. page = this.page,
  7288. viewport = this.viewport;
  7289. const container = document.createElement("section");
  7290. let width = data.rect[2] - data.rect[0];
  7291. let height = data.rect[3] - data.rect[1];
  7292. container.setAttribute("data-annotation-id", data.id);
  7293. 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]]);
  7294. container.style.transform = `matrix(${viewport.transform.join(",")})`;
  7295. container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
  7296. if (!ignoreBorder && data.borderStyle.width > 0) {
  7297. container.style.borderWidth = `${data.borderStyle.width}px`;
  7298. if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
  7299. width -= 2 * data.borderStyle.width;
  7300. height -= 2 * data.borderStyle.width;
  7301. }
  7302. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  7303. const verticalRadius = data.borderStyle.verticalCornerRadius;
  7304. if (horizontalRadius > 0 || verticalRadius > 0) {
  7305. const radius = `${horizontalRadius}px / ${verticalRadius}px`;
  7306. container.style.borderRadius = radius;
  7307. }
  7308. switch (data.borderStyle.style) {
  7309. case _util.AnnotationBorderStyleType.SOLID:
  7310. container.style.borderStyle = "solid";
  7311. break;
  7312. case _util.AnnotationBorderStyleType.DASHED:
  7313. container.style.borderStyle = "dashed";
  7314. break;
  7315. case _util.AnnotationBorderStyleType.BEVELED:
  7316. (0, _util.warn)("Unimplemented border style: beveled");
  7317. break;
  7318. case _util.AnnotationBorderStyleType.INSET:
  7319. (0, _util.warn)("Unimplemented border style: inset");
  7320. break;
  7321. case _util.AnnotationBorderStyleType.UNDERLINE:
  7322. container.style.borderBottomStyle = "solid";
  7323. break;
  7324. default:
  7325. break;
  7326. }
  7327. const borderColor = data.borderColor || data.color || null;
  7328. if (borderColor) {
  7329. container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  7330. } else {
  7331. container.style.borderWidth = 0;
  7332. }
  7333. }
  7334. container.style.left = `${rect[0]}px`;
  7335. container.style.top = `${rect[1]}px`;
  7336. container.style.width = `${width}px`;
  7337. container.style.height = `${height}px`;
  7338. return container;
  7339. }
  7340. _createQuadrilaterals(ignoreBorder = false) {
  7341. if (!this.data.quadPoints) {
  7342. return null;
  7343. }
  7344. const quadrilaterals = [];
  7345. const savedRect = this.data.rect;
  7346. for (const quadPoint of this.data.quadPoints) {
  7347. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  7348. quadrilaterals.push(this._createContainer(ignoreBorder));
  7349. }
  7350. this.data.rect = savedRect;
  7351. return quadrilaterals;
  7352. }
  7353. _createPopup(trigger, data) {
  7354. let container = this.container;
  7355. if (this.quadrilaterals) {
  7356. trigger = trigger || this.quadrilaterals;
  7357. container = this.quadrilaterals[0];
  7358. }
  7359. if (!trigger) {
  7360. trigger = document.createElement("div");
  7361. trigger.style.height = container.style.height;
  7362. trigger.style.width = container.style.width;
  7363. container.appendChild(trigger);
  7364. }
  7365. const popupElement = new PopupElement({
  7366. container,
  7367. trigger,
  7368. color: data.color,
  7369. titleObj: data.titleObj,
  7370. modificationDate: data.modificationDate,
  7371. contentsObj: data.contentsObj,
  7372. hideWrapper: true
  7373. });
  7374. const popup = popupElement.render();
  7375. popup.style.left = container.style.width;
  7376. container.appendChild(popup);
  7377. }
  7378. _renderQuadrilaterals(className) {
  7379. for (const quadrilateral of this.quadrilaterals) {
  7380. quadrilateral.className = className;
  7381. }
  7382. return this.quadrilaterals;
  7383. }
  7384. render() {
  7385. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  7386. }
  7387. _getElementsByName(name, skipId = null) {
  7388. const fields = [];
  7389. if (this._fieldObjects) {
  7390. const fieldObj = this._fieldObjects[name];
  7391. if (fieldObj) {
  7392. for (const {
  7393. page,
  7394. id,
  7395. exportValues
  7396. } of fieldObj) {
  7397. if (page === -1) {
  7398. continue;
  7399. }
  7400. if (id === skipId) {
  7401. continue;
  7402. }
  7403. const exportValue = typeof exportValues === "string" ? exportValues : null;
  7404. const domElement = document.getElementById(id);
  7405. if (domElement && !GetElementsByNameSet.has(domElement)) {
  7406. (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
  7407. continue;
  7408. }
  7409. fields.push({
  7410. id,
  7411. exportValue,
  7412. domElement
  7413. });
  7414. }
  7415. }
  7416. return fields;
  7417. }
  7418. for (const domElement of document.getElementsByName(name)) {
  7419. const {
  7420. id,
  7421. exportValue
  7422. } = domElement;
  7423. if (id === skipId) {
  7424. continue;
  7425. }
  7426. if (!GetElementsByNameSet.has(domElement)) {
  7427. continue;
  7428. }
  7429. fields.push({
  7430. id,
  7431. exportValue,
  7432. domElement
  7433. });
  7434. }
  7435. return fields;
  7436. }
  7437. static get platform() {
  7438. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  7439. return (0, _util.shadow)(this, "platform", {
  7440. isWin: platform.includes("Win"),
  7441. isMac: platform.includes("Mac")
  7442. });
  7443. }
  7444. }
  7445. class LinkAnnotationElement extends AnnotationElement {
  7446. constructor(parameters) {
  7447. const isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action || parameters.data.isTooltipOnly || parameters.data.resetForm || parameters.data.actions && (parameters.data.actions.Action || parameters.data.actions["Mouse Up"] || parameters.data.actions["Mouse Down"]));
  7448. super(parameters, {
  7449. isRenderable,
  7450. createQuadrilaterals: true
  7451. });
  7452. }
  7453. render() {
  7454. const {
  7455. data,
  7456. linkService
  7457. } = this;
  7458. const link = document.createElement("a");
  7459. if (data.url) {
  7460. if (!linkService.addLinkAttributes) {
  7461. (0, _util.warn)("LinkAnnotationElement.render - missing `addLinkAttributes`-method on the `linkService`-instance.");
  7462. }
  7463. linkService.addLinkAttributes?.(link, data.url, data.newWindow);
  7464. } else if (data.action) {
  7465. this._bindNamedAction(link, data.action);
  7466. } else if (data.dest) {
  7467. this._bindLink(link, data.dest);
  7468. } else {
  7469. let hasClickAction = false;
  7470. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  7471. hasClickAction = true;
  7472. this._bindJSAction(link, data);
  7473. }
  7474. if (data.resetForm) {
  7475. this._bindResetFormAction(link, data.resetForm);
  7476. } else if (!hasClickAction) {
  7477. this._bindLink(link, "");
  7478. }
  7479. }
  7480. if (this.quadrilaterals) {
  7481. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  7482. const linkElement = index === 0 ? link : link.cloneNode();
  7483. quadrilateral.appendChild(linkElement);
  7484. return quadrilateral;
  7485. });
  7486. }
  7487. this.container.className = "linkAnnotation";
  7488. this.container.appendChild(link);
  7489. return this.container;
  7490. }
  7491. _bindLink(link, destination) {
  7492. link.href = this.linkService.getDestinationHash(destination);
  7493. link.onclick = () => {
  7494. if (destination) {
  7495. this.linkService.goToDestination(destination);
  7496. }
  7497. return false;
  7498. };
  7499. if (destination || destination === "") {
  7500. link.className = "internalLink";
  7501. }
  7502. }
  7503. _bindNamedAction(link, action) {
  7504. link.href = this.linkService.getAnchorUrl("");
  7505. link.onclick = () => {
  7506. this.linkService.executeNamedAction(action);
  7507. return false;
  7508. };
  7509. link.className = "internalLink";
  7510. }
  7511. _bindJSAction(link, data) {
  7512. link.href = this.linkService.getAnchorUrl("");
  7513. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  7514. for (const name of Object.keys(data.actions)) {
  7515. const jsName = map.get(name);
  7516. if (!jsName) {
  7517. continue;
  7518. }
  7519. link[jsName] = () => {
  7520. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7521. source: this,
  7522. detail: {
  7523. id: data.id,
  7524. name
  7525. }
  7526. });
  7527. return false;
  7528. };
  7529. }
  7530. if (!link.onclick) {
  7531. link.onclick = () => false;
  7532. }
  7533. link.className = "internalLink";
  7534. }
  7535. _bindResetFormAction(link, resetForm) {
  7536. const otherClickAction = link.onclick;
  7537. if (!otherClickAction) {
  7538. link.href = this.linkService.getAnchorUrl("");
  7539. }
  7540. link.className = "internalLink";
  7541. if (!this._fieldObjects) {
  7542. (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  7543. if (!otherClickAction) {
  7544. link.onclick = () => false;
  7545. }
  7546. return;
  7547. }
  7548. link.onclick = () => {
  7549. if (otherClickAction) {
  7550. otherClickAction();
  7551. }
  7552. const {
  7553. fields: resetFormFields,
  7554. refs: resetFormRefs,
  7555. include
  7556. } = resetForm;
  7557. const allFields = [];
  7558. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  7559. const fieldIds = new Set(resetFormRefs);
  7560. for (const fieldName of resetFormFields) {
  7561. const fields = this._fieldObjects[fieldName] || [];
  7562. for (const {
  7563. id
  7564. } of fields) {
  7565. fieldIds.add(id);
  7566. }
  7567. }
  7568. for (const fields of Object.values(this._fieldObjects)) {
  7569. for (const field of fields) {
  7570. if (fieldIds.has(field.id) === include) {
  7571. allFields.push(field);
  7572. }
  7573. }
  7574. }
  7575. } else {
  7576. for (const fields of Object.values(this._fieldObjects)) {
  7577. allFields.push(...fields);
  7578. }
  7579. }
  7580. const storage = this.annotationStorage;
  7581. const allIds = [];
  7582. for (const field of allFields) {
  7583. const {
  7584. id
  7585. } = field;
  7586. allIds.push(id);
  7587. switch (field.type) {
  7588. case "text":
  7589. {
  7590. const value = field.defaultValue || "";
  7591. storage.setValue(id, {
  7592. value,
  7593. valueAsString: value
  7594. });
  7595. break;
  7596. }
  7597. case "checkbox":
  7598. case "radiobutton":
  7599. {
  7600. const value = field.defaultValue === field.exportValues;
  7601. storage.setValue(id, {
  7602. value
  7603. });
  7604. break;
  7605. }
  7606. case "combobox":
  7607. case "listbox":
  7608. {
  7609. const value = field.defaultValue || "";
  7610. storage.setValue(id, {
  7611. value
  7612. });
  7613. break;
  7614. }
  7615. default:
  7616. continue;
  7617. }
  7618. const domElement = document.getElementById(id);
  7619. if (!domElement || !GetElementsByNameSet.has(domElement)) {
  7620. continue;
  7621. }
  7622. domElement.dispatchEvent(new Event("resetform"));
  7623. }
  7624. if (this.enableScripting) {
  7625. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7626. source: this,
  7627. detail: {
  7628. id: "app",
  7629. ids: allIds,
  7630. name: "ResetForm"
  7631. }
  7632. });
  7633. }
  7634. return false;
  7635. };
  7636. }
  7637. }
  7638. class TextAnnotationElement extends AnnotationElement {
  7639. constructor(parameters) {
  7640. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  7641. super(parameters, {
  7642. isRenderable
  7643. });
  7644. }
  7645. render() {
  7646. this.container.className = "textAnnotation";
  7647. const image = document.createElement("img");
  7648. image.style.height = this.container.style.height;
  7649. image.style.width = this.container.style.width;
  7650. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  7651. image.alt = "[{{type}} Annotation]";
  7652. image.dataset.l10nId = "text_annotation_type";
  7653. image.dataset.l10nArgs = JSON.stringify({
  7654. type: this.data.name
  7655. });
  7656. if (!this.data.hasPopup) {
  7657. this._createPopup(image, this.data);
  7658. }
  7659. this.container.appendChild(image);
  7660. return this.container;
  7661. }
  7662. }
  7663. class WidgetAnnotationElement extends AnnotationElement {
  7664. render() {
  7665. if (this.data.alternativeText) {
  7666. this.container.title = this.data.alternativeText;
  7667. }
  7668. return this.container;
  7669. }
  7670. _getKeyModifier(event) {
  7671. const {
  7672. isWin,
  7673. isMac
  7674. } = AnnotationElement.platform;
  7675. return isWin && event.ctrlKey || isMac && event.metaKey;
  7676. }
  7677. _setEventListener(element, baseName, eventName, valueGetter) {
  7678. if (baseName.includes("mouse")) {
  7679. element.addEventListener(baseName, event => {
  7680. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7681. source: this,
  7682. detail: {
  7683. id: this.data.id,
  7684. name: eventName,
  7685. value: valueGetter(event),
  7686. shift: event.shiftKey,
  7687. modifier: this._getKeyModifier(event)
  7688. }
  7689. });
  7690. });
  7691. } else {
  7692. element.addEventListener(baseName, event => {
  7693. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7694. source: this,
  7695. detail: {
  7696. id: this.data.id,
  7697. name: eventName,
  7698. value: event.target.checked
  7699. }
  7700. });
  7701. });
  7702. }
  7703. }
  7704. _setEventListeners(element, names, getter) {
  7705. for (const [baseName, eventName] of names) {
  7706. if (eventName === "Action" || this.data.actions?.[eventName]) {
  7707. this._setEventListener(element, baseName, eventName, getter);
  7708. }
  7709. }
  7710. }
  7711. _setBackgroundColor(element) {
  7712. const color = this.data.backgroundColor || null;
  7713. element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  7714. }
  7715. _dispatchEventFromSandbox(actions, jsEvent) {
  7716. const setColor = (jsName, styleName, event) => {
  7717. const color = event.detail[jsName];
  7718. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  7719. };
  7720. const commonActions = {
  7721. display: event => {
  7722. const hidden = event.detail.display % 2 === 1;
  7723. event.target.style.visibility = hidden ? "hidden" : "visible";
  7724. this.annotationStorage.setValue(this.data.id, {
  7725. hidden,
  7726. print: event.detail.display === 0 || event.detail.display === 3
  7727. });
  7728. },
  7729. print: event => {
  7730. this.annotationStorage.setValue(this.data.id, {
  7731. print: event.detail.print
  7732. });
  7733. },
  7734. hidden: event => {
  7735. event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
  7736. this.annotationStorage.setValue(this.data.id, {
  7737. hidden: event.detail.hidden
  7738. });
  7739. },
  7740. focus: event => {
  7741. setTimeout(() => event.target.focus({
  7742. preventScroll: false
  7743. }), 0);
  7744. },
  7745. userName: event => {
  7746. event.target.title = event.detail.userName;
  7747. },
  7748. readonly: event => {
  7749. if (event.detail.readonly) {
  7750. event.target.setAttribute("readonly", "");
  7751. } else {
  7752. event.target.removeAttribute("readonly");
  7753. }
  7754. },
  7755. required: event => {
  7756. if (event.detail.required) {
  7757. event.target.setAttribute("required", "");
  7758. } else {
  7759. event.target.removeAttribute("required");
  7760. }
  7761. },
  7762. bgColor: event => {
  7763. setColor("bgColor", "backgroundColor", event);
  7764. },
  7765. fillColor: event => {
  7766. setColor("fillColor", "backgroundColor", event);
  7767. },
  7768. fgColor: event => {
  7769. setColor("fgColor", "color", event);
  7770. },
  7771. textColor: event => {
  7772. setColor("textColor", "color", event);
  7773. },
  7774. borderColor: event => {
  7775. setColor("borderColor", "borderColor", event);
  7776. },
  7777. strokeColor: event => {
  7778. setColor("strokeColor", "borderColor", event);
  7779. }
  7780. };
  7781. for (const name of Object.keys(jsEvent.detail)) {
  7782. const action = actions[name] || commonActions[name];
  7783. if (action) {
  7784. action(jsEvent);
  7785. }
  7786. }
  7787. }
  7788. }
  7789. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  7790. constructor(parameters) {
  7791. const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  7792. super(parameters, {
  7793. isRenderable
  7794. });
  7795. }
  7796. setPropertyOnSiblings(base, key, value, keyInStorage) {
  7797. const storage = this.annotationStorage;
  7798. for (const element of this._getElementsByName(base.name, base.id)) {
  7799. if (element.domElement) {
  7800. element.domElement[key] = value;
  7801. }
  7802. storage.setValue(element.id, {
  7803. [keyInStorage]: value
  7804. });
  7805. }
  7806. }
  7807. render() {
  7808. const storage = this.annotationStorage;
  7809. const id = this.data.id;
  7810. this.container.className = "textWidgetAnnotation";
  7811. let element = null;
  7812. if (this.renderForms) {
  7813. const storedData = storage.getValue(id, {
  7814. value: this.data.fieldValue,
  7815. valueAsString: this.data.fieldValue
  7816. });
  7817. const textContent = storedData.valueAsString || storedData.value || "";
  7818. const elementData = {
  7819. userValue: null,
  7820. formattedValue: null,
  7821. beforeInputSelectionRange: null,
  7822. beforeInputValue: null
  7823. };
  7824. if (this.data.multiLine) {
  7825. element = document.createElement("textarea");
  7826. element.textContent = textContent;
  7827. } else {
  7828. element = document.createElement("input");
  7829. element.type = "text";
  7830. element.setAttribute("value", textContent);
  7831. }
  7832. GetElementsByNameSet.add(element);
  7833. element.disabled = this.data.readOnly;
  7834. element.name = this.data.fieldName;
  7835. element.tabIndex = DEFAULT_TAB_INDEX;
  7836. elementData.userValue = textContent;
  7837. element.setAttribute("id", id);
  7838. element.addEventListener("input", event => {
  7839. storage.setValue(id, {
  7840. value: event.target.value
  7841. });
  7842. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  7843. });
  7844. element.addEventListener("resetform", event => {
  7845. const defaultValue = this.data.defaultFieldValue || "";
  7846. element.value = elementData.userValue = defaultValue;
  7847. delete elementData.formattedValue;
  7848. });
  7849. let blurListener = event => {
  7850. if (elementData.formattedValue) {
  7851. event.target.value = elementData.formattedValue;
  7852. }
  7853. event.target.scrollLeft = 0;
  7854. elementData.beforeInputSelectionRange = null;
  7855. };
  7856. if (this.enableScripting && this.hasJSActions) {
  7857. element.addEventListener("focus", event => {
  7858. if (elementData.userValue) {
  7859. event.target.value = elementData.userValue;
  7860. }
  7861. });
  7862. element.addEventListener("updatefromsandbox", jsEvent => {
  7863. const actions = {
  7864. value(event) {
  7865. elementData.userValue = event.detail.value || "";
  7866. storage.setValue(id, {
  7867. value: elementData.userValue.toString()
  7868. });
  7869. if (!elementData.formattedValue) {
  7870. event.target.value = elementData.userValue;
  7871. }
  7872. },
  7873. valueAsString(event) {
  7874. elementData.formattedValue = event.detail.valueAsString || "";
  7875. if (event.target !== document.activeElement) {
  7876. event.target.value = elementData.formattedValue;
  7877. }
  7878. storage.setValue(id, {
  7879. formattedValue: elementData.formattedValue
  7880. });
  7881. },
  7882. selRange(event) {
  7883. const [selStart, selEnd] = event.detail.selRange;
  7884. if (selStart >= 0 && selEnd < event.target.value.length) {
  7885. event.target.setSelectionRange(selStart, selEnd);
  7886. }
  7887. }
  7888. };
  7889. this._dispatchEventFromSandbox(actions, jsEvent);
  7890. });
  7891. element.addEventListener("keydown", event => {
  7892. elementData.beforeInputValue = event.target.value;
  7893. let commitKey = -1;
  7894. if (event.key === "Escape") {
  7895. commitKey = 0;
  7896. } else if (event.key === "Enter") {
  7897. commitKey = 2;
  7898. } else if (event.key === "Tab") {
  7899. commitKey = 3;
  7900. }
  7901. if (commitKey === -1) {
  7902. return;
  7903. }
  7904. elementData.userValue = event.target.value;
  7905. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7906. source: this,
  7907. detail: {
  7908. id,
  7909. name: "Keystroke",
  7910. value: event.target.value,
  7911. willCommit: true,
  7912. commitKey,
  7913. selStart: event.target.selectionStart,
  7914. selEnd: event.target.selectionEnd
  7915. }
  7916. });
  7917. });
  7918. const _blurListener = blurListener;
  7919. blurListener = null;
  7920. element.addEventListener("blur", event => {
  7921. if (this._mouseState.isDown) {
  7922. elementData.userValue = event.target.value;
  7923. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7924. source: this,
  7925. detail: {
  7926. id,
  7927. name: "Keystroke",
  7928. value: event.target.value,
  7929. willCommit: true,
  7930. commitKey: 1,
  7931. selStart: event.target.selectionStart,
  7932. selEnd: event.target.selectionEnd
  7933. }
  7934. });
  7935. }
  7936. _blurListener(event);
  7937. });
  7938. element.addEventListener("mousedown", event => {
  7939. elementData.beforeInputValue = event.target.value;
  7940. elementData.beforeInputSelectionRange = null;
  7941. });
  7942. element.addEventListener("keyup", event => {
  7943. if (event.target.selectionStart === event.target.selectionEnd) {
  7944. elementData.beforeInputSelectionRange = null;
  7945. }
  7946. });
  7947. element.addEventListener("select", event => {
  7948. elementData.beforeInputSelectionRange = [event.target.selectionStart, event.target.selectionEnd];
  7949. });
  7950. if (this.data.actions?.Keystroke) {
  7951. element.addEventListener("input", event => {
  7952. let selStart = -1;
  7953. let selEnd = -1;
  7954. if (elementData.beforeInputSelectionRange) {
  7955. [selStart, selEnd] = elementData.beforeInputSelectionRange;
  7956. }
  7957. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7958. source: this,
  7959. detail: {
  7960. id,
  7961. name: "Keystroke",
  7962. value: elementData.beforeInputValue,
  7963. change: event.data,
  7964. willCommit: false,
  7965. selStart,
  7966. selEnd
  7967. }
  7968. });
  7969. });
  7970. }
  7971. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  7972. }
  7973. if (blurListener) {
  7974. element.addEventListener("blur", blurListener);
  7975. }
  7976. if (this.data.maxLen !== null) {
  7977. element.maxLength = this.data.maxLen;
  7978. }
  7979. if (this.data.comb) {
  7980. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  7981. const combWidth = fieldWidth / this.data.maxLen;
  7982. element.classList.add("comb");
  7983. element.style.letterSpacing = `calc(${combWidth}px - 1ch)`;
  7984. }
  7985. } else {
  7986. element = document.createElement("div");
  7987. element.textContent = this.data.fieldValue;
  7988. element.style.verticalAlign = "middle";
  7989. element.style.display = "table-cell";
  7990. }
  7991. this._setTextStyle(element);
  7992. this._setBackgroundColor(element);
  7993. this.container.appendChild(element);
  7994. return this.container;
  7995. }
  7996. _setTextStyle(element) {
  7997. const TEXT_ALIGNMENT = ["left", "center", "right"];
  7998. const {
  7999. fontSize,
  8000. fontColor
  8001. } = this.data.defaultAppearanceData;
  8002. const style = element.style;
  8003. if (fontSize) {
  8004. style.fontSize = `${fontSize}px`;
  8005. }
  8006. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  8007. if (this.data.textAlignment !== null) {
  8008. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  8009. }
  8010. }
  8011. }
  8012. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  8013. constructor(parameters) {
  8014. super(parameters, {
  8015. isRenderable: parameters.renderForms
  8016. });
  8017. }
  8018. render() {
  8019. const storage = this.annotationStorage;
  8020. const data = this.data;
  8021. const id = data.id;
  8022. let value = storage.getValue(id, {
  8023. value: data.exportValue === data.fieldValue
  8024. }).value;
  8025. if (typeof value === "string") {
  8026. value = value !== "Off";
  8027. storage.setValue(id, {
  8028. value
  8029. });
  8030. }
  8031. this.container.className = "buttonWidgetAnnotation checkBox";
  8032. const element = document.createElement("input");
  8033. GetElementsByNameSet.add(element);
  8034. element.disabled = data.readOnly;
  8035. element.type = "checkbox";
  8036. element.name = data.fieldName;
  8037. if (value) {
  8038. element.setAttribute("checked", true);
  8039. }
  8040. element.setAttribute("id", id);
  8041. element.setAttribute("exportValue", data.exportValue);
  8042. element.tabIndex = DEFAULT_TAB_INDEX;
  8043. element.addEventListener("change", event => {
  8044. const {
  8045. name,
  8046. checked
  8047. } = event.target;
  8048. for (const checkbox of this._getElementsByName(name, id)) {
  8049. const curChecked = checked && checkbox.exportValue === data.exportValue;
  8050. if (checkbox.domElement) {
  8051. checkbox.domElement.checked = curChecked;
  8052. }
  8053. storage.setValue(checkbox.id, {
  8054. value: curChecked
  8055. });
  8056. }
  8057. storage.setValue(id, {
  8058. value: checked
  8059. });
  8060. });
  8061. element.addEventListener("resetform", event => {
  8062. const defaultValue = data.defaultFieldValue || "Off";
  8063. event.target.checked = defaultValue === data.exportValue;
  8064. });
  8065. if (this.enableScripting && this.hasJSActions) {
  8066. element.addEventListener("updatefromsandbox", jsEvent => {
  8067. const actions = {
  8068. value(event) {
  8069. event.target.checked = event.detail.value !== "Off";
  8070. storage.setValue(id, {
  8071. value: event.target.checked
  8072. });
  8073. }
  8074. };
  8075. this._dispatchEventFromSandbox(actions, jsEvent);
  8076. });
  8077. 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);
  8078. }
  8079. this._setBackgroundColor(element);
  8080. this.container.appendChild(element);
  8081. return this.container;
  8082. }
  8083. }
  8084. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  8085. constructor(parameters) {
  8086. super(parameters, {
  8087. isRenderable: parameters.renderForms
  8088. });
  8089. }
  8090. render() {
  8091. this.container.className = "buttonWidgetAnnotation radioButton";
  8092. const storage = this.annotationStorage;
  8093. const data = this.data;
  8094. const id = data.id;
  8095. let value = storage.getValue(id, {
  8096. value: data.fieldValue === data.buttonValue
  8097. }).value;
  8098. if (typeof value === "string") {
  8099. value = value !== data.buttonValue;
  8100. storage.setValue(id, {
  8101. value
  8102. });
  8103. }
  8104. const element = document.createElement("input");
  8105. GetElementsByNameSet.add(element);
  8106. element.disabled = data.readOnly;
  8107. element.type = "radio";
  8108. element.name = data.fieldName;
  8109. if (value) {
  8110. element.setAttribute("checked", true);
  8111. }
  8112. element.setAttribute("id", id);
  8113. element.tabIndex = DEFAULT_TAB_INDEX;
  8114. element.addEventListener("change", event => {
  8115. const {
  8116. name,
  8117. checked
  8118. } = event.target;
  8119. for (const radio of this._getElementsByName(name, id)) {
  8120. storage.setValue(radio.id, {
  8121. value: false
  8122. });
  8123. }
  8124. storage.setValue(id, {
  8125. value: checked
  8126. });
  8127. });
  8128. element.addEventListener("resetform", event => {
  8129. const defaultValue = data.defaultFieldValue;
  8130. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  8131. });
  8132. if (this.enableScripting && this.hasJSActions) {
  8133. const pdfButtonValue = data.buttonValue;
  8134. element.addEventListener("updatefromsandbox", jsEvent => {
  8135. const actions = {
  8136. value: event => {
  8137. const checked = pdfButtonValue === event.detail.value;
  8138. for (const radio of this._getElementsByName(event.target.name)) {
  8139. const curChecked = checked && radio.id === id;
  8140. if (radio.domElement) {
  8141. radio.domElement.checked = curChecked;
  8142. }
  8143. storage.setValue(radio.id, {
  8144. value: curChecked
  8145. });
  8146. }
  8147. }
  8148. };
  8149. this._dispatchEventFromSandbox(actions, jsEvent);
  8150. });
  8151. 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);
  8152. }
  8153. this._setBackgroundColor(element);
  8154. this.container.appendChild(element);
  8155. return this.container;
  8156. }
  8157. }
  8158. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  8159. render() {
  8160. const container = super.render();
  8161. container.className = "buttonWidgetAnnotation pushButton";
  8162. if (this.data.alternativeText) {
  8163. container.title = this.data.alternativeText;
  8164. }
  8165. return container;
  8166. }
  8167. }
  8168. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  8169. constructor(parameters) {
  8170. super(parameters, {
  8171. isRenderable: parameters.renderForms
  8172. });
  8173. }
  8174. render() {
  8175. this.container.className = "choiceWidgetAnnotation";
  8176. const storage = this.annotationStorage;
  8177. const id = this.data.id;
  8178. storage.getValue(id, {
  8179. value: this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : undefined
  8180. });
  8181. let {
  8182. fontSize
  8183. } = this.data.defaultAppearanceData;
  8184. if (!fontSize) {
  8185. fontSize = 9;
  8186. }
  8187. const fontSizeStyle = `calc(${fontSize}px * var(--zoom-factor))`;
  8188. const selectElement = document.createElement("select");
  8189. GetElementsByNameSet.add(selectElement);
  8190. selectElement.disabled = this.data.readOnly;
  8191. selectElement.name = this.data.fieldName;
  8192. selectElement.setAttribute("id", id);
  8193. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  8194. selectElement.style.fontSize = `${fontSize}px`;
  8195. if (!this.data.combo) {
  8196. selectElement.size = this.data.options.length;
  8197. if (this.data.multiSelect) {
  8198. selectElement.multiple = true;
  8199. }
  8200. }
  8201. selectElement.addEventListener("resetform", event => {
  8202. const defaultValue = this.data.defaultFieldValue;
  8203. for (const option of selectElement.options) {
  8204. option.selected = option.value === defaultValue;
  8205. }
  8206. });
  8207. for (const option of this.data.options) {
  8208. const optionElement = document.createElement("option");
  8209. optionElement.textContent = option.displayValue;
  8210. optionElement.value = option.exportValue;
  8211. if (this.data.combo) {
  8212. optionElement.style.fontSize = fontSizeStyle;
  8213. }
  8214. if (this.data.fieldValue.includes(option.exportValue)) {
  8215. optionElement.setAttribute("selected", true);
  8216. }
  8217. selectElement.appendChild(optionElement);
  8218. }
  8219. const getValue = (event, isExport) => {
  8220. const name = isExport ? "value" : "textContent";
  8221. const options = event.target.options;
  8222. if (!event.target.multiple) {
  8223. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  8224. }
  8225. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  8226. };
  8227. const getItems = event => {
  8228. const options = event.target.options;
  8229. return Array.prototype.map.call(options, option => {
  8230. return {
  8231. displayValue: option.textContent,
  8232. exportValue: option.value
  8233. };
  8234. });
  8235. };
  8236. if (this.enableScripting && this.hasJSActions) {
  8237. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  8238. const actions = {
  8239. value(event) {
  8240. const value = event.detail.value;
  8241. const values = new Set(Array.isArray(value) ? value : [value]);
  8242. for (const option of selectElement.options) {
  8243. option.selected = values.has(option.value);
  8244. }
  8245. storage.setValue(id, {
  8246. value: getValue(event, true)
  8247. });
  8248. },
  8249. multipleSelection(event) {
  8250. selectElement.multiple = true;
  8251. },
  8252. remove(event) {
  8253. const options = selectElement.options;
  8254. const index = event.detail.remove;
  8255. options[index].selected = false;
  8256. selectElement.remove(index);
  8257. if (options.length > 0) {
  8258. const i = Array.prototype.findIndex.call(options, option => option.selected);
  8259. if (i === -1) {
  8260. options[0].selected = true;
  8261. }
  8262. }
  8263. storage.setValue(id, {
  8264. value: getValue(event, true),
  8265. items: getItems(event)
  8266. });
  8267. },
  8268. clear(event) {
  8269. while (selectElement.length !== 0) {
  8270. selectElement.remove(0);
  8271. }
  8272. storage.setValue(id, {
  8273. value: null,
  8274. items: []
  8275. });
  8276. },
  8277. insert(event) {
  8278. const {
  8279. index,
  8280. displayValue,
  8281. exportValue
  8282. } = event.detail.insert;
  8283. const optionElement = document.createElement("option");
  8284. optionElement.textContent = displayValue;
  8285. optionElement.value = exportValue;
  8286. selectElement.insertBefore(optionElement, selectElement.children[index]);
  8287. storage.setValue(id, {
  8288. value: getValue(event, true),
  8289. items: getItems(event)
  8290. });
  8291. },
  8292. items(event) {
  8293. const {
  8294. items
  8295. } = event.detail;
  8296. while (selectElement.length !== 0) {
  8297. selectElement.remove(0);
  8298. }
  8299. for (const item of items) {
  8300. const {
  8301. displayValue,
  8302. exportValue
  8303. } = item;
  8304. const optionElement = document.createElement("option");
  8305. optionElement.textContent = displayValue;
  8306. optionElement.value = exportValue;
  8307. selectElement.appendChild(optionElement);
  8308. }
  8309. if (selectElement.options.length > 0) {
  8310. selectElement.options[0].selected = true;
  8311. }
  8312. storage.setValue(id, {
  8313. value: getValue(event, true),
  8314. items: getItems(event)
  8315. });
  8316. },
  8317. indices(event) {
  8318. const indices = new Set(event.detail.indices);
  8319. for (const option of event.target.options) {
  8320. option.selected = indices.has(option.index);
  8321. }
  8322. storage.setValue(id, {
  8323. value: getValue(event, true)
  8324. });
  8325. },
  8326. editable(event) {
  8327. event.target.disabled = !event.detail.editable;
  8328. }
  8329. };
  8330. this._dispatchEventFromSandbox(actions, jsEvent);
  8331. });
  8332. selectElement.addEventListener("input", event => {
  8333. const exportValue = getValue(event, true);
  8334. const value = getValue(event, false);
  8335. storage.setValue(id, {
  8336. value: exportValue
  8337. });
  8338. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  8339. source: this,
  8340. detail: {
  8341. id,
  8342. name: "Keystroke",
  8343. value,
  8344. changeEx: exportValue,
  8345. willCommit: true,
  8346. commitKey: 1,
  8347. keyDown: false
  8348. }
  8349. });
  8350. });
  8351. 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);
  8352. } else {
  8353. selectElement.addEventListener("input", function (event) {
  8354. storage.setValue(id, {
  8355. value: getValue(event)
  8356. });
  8357. });
  8358. }
  8359. this._setBackgroundColor(selectElement);
  8360. this.container.appendChild(selectElement);
  8361. return this.container;
  8362. }
  8363. }
  8364. class PopupAnnotationElement extends AnnotationElement {
  8365. constructor(parameters) {
  8366. const isRenderable = !!(parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8367. super(parameters, {
  8368. isRenderable
  8369. });
  8370. }
  8371. render() {
  8372. const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"];
  8373. this.container.className = "popupAnnotation";
  8374. if (IGNORE_TYPES.includes(this.data.parentType)) {
  8375. return this.container;
  8376. }
  8377. const selector = `[data-annotation-id="${this.data.parentId}"]`;
  8378. const parentElements = this.layer.querySelectorAll(selector);
  8379. if (parentElements.length === 0) {
  8380. return this.container;
  8381. }
  8382. const popup = new PopupElement({
  8383. container: this.container,
  8384. trigger: Array.from(parentElements),
  8385. color: this.data.color,
  8386. titleObj: this.data.titleObj,
  8387. modificationDate: this.data.modificationDate,
  8388. contentsObj: this.data.contentsObj
  8389. });
  8390. const page = this.page;
  8391. 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]]);
  8392. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  8393. const popupTop = rect[1];
  8394. this.container.style.transformOrigin = `${-popupLeft}px ${-popupTop}px`;
  8395. this.container.style.left = `${popupLeft}px`;
  8396. this.container.style.top = `${popupTop}px`;
  8397. this.container.appendChild(popup.render());
  8398. return this.container;
  8399. }
  8400. }
  8401. class PopupElement {
  8402. constructor(parameters) {
  8403. this.container = parameters.container;
  8404. this.trigger = parameters.trigger;
  8405. this.color = parameters.color;
  8406. this.titleObj = parameters.titleObj;
  8407. this.modificationDate = parameters.modificationDate;
  8408. this.contentsObj = parameters.contentsObj;
  8409. this.hideWrapper = parameters.hideWrapper || false;
  8410. this.pinned = false;
  8411. }
  8412. render() {
  8413. const BACKGROUND_ENLIGHT = 0.7;
  8414. const wrapper = document.createElement("div");
  8415. wrapper.className = "popupWrapper";
  8416. this.hideElement = this.hideWrapper ? wrapper : this.container;
  8417. this.hideElement.hidden = true;
  8418. const popup = document.createElement("div");
  8419. popup.className = "popup";
  8420. const color = this.color;
  8421. if (color) {
  8422. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  8423. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  8424. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  8425. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  8426. }
  8427. const title = document.createElement("h1");
  8428. title.dir = this.titleObj.dir;
  8429. title.textContent = this.titleObj.str;
  8430. popup.appendChild(title);
  8431. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  8432. if (dateObject) {
  8433. const modificationDate = document.createElement("span");
  8434. modificationDate.textContent = "{{date}}, {{time}}";
  8435. modificationDate.dataset.l10nId = "annotation_date_string";
  8436. modificationDate.dataset.l10nArgs = JSON.stringify({
  8437. date: dateObject.toLocaleDateString(),
  8438. time: dateObject.toLocaleTimeString()
  8439. });
  8440. popup.appendChild(modificationDate);
  8441. }
  8442. const contents = this._formatContents(this.contentsObj);
  8443. popup.appendChild(contents);
  8444. if (!Array.isArray(this.trigger)) {
  8445. this.trigger = [this.trigger];
  8446. }
  8447. for (const element of this.trigger) {
  8448. element.addEventListener("click", this._toggle.bind(this));
  8449. element.addEventListener("mouseover", this._show.bind(this, false));
  8450. element.addEventListener("mouseout", this._hide.bind(this, false));
  8451. }
  8452. popup.addEventListener("click", this._hide.bind(this, true));
  8453. wrapper.appendChild(popup);
  8454. return wrapper;
  8455. }
  8456. _formatContents({
  8457. str,
  8458. dir
  8459. }) {
  8460. const p = document.createElement("p");
  8461. p.dir = dir;
  8462. const lines = str.split(/(?:\r\n?|\n)/);
  8463. for (let i = 0, ii = lines.length; i < ii; ++i) {
  8464. const line = lines[i];
  8465. p.appendChild(document.createTextNode(line));
  8466. if (i < ii - 1) {
  8467. p.appendChild(document.createElement("br"));
  8468. }
  8469. }
  8470. return p;
  8471. }
  8472. _toggle() {
  8473. if (this.pinned) {
  8474. this._hide(true);
  8475. } else {
  8476. this._show(true);
  8477. }
  8478. }
  8479. _show(pin = false) {
  8480. if (pin) {
  8481. this.pinned = true;
  8482. }
  8483. if (this.hideElement.hidden) {
  8484. this.hideElement.hidden = false;
  8485. this.container.style.zIndex += 1;
  8486. }
  8487. }
  8488. _hide(unpin = true) {
  8489. if (unpin) {
  8490. this.pinned = false;
  8491. }
  8492. if (!this.hideElement.hidden && !this.pinned) {
  8493. this.hideElement.hidden = true;
  8494. this.container.style.zIndex -= 1;
  8495. }
  8496. }
  8497. }
  8498. class FreeTextAnnotationElement extends AnnotationElement {
  8499. constructor(parameters) {
  8500. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8501. super(parameters, {
  8502. isRenderable,
  8503. ignoreBorder: true
  8504. });
  8505. }
  8506. render() {
  8507. this.container.className = "freeTextAnnotation";
  8508. if (!this.data.hasPopup) {
  8509. this._createPopup(null, this.data);
  8510. }
  8511. return this.container;
  8512. }
  8513. }
  8514. class LineAnnotationElement extends AnnotationElement {
  8515. constructor(parameters) {
  8516. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8517. super(parameters, {
  8518. isRenderable,
  8519. ignoreBorder: true
  8520. });
  8521. }
  8522. render() {
  8523. this.container.className = "lineAnnotation";
  8524. const data = this.data;
  8525. const width = data.rect[2] - data.rect[0];
  8526. const height = data.rect[3] - data.rect[1];
  8527. const svg = this.svgFactory.create(width, height);
  8528. const line = this.svgFactory.createElement("svg:line");
  8529. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  8530. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  8531. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  8532. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  8533. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  8534. line.setAttribute("stroke", "transparent");
  8535. svg.appendChild(line);
  8536. this.container.append(svg);
  8537. this._createPopup(line, data);
  8538. return this.container;
  8539. }
  8540. }
  8541. class SquareAnnotationElement extends AnnotationElement {
  8542. constructor(parameters) {
  8543. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8544. super(parameters, {
  8545. isRenderable,
  8546. ignoreBorder: true
  8547. });
  8548. }
  8549. render() {
  8550. this.container.className = "squareAnnotation";
  8551. const data = this.data;
  8552. const width = data.rect[2] - data.rect[0];
  8553. const height = data.rect[3] - data.rect[1];
  8554. const svg = this.svgFactory.create(width, height);
  8555. const borderWidth = data.borderStyle.width;
  8556. const square = this.svgFactory.createElement("svg:rect");
  8557. square.setAttribute("x", borderWidth / 2);
  8558. square.setAttribute("y", borderWidth / 2);
  8559. square.setAttribute("width", width - borderWidth);
  8560. square.setAttribute("height", height - borderWidth);
  8561. square.setAttribute("stroke-width", borderWidth || 1);
  8562. square.setAttribute("stroke", "transparent");
  8563. square.setAttribute("fill", "none");
  8564. svg.appendChild(square);
  8565. this.container.append(svg);
  8566. this._createPopup(square, data);
  8567. return this.container;
  8568. }
  8569. }
  8570. class CircleAnnotationElement extends AnnotationElement {
  8571. constructor(parameters) {
  8572. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8573. super(parameters, {
  8574. isRenderable,
  8575. ignoreBorder: true
  8576. });
  8577. }
  8578. render() {
  8579. this.container.className = "circleAnnotation";
  8580. const data = this.data;
  8581. const width = data.rect[2] - data.rect[0];
  8582. const height = data.rect[3] - data.rect[1];
  8583. const svg = this.svgFactory.create(width, height);
  8584. const borderWidth = data.borderStyle.width;
  8585. const circle = this.svgFactory.createElement("svg:ellipse");
  8586. circle.setAttribute("cx", width / 2);
  8587. circle.setAttribute("cy", height / 2);
  8588. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  8589. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  8590. circle.setAttribute("stroke-width", borderWidth || 1);
  8591. circle.setAttribute("stroke", "transparent");
  8592. circle.setAttribute("fill", "none");
  8593. svg.appendChild(circle);
  8594. this.container.append(svg);
  8595. this._createPopup(circle, data);
  8596. return this.container;
  8597. }
  8598. }
  8599. class PolylineAnnotationElement extends AnnotationElement {
  8600. constructor(parameters) {
  8601. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8602. super(parameters, {
  8603. isRenderable,
  8604. ignoreBorder: true
  8605. });
  8606. this.containerClassName = "polylineAnnotation";
  8607. this.svgElementName = "svg:polyline";
  8608. }
  8609. render() {
  8610. this.container.className = this.containerClassName;
  8611. const data = this.data;
  8612. const width = data.rect[2] - data.rect[0];
  8613. const height = data.rect[3] - data.rect[1];
  8614. const svg = this.svgFactory.create(width, height);
  8615. let points = [];
  8616. for (const coordinate of data.vertices) {
  8617. const x = coordinate.x - data.rect[0];
  8618. const y = data.rect[3] - coordinate.y;
  8619. points.push(x + "," + y);
  8620. }
  8621. points = points.join(" ");
  8622. const polyline = this.svgFactory.createElement(this.svgElementName);
  8623. polyline.setAttribute("points", points);
  8624. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  8625. polyline.setAttribute("stroke", "transparent");
  8626. polyline.setAttribute("fill", "none");
  8627. svg.appendChild(polyline);
  8628. this.container.append(svg);
  8629. this._createPopup(polyline, data);
  8630. return this.container;
  8631. }
  8632. }
  8633. class PolygonAnnotationElement extends PolylineAnnotationElement {
  8634. constructor(parameters) {
  8635. super(parameters);
  8636. this.containerClassName = "polygonAnnotation";
  8637. this.svgElementName = "svg:polygon";
  8638. }
  8639. }
  8640. class CaretAnnotationElement extends AnnotationElement {
  8641. constructor(parameters) {
  8642. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8643. super(parameters, {
  8644. isRenderable,
  8645. ignoreBorder: true
  8646. });
  8647. }
  8648. render() {
  8649. this.container.className = "caretAnnotation";
  8650. if (!this.data.hasPopup) {
  8651. this._createPopup(null, this.data);
  8652. }
  8653. return this.container;
  8654. }
  8655. }
  8656. class InkAnnotationElement extends AnnotationElement {
  8657. constructor(parameters) {
  8658. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8659. super(parameters, {
  8660. isRenderable,
  8661. ignoreBorder: true
  8662. });
  8663. this.containerClassName = "inkAnnotation";
  8664. this.svgElementName = "svg:polyline";
  8665. }
  8666. render() {
  8667. this.container.className = this.containerClassName;
  8668. const data = this.data;
  8669. const width = data.rect[2] - data.rect[0];
  8670. const height = data.rect[3] - data.rect[1];
  8671. const svg = this.svgFactory.create(width, height);
  8672. for (const inkList of data.inkLists) {
  8673. let points = [];
  8674. for (const coordinate of inkList) {
  8675. const x = coordinate.x - data.rect[0];
  8676. const y = data.rect[3] - coordinate.y;
  8677. points.push(`${x},${y}`);
  8678. }
  8679. points = points.join(" ");
  8680. const polyline = this.svgFactory.createElement(this.svgElementName);
  8681. polyline.setAttribute("points", points);
  8682. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  8683. polyline.setAttribute("stroke", "transparent");
  8684. polyline.setAttribute("fill", "none");
  8685. this._createPopup(polyline, data);
  8686. svg.appendChild(polyline);
  8687. }
  8688. this.container.append(svg);
  8689. return this.container;
  8690. }
  8691. }
  8692. class HighlightAnnotationElement extends AnnotationElement {
  8693. constructor(parameters) {
  8694. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8695. super(parameters, {
  8696. isRenderable,
  8697. ignoreBorder: true,
  8698. createQuadrilaterals: true
  8699. });
  8700. }
  8701. render() {
  8702. if (!this.data.hasPopup) {
  8703. this._createPopup(null, this.data);
  8704. }
  8705. if (this.quadrilaterals) {
  8706. return this._renderQuadrilaterals("highlightAnnotation");
  8707. }
  8708. this.container.className = "highlightAnnotation";
  8709. return this.container;
  8710. }
  8711. }
  8712. class UnderlineAnnotationElement extends AnnotationElement {
  8713. constructor(parameters) {
  8714. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8715. super(parameters, {
  8716. isRenderable,
  8717. ignoreBorder: true,
  8718. createQuadrilaterals: true
  8719. });
  8720. }
  8721. render() {
  8722. if (!this.data.hasPopup) {
  8723. this._createPopup(null, this.data);
  8724. }
  8725. if (this.quadrilaterals) {
  8726. return this._renderQuadrilaterals("underlineAnnotation");
  8727. }
  8728. this.container.className = "underlineAnnotation";
  8729. return this.container;
  8730. }
  8731. }
  8732. class SquigglyAnnotationElement extends AnnotationElement {
  8733. constructor(parameters) {
  8734. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8735. super(parameters, {
  8736. isRenderable,
  8737. ignoreBorder: true,
  8738. createQuadrilaterals: true
  8739. });
  8740. }
  8741. render() {
  8742. if (!this.data.hasPopup) {
  8743. this._createPopup(null, this.data);
  8744. }
  8745. if (this.quadrilaterals) {
  8746. return this._renderQuadrilaterals("squigglyAnnotation");
  8747. }
  8748. this.container.className = "squigglyAnnotation";
  8749. return this.container;
  8750. }
  8751. }
  8752. class StrikeOutAnnotationElement extends AnnotationElement {
  8753. constructor(parameters) {
  8754. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8755. super(parameters, {
  8756. isRenderable,
  8757. ignoreBorder: true,
  8758. createQuadrilaterals: true
  8759. });
  8760. }
  8761. render() {
  8762. if (!this.data.hasPopup) {
  8763. this._createPopup(null, this.data);
  8764. }
  8765. if (this.quadrilaterals) {
  8766. return this._renderQuadrilaterals("strikeoutAnnotation");
  8767. }
  8768. this.container.className = "strikeoutAnnotation";
  8769. return this.container;
  8770. }
  8771. }
  8772. class StampAnnotationElement extends AnnotationElement {
  8773. constructor(parameters) {
  8774. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str);
  8775. super(parameters, {
  8776. isRenderable,
  8777. ignoreBorder: true
  8778. });
  8779. }
  8780. render() {
  8781. this.container.className = "stampAnnotation";
  8782. if (!this.data.hasPopup) {
  8783. this._createPopup(null, this.data);
  8784. }
  8785. return this.container;
  8786. }
  8787. }
  8788. class FileAttachmentAnnotationElement extends AnnotationElement {
  8789. constructor(parameters) {
  8790. super(parameters, {
  8791. isRenderable: true
  8792. });
  8793. const {
  8794. filename,
  8795. content
  8796. } = this.data.file;
  8797. this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
  8798. this.content = content;
  8799. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  8800. source: this,
  8801. id: (0, _util.stringToPDFString)(filename),
  8802. filename,
  8803. content
  8804. });
  8805. }
  8806. render() {
  8807. this.container.className = "fileAttachmentAnnotation";
  8808. const trigger = document.createElement("div");
  8809. trigger.style.height = this.container.style.height;
  8810. trigger.style.width = this.container.style.width;
  8811. trigger.addEventListener("dblclick", this._download.bind(this));
  8812. if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str)) {
  8813. this._createPopup(trigger, this.data);
  8814. }
  8815. this.container.appendChild(trigger);
  8816. return this.container;
  8817. }
  8818. _download() {
  8819. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  8820. }
  8821. }
  8822. class AnnotationLayer {
  8823. static render(parameters) {
  8824. const sortedAnnotations = [],
  8825. popupAnnotations = [];
  8826. for (const data of parameters.annotations) {
  8827. if (!data) {
  8828. continue;
  8829. }
  8830. if (data.annotationType === _util.AnnotationType.POPUP) {
  8831. popupAnnotations.push(data);
  8832. continue;
  8833. }
  8834. sortedAnnotations.push(data);
  8835. }
  8836. if (popupAnnotations.length) {
  8837. sortedAnnotations.push(...popupAnnotations);
  8838. }
  8839. for (const data of sortedAnnotations) {
  8840. const element = AnnotationElementFactory.create({
  8841. data,
  8842. layer: parameters.div,
  8843. page: parameters.page,
  8844. viewport: parameters.viewport,
  8845. linkService: parameters.linkService,
  8846. downloadManager: parameters.downloadManager,
  8847. imageResourcesPath: parameters.imageResourcesPath || "",
  8848. renderForms: parameters.renderForms !== false,
  8849. svgFactory: new _display_utils.DOMSVGFactory(),
  8850. annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
  8851. enableScripting: parameters.enableScripting,
  8852. hasJSActions: parameters.hasJSActions,
  8853. fieldObjects: parameters.fieldObjects,
  8854. mouseState: parameters.mouseState || {
  8855. isDown: false
  8856. }
  8857. });
  8858. if (element.isRenderable) {
  8859. const rendered = element.render();
  8860. if (data.hidden) {
  8861. rendered.style.visibility = "hidden";
  8862. }
  8863. if (Array.isArray(rendered)) {
  8864. for (const renderedElement of rendered) {
  8865. parameters.div.appendChild(renderedElement);
  8866. }
  8867. } else {
  8868. if (element instanceof PopupAnnotationElement) {
  8869. parameters.div.prepend(rendered);
  8870. } else {
  8871. parameters.div.appendChild(rendered);
  8872. }
  8873. }
  8874. }
  8875. }
  8876. }
  8877. static update(parameters) {
  8878. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  8879. for (const data of parameters.annotations) {
  8880. const elements = parameters.div.querySelectorAll(`[data-annotation-id="${data.id}"]`);
  8881. if (elements) {
  8882. for (const element of elements) {
  8883. element.style.transform = transform;
  8884. }
  8885. }
  8886. }
  8887. parameters.div.hidden = false;
  8888. }
  8889. }
  8890. exports.AnnotationLayer = AnnotationLayer;
  8891. /***/ }),
  8892. /* 19 */
  8893. /***/ ((__unused_webpack_module, exports) => {
  8894. Object.defineProperty(exports, "__esModule", ({
  8895. value: true
  8896. }));
  8897. exports.ColorConverters = void 0;
  8898. function makeColorComp(n) {
  8899. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  8900. }
  8901. class ColorConverters {
  8902. static CMYK_G([c, y, m, k]) {
  8903. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  8904. }
  8905. static G_CMYK([g]) {
  8906. return ["CMYK", 0, 0, 0, 1 - g];
  8907. }
  8908. static G_RGB([g]) {
  8909. return ["RGB", g, g, g];
  8910. }
  8911. static G_HTML([g]) {
  8912. const G = makeColorComp(g);
  8913. return `#${G}${G}${G}`;
  8914. }
  8915. static RGB_G([r, g, b]) {
  8916. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  8917. }
  8918. static RGB_HTML([r, g, b]) {
  8919. const R = makeColorComp(r);
  8920. const G = makeColorComp(g);
  8921. const B = makeColorComp(b);
  8922. return `#${R}${G}${B}`;
  8923. }
  8924. static T_HTML() {
  8925. return "#00000000";
  8926. }
  8927. static CMYK_RGB([c, y, m, k]) {
  8928. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  8929. }
  8930. static CMYK_HTML(components) {
  8931. return this.RGB_HTML(this.CMYK_RGB(components));
  8932. }
  8933. static RGB_CMYK([r, g, b]) {
  8934. const c = 1 - r;
  8935. const m = 1 - g;
  8936. const y = 1 - b;
  8937. const k = Math.min(c, m, y);
  8938. return ["CMYK", c, m, y, k];
  8939. }
  8940. }
  8941. exports.ColorConverters = ColorConverters;
  8942. /***/ }),
  8943. /* 20 */
  8944. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8945. Object.defineProperty(exports, "__esModule", ({
  8946. value: true
  8947. }));
  8948. exports.renderTextLayer = renderTextLayer;
  8949. var _util = __w_pdfjs_require__(2);
  8950. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  8951. const DEFAULT_FONT_SIZE = 30;
  8952. const DEFAULT_FONT_ASCENT = 0.8;
  8953. const ascentCache = new Map();
  8954. const AllWhitespaceRegexp = /^\s+$/g;
  8955. function getAscent(fontFamily, ctx) {
  8956. const cachedAscent = ascentCache.get(fontFamily);
  8957. if (cachedAscent) {
  8958. return cachedAscent;
  8959. }
  8960. ctx.save();
  8961. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  8962. const metrics = ctx.measureText("");
  8963. let ascent = metrics.fontBoundingBoxAscent;
  8964. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  8965. if (ascent) {
  8966. ctx.restore();
  8967. const ratio = ascent / (ascent + descent);
  8968. ascentCache.set(fontFamily, ratio);
  8969. return ratio;
  8970. }
  8971. ctx.strokeStyle = "red";
  8972. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8973. ctx.strokeText("g", 0, 0);
  8974. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8975. descent = 0;
  8976. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  8977. if (pixels[i] > 0) {
  8978. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  8979. break;
  8980. }
  8981. }
  8982. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8983. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  8984. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8985. ascent = 0;
  8986. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  8987. if (pixels[i] > 0) {
  8988. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  8989. break;
  8990. }
  8991. }
  8992. ctx.restore();
  8993. if (ascent) {
  8994. const ratio = ascent / (ascent + descent);
  8995. ascentCache.set(fontFamily, ratio);
  8996. return ratio;
  8997. }
  8998. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  8999. return DEFAULT_FONT_ASCENT;
  9000. }
  9001. function appendText(task, geom, styles, ctx) {
  9002. const textDiv = document.createElement("span");
  9003. const textDivProperties = task._enhanceTextSelection ? {
  9004. angle: 0,
  9005. canvasWidth: 0,
  9006. hasText: geom.str !== "",
  9007. hasEOL: geom.hasEOL,
  9008. originalTransform: null,
  9009. paddingBottom: 0,
  9010. paddingLeft: 0,
  9011. paddingRight: 0,
  9012. paddingTop: 0,
  9013. scale: 1
  9014. } : {
  9015. angle: 0,
  9016. canvasWidth: 0,
  9017. hasText: geom.str !== "",
  9018. hasEOL: geom.hasEOL
  9019. };
  9020. task._textDivs.push(textDiv);
  9021. const tx = _util.Util.transform(task._viewport.transform, geom.transform);
  9022. let angle = Math.atan2(tx[1], tx[0]);
  9023. const style = styles[geom.fontName];
  9024. if (style.vertical) {
  9025. angle += Math.PI / 2;
  9026. }
  9027. const fontHeight = Math.hypot(tx[2], tx[3]);
  9028. const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
  9029. let left, top;
  9030. if (angle === 0) {
  9031. left = tx[4];
  9032. top = tx[5] - fontAscent;
  9033. } else {
  9034. left = tx[4] + fontAscent * Math.sin(angle);
  9035. top = tx[5] - fontAscent * Math.cos(angle);
  9036. }
  9037. textDiv.style.left = `${left}px`;
  9038. textDiv.style.top = `${top}px`;
  9039. textDiv.style.fontSize = `${fontHeight}px`;
  9040. textDiv.style.fontFamily = style.fontFamily;
  9041. textDiv.setAttribute("role", "presentation");
  9042. textDiv.textContent = geom.str;
  9043. textDiv.dir = geom.dir;
  9044. if (task._fontInspectorEnabled) {
  9045. textDiv.dataset.fontName = geom.fontName;
  9046. }
  9047. if (angle !== 0) {
  9048. textDivProperties.angle = angle * (180 / Math.PI);
  9049. }
  9050. let shouldScaleText = false;
  9051. if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) {
  9052. shouldScaleText = true;
  9053. } else if (geom.transform[0] !== geom.transform[3]) {
  9054. const absScaleX = Math.abs(geom.transform[0]),
  9055. absScaleY = Math.abs(geom.transform[3]);
  9056. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  9057. shouldScaleText = true;
  9058. }
  9059. }
  9060. if (shouldScaleText) {
  9061. if (style.vertical) {
  9062. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  9063. } else {
  9064. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  9065. }
  9066. }
  9067. task._textDivProperties.set(textDiv, textDivProperties);
  9068. if (task._textContentStream) {
  9069. task._layoutText(textDiv);
  9070. }
  9071. if (task._enhanceTextSelection && textDivProperties.hasText) {
  9072. let angleCos = 1,
  9073. angleSin = 0;
  9074. if (angle !== 0) {
  9075. angleCos = Math.cos(angle);
  9076. angleSin = Math.sin(angle);
  9077. }
  9078. const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  9079. const divHeight = fontHeight;
  9080. let m, b;
  9081. if (angle !== 0) {
  9082. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  9083. b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  9084. } else {
  9085. b = [left, top, left + divWidth, top + divHeight];
  9086. }
  9087. task._bounds.push({
  9088. left: b[0],
  9089. top: b[1],
  9090. right: b[2],
  9091. bottom: b[3],
  9092. div: textDiv,
  9093. size: [divWidth, divHeight],
  9094. m
  9095. });
  9096. }
  9097. }
  9098. function render(task) {
  9099. if (task._canceled) {
  9100. return;
  9101. }
  9102. const textDivs = task._textDivs;
  9103. const capability = task._capability;
  9104. const textDivsLength = textDivs.length;
  9105. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  9106. task._renderingDone = true;
  9107. capability.resolve();
  9108. return;
  9109. }
  9110. if (!task._textContentStream) {
  9111. for (let i = 0; i < textDivsLength; i++) {
  9112. task._layoutText(textDivs[i]);
  9113. }
  9114. }
  9115. task._renderingDone = true;
  9116. capability.resolve();
  9117. }
  9118. function findPositiveMin(ts, offset, count) {
  9119. let result = 0;
  9120. for (let i = 0; i < count; i++) {
  9121. const t = ts[offset++];
  9122. if (t > 0) {
  9123. result = result ? Math.min(t, result) : t;
  9124. }
  9125. }
  9126. return result;
  9127. }
  9128. function expand(task) {
  9129. const bounds = task._bounds;
  9130. const viewport = task._viewport;
  9131. const expanded = expandBounds(viewport.width, viewport.height, bounds);
  9132. for (let i = 0; i < expanded.length; i++) {
  9133. const div = bounds[i].div;
  9134. const divProperties = task._textDivProperties.get(div);
  9135. if (divProperties.angle === 0) {
  9136. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  9137. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  9138. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  9139. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  9140. task._textDivProperties.set(div, divProperties);
  9141. continue;
  9142. }
  9143. const e = expanded[i],
  9144. b = bounds[i];
  9145. const m = b.m,
  9146. c = m[0],
  9147. s = m[1];
  9148. const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  9149. const ts = new Float64Array(64);
  9150. for (let j = 0, jj = points.length; j < jj; j++) {
  9151. const t = _util.Util.applyTransform(points[j], m);
  9152. ts[j + 0] = c && (e.left - t[0]) / c;
  9153. ts[j + 4] = s && (e.top - t[1]) / s;
  9154. ts[j + 8] = c && (e.right - t[0]) / c;
  9155. ts[j + 12] = s && (e.bottom - t[1]) / s;
  9156. ts[j + 16] = s && (e.left - t[0]) / -s;
  9157. ts[j + 20] = c && (e.top - t[1]) / c;
  9158. ts[j + 24] = s && (e.right - t[0]) / -s;
  9159. ts[j + 28] = c && (e.bottom - t[1]) / c;
  9160. ts[j + 32] = c && (e.left - t[0]) / -c;
  9161. ts[j + 36] = s && (e.top - t[1]) / -s;
  9162. ts[j + 40] = c && (e.right - t[0]) / -c;
  9163. ts[j + 44] = s && (e.bottom - t[1]) / -s;
  9164. ts[j + 48] = s && (e.left - t[0]) / s;
  9165. ts[j + 52] = c && (e.top - t[1]) / -c;
  9166. ts[j + 56] = s && (e.right - t[0]) / s;
  9167. ts[j + 60] = c && (e.bottom - t[1]) / -c;
  9168. }
  9169. const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  9170. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  9171. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  9172. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  9173. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  9174. task._textDivProperties.set(div, divProperties);
  9175. }
  9176. }
  9177. function expandBounds(width, height, boxes) {
  9178. const bounds = boxes.map(function (box, i) {
  9179. return {
  9180. x1: box.left,
  9181. y1: box.top,
  9182. x2: box.right,
  9183. y2: box.bottom,
  9184. index: i,
  9185. x1New: undefined,
  9186. x2New: undefined
  9187. };
  9188. });
  9189. expandBoundsLTR(width, bounds);
  9190. const expanded = new Array(boxes.length);
  9191. for (const b of bounds) {
  9192. const i = b.index;
  9193. expanded[i] = {
  9194. left: b.x1New,
  9195. top: 0,
  9196. right: b.x2New,
  9197. bottom: 0
  9198. };
  9199. }
  9200. boxes.map(function (box, i) {
  9201. const e = expanded[i],
  9202. b = bounds[i];
  9203. b.x1 = box.top;
  9204. b.y1 = width - e.right;
  9205. b.x2 = box.bottom;
  9206. b.y2 = width - e.left;
  9207. b.index = i;
  9208. b.x1New = undefined;
  9209. b.x2New = undefined;
  9210. });
  9211. expandBoundsLTR(height, bounds);
  9212. for (const b of bounds) {
  9213. const i = b.index;
  9214. expanded[i].top = b.x1New;
  9215. expanded[i].bottom = b.x2New;
  9216. }
  9217. return expanded;
  9218. }
  9219. function expandBoundsLTR(width, bounds) {
  9220. bounds.sort(function (a, b) {
  9221. return a.x1 - b.x1 || a.index - b.index;
  9222. });
  9223. const fakeBoundary = {
  9224. x1: -Infinity,
  9225. y1: -Infinity,
  9226. x2: 0,
  9227. y2: Infinity,
  9228. index: -1,
  9229. x1New: 0,
  9230. x2New: 0
  9231. };
  9232. const horizon = [{
  9233. start: -Infinity,
  9234. end: Infinity,
  9235. boundary: fakeBoundary
  9236. }];
  9237. for (const boundary of bounds) {
  9238. let i = 0;
  9239. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  9240. i++;
  9241. }
  9242. let j = horizon.length - 1;
  9243. while (j >= 0 && horizon[j].start >= boundary.y2) {
  9244. j--;
  9245. }
  9246. let horizonPart, affectedBoundary;
  9247. let q,
  9248. k,
  9249. maxXNew = -Infinity;
  9250. for (q = i; q <= j; q++) {
  9251. horizonPart = horizon[q];
  9252. affectedBoundary = horizonPart.boundary;
  9253. let xNew;
  9254. if (affectedBoundary.x2 > boundary.x1) {
  9255. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  9256. } else if (affectedBoundary.x2New === undefined) {
  9257. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  9258. } else {
  9259. xNew = affectedBoundary.x2New;
  9260. }
  9261. if (xNew > maxXNew) {
  9262. maxXNew = xNew;
  9263. }
  9264. }
  9265. boundary.x1New = maxXNew;
  9266. for (q = i; q <= j; q++) {
  9267. horizonPart = horizon[q];
  9268. affectedBoundary = horizonPart.boundary;
  9269. if (affectedBoundary.x2New === undefined) {
  9270. if (affectedBoundary.x2 > boundary.x1) {
  9271. if (affectedBoundary.index > boundary.index) {
  9272. affectedBoundary.x2New = affectedBoundary.x2;
  9273. }
  9274. } else {
  9275. affectedBoundary.x2New = maxXNew;
  9276. }
  9277. } else if (affectedBoundary.x2New > maxXNew) {
  9278. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  9279. }
  9280. }
  9281. const changedHorizon = [];
  9282. let lastBoundary = null;
  9283. for (q = i; q <= j; q++) {
  9284. horizonPart = horizon[q];
  9285. affectedBoundary = horizonPart.boundary;
  9286. const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  9287. if (lastBoundary === useBoundary) {
  9288. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  9289. } else {
  9290. changedHorizon.push({
  9291. start: horizonPart.start,
  9292. end: horizonPart.end,
  9293. boundary: useBoundary
  9294. });
  9295. lastBoundary = useBoundary;
  9296. }
  9297. }
  9298. if (horizon[i].start < boundary.y1) {
  9299. changedHorizon[0].start = boundary.y1;
  9300. changedHorizon.unshift({
  9301. start: horizon[i].start,
  9302. end: boundary.y1,
  9303. boundary: horizon[i].boundary
  9304. });
  9305. }
  9306. if (boundary.y2 < horizon[j].end) {
  9307. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  9308. changedHorizon.push({
  9309. start: boundary.y2,
  9310. end: horizon[j].end,
  9311. boundary: horizon[j].boundary
  9312. });
  9313. }
  9314. for (q = i; q <= j; q++) {
  9315. horizonPart = horizon[q];
  9316. affectedBoundary = horizonPart.boundary;
  9317. if (affectedBoundary.x2New !== undefined) {
  9318. continue;
  9319. }
  9320. let used = false;
  9321. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  9322. used = horizon[k].boundary === affectedBoundary;
  9323. }
  9324. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  9325. used = horizon[k].boundary === affectedBoundary;
  9326. }
  9327. for (k = 0; !used && k < changedHorizon.length; k++) {
  9328. used = changedHorizon[k].boundary === affectedBoundary;
  9329. }
  9330. if (!used) {
  9331. affectedBoundary.x2New = maxXNew;
  9332. }
  9333. }
  9334. Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
  9335. }
  9336. for (const horizonPart of horizon) {
  9337. const affectedBoundary = horizonPart.boundary;
  9338. if (affectedBoundary.x2New === undefined) {
  9339. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  9340. }
  9341. }
  9342. }
  9343. class TextLayerRenderTask {
  9344. constructor({
  9345. textContent,
  9346. textContentStream,
  9347. container,
  9348. viewport,
  9349. textDivs,
  9350. textContentItemsStr,
  9351. enhanceTextSelection
  9352. }) {
  9353. this._textContent = textContent;
  9354. this._textContentStream = textContentStream;
  9355. this._container = container;
  9356. this._document = container.ownerDocument;
  9357. this._viewport = viewport;
  9358. this._textDivs = textDivs || [];
  9359. this._textContentItemsStr = textContentItemsStr || [];
  9360. this._enhanceTextSelection = !!enhanceTextSelection;
  9361. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  9362. this._reader = null;
  9363. this._layoutTextLastFontSize = null;
  9364. this._layoutTextLastFontFamily = null;
  9365. this._layoutTextCtx = null;
  9366. this._textDivProperties = new WeakMap();
  9367. this._renderingDone = false;
  9368. this._canceled = false;
  9369. this._capability = (0, _util.createPromiseCapability)();
  9370. this._renderTimer = null;
  9371. this._bounds = [];
  9372. this._capability.promise.finally(() => {
  9373. if (!this._enhanceTextSelection) {
  9374. this._textDivProperties = null;
  9375. }
  9376. if (this._layoutTextCtx) {
  9377. this._layoutTextCtx.canvas.width = 0;
  9378. this._layoutTextCtx.canvas.height = 0;
  9379. this._layoutTextCtx = null;
  9380. }
  9381. }).catch(() => {});
  9382. }
  9383. get promise() {
  9384. return this._capability.promise;
  9385. }
  9386. cancel() {
  9387. this._canceled = true;
  9388. if (this._reader) {
  9389. this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
  9390. this._reader = null;
  9391. }
  9392. if (this._renderTimer !== null) {
  9393. clearTimeout(this._renderTimer);
  9394. this._renderTimer = null;
  9395. }
  9396. this._capability.reject(new Error("TextLayer task cancelled."));
  9397. }
  9398. _processItems(items, styleCache) {
  9399. for (let i = 0, len = items.length; i < len; i++) {
  9400. if (items[i].str === undefined) {
  9401. if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") {
  9402. const parent = this._container;
  9403. this._container = document.createElement("span");
  9404. this._container.classList.add("markedContent");
  9405. if (items[i].id !== null) {
  9406. this._container.setAttribute("id", `${items[i].id}`);
  9407. }
  9408. parent.appendChild(this._container);
  9409. } else if (items[i].type === "endMarkedContent") {
  9410. this._container = this._container.parentNode;
  9411. }
  9412. continue;
  9413. }
  9414. this._textContentItemsStr.push(items[i].str);
  9415. appendText(this, items[i], styleCache, this._layoutTextCtx);
  9416. }
  9417. }
  9418. _layoutText(textDiv) {
  9419. const textDivProperties = this._textDivProperties.get(textDiv);
  9420. let transform = "";
  9421. if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
  9422. const {
  9423. fontSize,
  9424. fontFamily
  9425. } = textDiv.style;
  9426. if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
  9427. this._layoutTextCtx.font = `${fontSize} ${fontFamily}`;
  9428. this._layoutTextLastFontSize = fontSize;
  9429. this._layoutTextLastFontFamily = fontFamily;
  9430. }
  9431. const {
  9432. width
  9433. } = this._layoutTextCtx.measureText(textDiv.textContent);
  9434. if (width > 0) {
  9435. const scale = textDivProperties.canvasWidth / width;
  9436. if (this._enhanceTextSelection) {
  9437. textDivProperties.scale = scale;
  9438. }
  9439. transform = `scaleX(${scale})`;
  9440. }
  9441. }
  9442. if (textDivProperties.angle !== 0) {
  9443. transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
  9444. }
  9445. if (transform.length > 0) {
  9446. if (this._enhanceTextSelection) {
  9447. textDivProperties.originalTransform = transform;
  9448. }
  9449. textDiv.style.transform = transform;
  9450. }
  9451. if (textDivProperties.hasText) {
  9452. this._container.appendChild(textDiv);
  9453. }
  9454. if (textDivProperties.hasEOL) {
  9455. const br = document.createElement("br");
  9456. br.setAttribute("role", "presentation");
  9457. this._container.appendChild(br);
  9458. }
  9459. }
  9460. _render(timeout = 0) {
  9461. const capability = (0, _util.createPromiseCapability)();
  9462. let styleCache = Object.create(null);
  9463. const canvas = this._document.createElement("canvas");
  9464. canvas.height = canvas.width = DEFAULT_FONT_SIZE;
  9465. canvas.mozOpaque = true;
  9466. this._layoutTextCtx = canvas.getContext("2d", {
  9467. alpha: false
  9468. });
  9469. if (this._textContent) {
  9470. const textItems = this._textContent.items;
  9471. const textStyles = this._textContent.styles;
  9472. this._processItems(textItems, textStyles);
  9473. capability.resolve();
  9474. } else if (this._textContentStream) {
  9475. const pump = () => {
  9476. this._reader.read().then(({
  9477. value,
  9478. done
  9479. }) => {
  9480. if (done) {
  9481. capability.resolve();
  9482. return;
  9483. }
  9484. Object.assign(styleCache, value.styles);
  9485. this._processItems(value.items, styleCache);
  9486. pump();
  9487. }, capability.reject);
  9488. };
  9489. this._reader = this._textContentStream.getReader();
  9490. pump();
  9491. } else {
  9492. throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');
  9493. }
  9494. capability.promise.then(() => {
  9495. styleCache = null;
  9496. if (!timeout) {
  9497. render(this);
  9498. } else {
  9499. this._renderTimer = setTimeout(() => {
  9500. render(this);
  9501. this._renderTimer = null;
  9502. }, timeout);
  9503. }
  9504. }, this._capability.reject);
  9505. }
  9506. expandTextDivs(expandDivs = false) {
  9507. if (!this._enhanceTextSelection || !this._renderingDone) {
  9508. return;
  9509. }
  9510. if (this._bounds !== null) {
  9511. expand(this);
  9512. this._bounds = null;
  9513. }
  9514. const transformBuf = [],
  9515. paddingBuf = [];
  9516. for (let i = 0, ii = this._textDivs.length; i < ii; i++) {
  9517. const div = this._textDivs[i];
  9518. const divProps = this._textDivProperties.get(div);
  9519. if (!divProps.hasText) {
  9520. continue;
  9521. }
  9522. if (expandDivs) {
  9523. transformBuf.length = 0;
  9524. paddingBuf.length = 0;
  9525. if (divProps.originalTransform) {
  9526. transformBuf.push(divProps.originalTransform);
  9527. }
  9528. if (divProps.paddingTop > 0) {
  9529. paddingBuf.push(`${divProps.paddingTop}px`);
  9530. transformBuf.push(`translateY(${-divProps.paddingTop}px)`);
  9531. } else {
  9532. paddingBuf.push(0);
  9533. }
  9534. if (divProps.paddingRight > 0) {
  9535. paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`);
  9536. } else {
  9537. paddingBuf.push(0);
  9538. }
  9539. if (divProps.paddingBottom > 0) {
  9540. paddingBuf.push(`${divProps.paddingBottom}px`);
  9541. } else {
  9542. paddingBuf.push(0);
  9543. }
  9544. if (divProps.paddingLeft > 0) {
  9545. paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`);
  9546. transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`);
  9547. } else {
  9548. paddingBuf.push(0);
  9549. }
  9550. div.style.padding = paddingBuf.join(" ");
  9551. if (transformBuf.length) {
  9552. div.style.transform = transformBuf.join(" ");
  9553. }
  9554. } else {
  9555. div.style.padding = null;
  9556. div.style.transform = divProps.originalTransform;
  9557. }
  9558. }
  9559. }
  9560. }
  9561. function renderTextLayer(renderParameters) {
  9562. const task = new TextLayerRenderTask({
  9563. textContent: renderParameters.textContent,
  9564. textContentStream: renderParameters.textContentStream,
  9565. container: renderParameters.container,
  9566. viewport: renderParameters.viewport,
  9567. textDivs: renderParameters.textDivs,
  9568. textContentItemsStr: renderParameters.textContentItemsStr,
  9569. enhanceTextSelection: renderParameters.enhanceTextSelection
  9570. });
  9571. task._render(renderParameters.timeout);
  9572. return task;
  9573. }
  9574. /***/ }),
  9575. /* 21 */
  9576. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9577. Object.defineProperty(exports, "__esModule", ({
  9578. value: true
  9579. }));
  9580. exports.SVGGraphics = void 0;
  9581. var _util = __w_pdfjs_require__(2);
  9582. var _display_utils = __w_pdfjs_require__(1);
  9583. var _is_node = __w_pdfjs_require__(4);
  9584. let SVGGraphics = class {
  9585. constructor() {
  9586. (0, _util.unreachable)("Not implemented: SVGGraphics");
  9587. }
  9588. };
  9589. exports.SVGGraphics = SVGGraphics;
  9590. {
  9591. const SVG_DEFAULTS = {
  9592. fontStyle: "normal",
  9593. fontWeight: "normal",
  9594. fillColor: "#000000"
  9595. };
  9596. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  9597. const XLINK_NS = "http://www.w3.org/1999/xlink";
  9598. const LINE_CAP_STYLES = ["butt", "round", "square"];
  9599. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  9600. const convertImgDataToPng = function () {
  9601. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  9602. const CHUNK_WRAPPER_SIZE = 12;
  9603. const crcTable = new Int32Array(256);
  9604. for (let i = 0; i < 256; i++) {
  9605. let c = i;
  9606. for (let h = 0; h < 8; h++) {
  9607. if (c & 1) {
  9608. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  9609. } else {
  9610. c = c >> 1 & 0x7fffffff;
  9611. }
  9612. }
  9613. crcTable[i] = c;
  9614. }
  9615. function crc32(data, start, end) {
  9616. let crc = -1;
  9617. for (let i = start; i < end; i++) {
  9618. const a = (crc ^ data[i]) & 0xff;
  9619. const b = crcTable[a];
  9620. crc = crc >>> 8 ^ b;
  9621. }
  9622. return crc ^ -1;
  9623. }
  9624. function writePngChunk(type, body, data, offset) {
  9625. let p = offset;
  9626. const len = body.length;
  9627. data[p] = len >> 24 & 0xff;
  9628. data[p + 1] = len >> 16 & 0xff;
  9629. data[p + 2] = len >> 8 & 0xff;
  9630. data[p + 3] = len & 0xff;
  9631. p += 4;
  9632. data[p] = type.charCodeAt(0) & 0xff;
  9633. data[p + 1] = type.charCodeAt(1) & 0xff;
  9634. data[p + 2] = type.charCodeAt(2) & 0xff;
  9635. data[p + 3] = type.charCodeAt(3) & 0xff;
  9636. p += 4;
  9637. data.set(body, p);
  9638. p += body.length;
  9639. const crc = crc32(data, offset + 4, p);
  9640. data[p] = crc >> 24 & 0xff;
  9641. data[p + 1] = crc >> 16 & 0xff;
  9642. data[p + 2] = crc >> 8 & 0xff;
  9643. data[p + 3] = crc & 0xff;
  9644. }
  9645. function adler32(data, start, end) {
  9646. let a = 1;
  9647. let b = 0;
  9648. for (let i = start; i < end; ++i) {
  9649. a = (a + (data[i] & 0xff)) % 65521;
  9650. b = (b + a) % 65521;
  9651. }
  9652. return b << 16 | a;
  9653. }
  9654. function deflateSync(literals) {
  9655. if (!_is_node.isNodeJS) {
  9656. return deflateSyncUncompressed(literals);
  9657. }
  9658. try {
  9659. let input;
  9660. if (parseInt(process.versions.node) >= 8) {
  9661. input = literals;
  9662. } else {
  9663. input = Buffer.from(literals);
  9664. }
  9665. const output = require("zlib").deflateSync(input, {
  9666. level: 9
  9667. });
  9668. return output instanceof Uint8Array ? output : new Uint8Array(output);
  9669. } catch (e) {
  9670. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  9671. }
  9672. return deflateSyncUncompressed(literals);
  9673. }
  9674. function deflateSyncUncompressed(literals) {
  9675. let len = literals.length;
  9676. const maxBlockLength = 0xffff;
  9677. const deflateBlocks = Math.ceil(len / maxBlockLength);
  9678. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  9679. let pi = 0;
  9680. idat[pi++] = 0x78;
  9681. idat[pi++] = 0x9c;
  9682. let pos = 0;
  9683. while (len > maxBlockLength) {
  9684. idat[pi++] = 0x00;
  9685. idat[pi++] = 0xff;
  9686. idat[pi++] = 0xff;
  9687. idat[pi++] = 0x00;
  9688. idat[pi++] = 0x00;
  9689. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  9690. pi += maxBlockLength;
  9691. pos += maxBlockLength;
  9692. len -= maxBlockLength;
  9693. }
  9694. idat[pi++] = 0x01;
  9695. idat[pi++] = len & 0xff;
  9696. idat[pi++] = len >> 8 & 0xff;
  9697. idat[pi++] = ~len & 0xffff & 0xff;
  9698. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  9699. idat.set(literals.subarray(pos), pi);
  9700. pi += literals.length - pos;
  9701. const adler = adler32(literals, 0, literals.length);
  9702. idat[pi++] = adler >> 24 & 0xff;
  9703. idat[pi++] = adler >> 16 & 0xff;
  9704. idat[pi++] = adler >> 8 & 0xff;
  9705. idat[pi++] = adler & 0xff;
  9706. return idat;
  9707. }
  9708. function encode(imgData, kind, forceDataSchema, isMask) {
  9709. const width = imgData.width;
  9710. const height = imgData.height;
  9711. let bitDepth, colorType, lineSize;
  9712. const bytes = imgData.data;
  9713. switch (kind) {
  9714. case _util.ImageKind.GRAYSCALE_1BPP:
  9715. colorType = 0;
  9716. bitDepth = 1;
  9717. lineSize = width + 7 >> 3;
  9718. break;
  9719. case _util.ImageKind.RGB_24BPP:
  9720. colorType = 2;
  9721. bitDepth = 8;
  9722. lineSize = width * 3;
  9723. break;
  9724. case _util.ImageKind.RGBA_32BPP:
  9725. colorType = 6;
  9726. bitDepth = 8;
  9727. lineSize = width * 4;
  9728. break;
  9729. default:
  9730. throw new Error("invalid format");
  9731. }
  9732. const literals = new Uint8Array((1 + lineSize) * height);
  9733. let offsetLiterals = 0,
  9734. offsetBytes = 0;
  9735. for (let y = 0; y < height; ++y) {
  9736. literals[offsetLiterals++] = 0;
  9737. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  9738. offsetBytes += lineSize;
  9739. offsetLiterals += lineSize;
  9740. }
  9741. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  9742. offsetLiterals = 0;
  9743. for (let y = 0; y < height; y++) {
  9744. offsetLiterals++;
  9745. for (let i = 0; i < lineSize; i++) {
  9746. literals[offsetLiterals++] ^= 0xff;
  9747. }
  9748. }
  9749. }
  9750. 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]);
  9751. const idat = deflateSync(literals);
  9752. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  9753. const data = new Uint8Array(pngLength);
  9754. let offset = 0;
  9755. data.set(PNG_HEADER, offset);
  9756. offset += PNG_HEADER.length;
  9757. writePngChunk("IHDR", ihdr, data, offset);
  9758. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  9759. writePngChunk("IDATA", idat, data, offset);
  9760. offset += CHUNK_WRAPPER_SIZE + idat.length;
  9761. writePngChunk("IEND", new Uint8Array(0), data, offset);
  9762. return (0, _util.createObjectURL)(data, "image/png", forceDataSchema);
  9763. }
  9764. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  9765. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  9766. return encode(imgData, kind, forceDataSchema, isMask);
  9767. };
  9768. }();
  9769. class SVGExtraState {
  9770. constructor() {
  9771. this.fontSizeScale = 1;
  9772. this.fontWeight = SVG_DEFAULTS.fontWeight;
  9773. this.fontSize = 0;
  9774. this.textMatrix = _util.IDENTITY_MATRIX;
  9775. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  9776. this.leading = 0;
  9777. this.textRenderingMode = _util.TextRenderingMode.FILL;
  9778. this.textMatrixScale = 1;
  9779. this.x = 0;
  9780. this.y = 0;
  9781. this.lineX = 0;
  9782. this.lineY = 0;
  9783. this.charSpacing = 0;
  9784. this.wordSpacing = 0;
  9785. this.textHScale = 1;
  9786. this.textRise = 0;
  9787. this.fillColor = SVG_DEFAULTS.fillColor;
  9788. this.strokeColor = "#000000";
  9789. this.fillAlpha = 1;
  9790. this.strokeAlpha = 1;
  9791. this.lineWidth = 1;
  9792. this.lineJoin = "";
  9793. this.lineCap = "";
  9794. this.miterLimit = 0;
  9795. this.dashArray = [];
  9796. this.dashPhase = 0;
  9797. this.dependencies = [];
  9798. this.activeClipUrl = null;
  9799. this.clipGroup = null;
  9800. this.maskId = "";
  9801. }
  9802. clone() {
  9803. return Object.create(this);
  9804. }
  9805. setCurrentPoint(x, y) {
  9806. this.x = x;
  9807. this.y = y;
  9808. }
  9809. }
  9810. function opListToTree(opList) {
  9811. let opTree = [];
  9812. const tmp = [];
  9813. for (const opListElement of opList) {
  9814. if (opListElement.fn === "save") {
  9815. opTree.push({
  9816. fnId: 92,
  9817. fn: "group",
  9818. items: []
  9819. });
  9820. tmp.push(opTree);
  9821. opTree = opTree[opTree.length - 1].items;
  9822. continue;
  9823. }
  9824. if (opListElement.fn === "restore") {
  9825. opTree = tmp.pop();
  9826. } else {
  9827. opTree.push(opListElement);
  9828. }
  9829. }
  9830. return opTree;
  9831. }
  9832. function pf(value) {
  9833. if (Number.isInteger(value)) {
  9834. return value.toString();
  9835. }
  9836. const s = value.toFixed(10);
  9837. let i = s.length - 1;
  9838. if (s[i] !== "0") {
  9839. return s;
  9840. }
  9841. do {
  9842. i--;
  9843. } while (s[i] === "0");
  9844. return s.substring(0, s[i] === "." ? i : i + 1);
  9845. }
  9846. function pm(m) {
  9847. if (m[4] === 0 && m[5] === 0) {
  9848. if (m[1] === 0 && m[2] === 0) {
  9849. if (m[0] === 1 && m[3] === 1) {
  9850. return "";
  9851. }
  9852. return `scale(${pf(m[0])} ${pf(m[3])})`;
  9853. }
  9854. if (m[0] === m[3] && m[1] === -m[2]) {
  9855. const a = Math.acos(m[0]) * 180 / Math.PI;
  9856. return `rotate(${pf(a)})`;
  9857. }
  9858. } else {
  9859. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  9860. return `translate(${pf(m[4])} ${pf(m[5])})`;
  9861. }
  9862. }
  9863. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  9864. }
  9865. let clipCount = 0;
  9866. let maskCount = 0;
  9867. let shadingCount = 0;
  9868. exports.SVGGraphics = SVGGraphics = class {
  9869. constructor(commonObjs, objs, forceDataSchema = false) {
  9870. this.svgFactory = new _display_utils.DOMSVGFactory();
  9871. this.current = new SVGExtraState();
  9872. this.transformMatrix = _util.IDENTITY_MATRIX;
  9873. this.transformStack = [];
  9874. this.extraStack = [];
  9875. this.commonObjs = commonObjs;
  9876. this.objs = objs;
  9877. this.pendingClip = null;
  9878. this.pendingEOFill = false;
  9879. this.embedFonts = false;
  9880. this.embeddedFonts = Object.create(null);
  9881. this.cssStyle = null;
  9882. this.forceDataSchema = !!forceDataSchema;
  9883. this._operatorIdMapping = [];
  9884. for (const op in _util.OPS) {
  9885. this._operatorIdMapping[_util.OPS[op]] = op;
  9886. }
  9887. }
  9888. save() {
  9889. this.transformStack.push(this.transformMatrix);
  9890. const old = this.current;
  9891. this.extraStack.push(old);
  9892. this.current = old.clone();
  9893. }
  9894. restore() {
  9895. this.transformMatrix = this.transformStack.pop();
  9896. this.current = this.extraStack.pop();
  9897. this.pendingClip = null;
  9898. this.tgrp = null;
  9899. }
  9900. group(items) {
  9901. this.save();
  9902. this.executeOpTree(items);
  9903. this.restore();
  9904. }
  9905. loadDependencies(operatorList) {
  9906. const fnArray = operatorList.fnArray;
  9907. const argsArray = operatorList.argsArray;
  9908. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  9909. if (fnArray[i] !== _util.OPS.dependency) {
  9910. continue;
  9911. }
  9912. for (const obj of argsArray[i]) {
  9913. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  9914. const promise = new Promise(resolve => {
  9915. objsPool.get(obj, resolve);
  9916. });
  9917. this.current.dependencies.push(promise);
  9918. }
  9919. }
  9920. return Promise.all(this.current.dependencies);
  9921. }
  9922. transform(a, b, c, d, e, f) {
  9923. const transformMatrix = [a, b, c, d, e, f];
  9924. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  9925. this.tgrp = null;
  9926. }
  9927. getSVG(operatorList, viewport) {
  9928. this.viewport = viewport;
  9929. const svgElement = this._initialize(viewport);
  9930. return this.loadDependencies(operatorList).then(() => {
  9931. this.transformMatrix = _util.IDENTITY_MATRIX;
  9932. this.executeOpTree(this.convertOpList(operatorList));
  9933. return svgElement;
  9934. });
  9935. }
  9936. convertOpList(operatorList) {
  9937. const operatorIdMapping = this._operatorIdMapping;
  9938. const argsArray = operatorList.argsArray;
  9939. const fnArray = operatorList.fnArray;
  9940. const opList = [];
  9941. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  9942. const fnId = fnArray[i];
  9943. opList.push({
  9944. fnId,
  9945. fn: operatorIdMapping[fnId],
  9946. args: argsArray[i]
  9947. });
  9948. }
  9949. return opListToTree(opList);
  9950. }
  9951. executeOpTree(opTree) {
  9952. for (const opTreeElement of opTree) {
  9953. const fn = opTreeElement.fn;
  9954. const fnId = opTreeElement.fnId;
  9955. const args = opTreeElement.args;
  9956. switch (fnId | 0) {
  9957. case _util.OPS.beginText:
  9958. this.beginText();
  9959. break;
  9960. case _util.OPS.dependency:
  9961. break;
  9962. case _util.OPS.setLeading:
  9963. this.setLeading(args);
  9964. break;
  9965. case _util.OPS.setLeadingMoveText:
  9966. this.setLeadingMoveText(args[0], args[1]);
  9967. break;
  9968. case _util.OPS.setFont:
  9969. this.setFont(args);
  9970. break;
  9971. case _util.OPS.showText:
  9972. this.showText(args[0]);
  9973. break;
  9974. case _util.OPS.showSpacedText:
  9975. this.showText(args[0]);
  9976. break;
  9977. case _util.OPS.endText:
  9978. this.endText();
  9979. break;
  9980. case _util.OPS.moveText:
  9981. this.moveText(args[0], args[1]);
  9982. break;
  9983. case _util.OPS.setCharSpacing:
  9984. this.setCharSpacing(args[0]);
  9985. break;
  9986. case _util.OPS.setWordSpacing:
  9987. this.setWordSpacing(args[0]);
  9988. break;
  9989. case _util.OPS.setHScale:
  9990. this.setHScale(args[0]);
  9991. break;
  9992. case _util.OPS.setTextMatrix:
  9993. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  9994. break;
  9995. case _util.OPS.setTextRise:
  9996. this.setTextRise(args[0]);
  9997. break;
  9998. case _util.OPS.setTextRenderingMode:
  9999. this.setTextRenderingMode(args[0]);
  10000. break;
  10001. case _util.OPS.setLineWidth:
  10002. this.setLineWidth(args[0]);
  10003. break;
  10004. case _util.OPS.setLineJoin:
  10005. this.setLineJoin(args[0]);
  10006. break;
  10007. case _util.OPS.setLineCap:
  10008. this.setLineCap(args[0]);
  10009. break;
  10010. case _util.OPS.setMiterLimit:
  10011. this.setMiterLimit(args[0]);
  10012. break;
  10013. case _util.OPS.setFillRGBColor:
  10014. this.setFillRGBColor(args[0], args[1], args[2]);
  10015. break;
  10016. case _util.OPS.setStrokeRGBColor:
  10017. this.setStrokeRGBColor(args[0], args[1], args[2]);
  10018. break;
  10019. case _util.OPS.setStrokeColorN:
  10020. this.setStrokeColorN(args);
  10021. break;
  10022. case _util.OPS.setFillColorN:
  10023. this.setFillColorN(args);
  10024. break;
  10025. case _util.OPS.shadingFill:
  10026. this.shadingFill(args[0]);
  10027. break;
  10028. case _util.OPS.setDash:
  10029. this.setDash(args[0], args[1]);
  10030. break;
  10031. case _util.OPS.setRenderingIntent:
  10032. this.setRenderingIntent(args[0]);
  10033. break;
  10034. case _util.OPS.setFlatness:
  10035. this.setFlatness(args[0]);
  10036. break;
  10037. case _util.OPS.setGState:
  10038. this.setGState(args[0]);
  10039. break;
  10040. case _util.OPS.fill:
  10041. this.fill();
  10042. break;
  10043. case _util.OPS.eoFill:
  10044. this.eoFill();
  10045. break;
  10046. case _util.OPS.stroke:
  10047. this.stroke();
  10048. break;
  10049. case _util.OPS.fillStroke:
  10050. this.fillStroke();
  10051. break;
  10052. case _util.OPS.eoFillStroke:
  10053. this.eoFillStroke();
  10054. break;
  10055. case _util.OPS.clip:
  10056. this.clip("nonzero");
  10057. break;
  10058. case _util.OPS.eoClip:
  10059. this.clip("evenodd");
  10060. break;
  10061. case _util.OPS.paintSolidColorImageMask:
  10062. this.paintSolidColorImageMask();
  10063. break;
  10064. case _util.OPS.paintImageXObject:
  10065. this.paintImageXObject(args[0]);
  10066. break;
  10067. case _util.OPS.paintInlineImageXObject:
  10068. this.paintInlineImageXObject(args[0]);
  10069. break;
  10070. case _util.OPS.paintImageMaskXObject:
  10071. this.paintImageMaskXObject(args[0]);
  10072. break;
  10073. case _util.OPS.paintFormXObjectBegin:
  10074. this.paintFormXObjectBegin(args[0], args[1]);
  10075. break;
  10076. case _util.OPS.paintFormXObjectEnd:
  10077. this.paintFormXObjectEnd();
  10078. break;
  10079. case _util.OPS.closePath:
  10080. this.closePath();
  10081. break;
  10082. case _util.OPS.closeStroke:
  10083. this.closeStroke();
  10084. break;
  10085. case _util.OPS.closeFillStroke:
  10086. this.closeFillStroke();
  10087. break;
  10088. case _util.OPS.closeEOFillStroke:
  10089. this.closeEOFillStroke();
  10090. break;
  10091. case _util.OPS.nextLine:
  10092. this.nextLine();
  10093. break;
  10094. case _util.OPS.transform:
  10095. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  10096. break;
  10097. case _util.OPS.constructPath:
  10098. this.constructPath(args[0], args[1]);
  10099. break;
  10100. case _util.OPS.endPath:
  10101. this.endPath();
  10102. break;
  10103. case 92:
  10104. this.group(opTreeElement.items);
  10105. break;
  10106. default:
  10107. (0, _util.warn)(`Unimplemented operator ${fn}`);
  10108. break;
  10109. }
  10110. }
  10111. }
  10112. setWordSpacing(wordSpacing) {
  10113. this.current.wordSpacing = wordSpacing;
  10114. }
  10115. setCharSpacing(charSpacing) {
  10116. this.current.charSpacing = charSpacing;
  10117. }
  10118. nextLine() {
  10119. this.moveText(0, this.current.leading);
  10120. }
  10121. setTextMatrix(a, b, c, d, e, f) {
  10122. const current = this.current;
  10123. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  10124. current.textMatrixScale = Math.hypot(a, b);
  10125. current.x = current.lineX = 0;
  10126. current.y = current.lineY = 0;
  10127. current.xcoords = [];
  10128. current.ycoords = [];
  10129. current.tspan = this.svgFactory.createElement("svg:tspan");
  10130. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  10131. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  10132. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  10133. current.txtElement = this.svgFactory.createElement("svg:text");
  10134. current.txtElement.appendChild(current.tspan);
  10135. }
  10136. beginText() {
  10137. const current = this.current;
  10138. current.x = current.lineX = 0;
  10139. current.y = current.lineY = 0;
  10140. current.textMatrix = _util.IDENTITY_MATRIX;
  10141. current.lineMatrix = _util.IDENTITY_MATRIX;
  10142. current.textMatrixScale = 1;
  10143. current.tspan = this.svgFactory.createElement("svg:tspan");
  10144. current.txtElement = this.svgFactory.createElement("svg:text");
  10145. current.txtgrp = this.svgFactory.createElement("svg:g");
  10146. current.xcoords = [];
  10147. current.ycoords = [];
  10148. }
  10149. moveText(x, y) {
  10150. const current = this.current;
  10151. current.x = current.lineX += x;
  10152. current.y = current.lineY += y;
  10153. current.xcoords = [];
  10154. current.ycoords = [];
  10155. current.tspan = this.svgFactory.createElement("svg:tspan");
  10156. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  10157. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  10158. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  10159. }
  10160. showText(glyphs) {
  10161. const current = this.current;
  10162. const font = current.font;
  10163. const fontSize = current.fontSize;
  10164. if (fontSize === 0) {
  10165. return;
  10166. }
  10167. const fontSizeScale = current.fontSizeScale;
  10168. const charSpacing = current.charSpacing;
  10169. const wordSpacing = current.wordSpacing;
  10170. const fontDirection = current.fontDirection;
  10171. const textHScale = current.textHScale * fontDirection;
  10172. const vertical = font.vertical;
  10173. const spacingDir = vertical ? 1 : -1;
  10174. const defaultVMetrics = font.defaultVMetrics;
  10175. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  10176. let x = 0;
  10177. for (const glyph of glyphs) {
  10178. if (glyph === null) {
  10179. x += fontDirection * wordSpacing;
  10180. continue;
  10181. } else if ((0, _util.isNum)(glyph)) {
  10182. x += spacingDir * glyph * fontSize / 1000;
  10183. continue;
  10184. }
  10185. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  10186. const character = glyph.fontChar;
  10187. let scaledX, scaledY;
  10188. let width = glyph.width;
  10189. if (vertical) {
  10190. let vx;
  10191. const vmetric = glyph.vmetric || defaultVMetrics;
  10192. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  10193. vx = -vx * widthAdvanceScale;
  10194. const vy = vmetric[2] * widthAdvanceScale;
  10195. width = vmetric ? -vmetric[0] : width;
  10196. scaledX = vx / fontSizeScale;
  10197. scaledY = (x + vy) / fontSizeScale;
  10198. } else {
  10199. scaledX = x / fontSizeScale;
  10200. scaledY = 0;
  10201. }
  10202. if (glyph.isInFont || font.missingFile) {
  10203. current.xcoords.push(current.x + scaledX);
  10204. if (vertical) {
  10205. current.ycoords.push(-current.y + scaledY);
  10206. }
  10207. current.tspan.textContent += character;
  10208. } else {}
  10209. let charWidth;
  10210. if (vertical) {
  10211. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  10212. } else {
  10213. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  10214. }
  10215. x += charWidth;
  10216. }
  10217. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  10218. if (vertical) {
  10219. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  10220. } else {
  10221. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  10222. }
  10223. if (vertical) {
  10224. current.y -= x;
  10225. } else {
  10226. current.x += x * textHScale;
  10227. }
  10228. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  10229. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  10230. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  10231. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  10232. }
  10233. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  10234. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  10235. }
  10236. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  10237. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  10238. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  10239. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  10240. }
  10241. if (current.fillAlpha < 1) {
  10242. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  10243. }
  10244. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  10245. current.tspan.setAttributeNS(null, "fill", "transparent");
  10246. } else {
  10247. current.tspan.setAttributeNS(null, "fill", "none");
  10248. }
  10249. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  10250. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  10251. this._setStrokeAttributes(current.tspan, lineWidthScale);
  10252. }
  10253. let textMatrix = current.textMatrix;
  10254. if (current.textRise !== 0) {
  10255. textMatrix = textMatrix.slice();
  10256. textMatrix[5] += current.textRise;
  10257. }
  10258. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  10259. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  10260. current.txtElement.appendChild(current.tspan);
  10261. current.txtgrp.appendChild(current.txtElement);
  10262. this._ensureTransformGroup().appendChild(current.txtElement);
  10263. }
  10264. setLeadingMoveText(x, y) {
  10265. this.setLeading(-y);
  10266. this.moveText(x, y);
  10267. }
  10268. addFontStyle(fontObj) {
  10269. if (!fontObj.data) {
  10270. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  10271. }
  10272. if (!this.cssStyle) {
  10273. this.cssStyle = this.svgFactory.createElement("svg:style");
  10274. this.cssStyle.setAttributeNS(null, "type", "text/css");
  10275. this.defs.appendChild(this.cssStyle);
  10276. }
  10277. const url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  10278. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  10279. }
  10280. setFont(details) {
  10281. const current = this.current;
  10282. const fontObj = this.commonObjs.get(details[0]);
  10283. let size = details[1];
  10284. current.font = fontObj;
  10285. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  10286. this.addFontStyle(fontObj);
  10287. this.embeddedFonts[fontObj.loadedName] = fontObj;
  10288. }
  10289. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  10290. let bold = "normal";
  10291. if (fontObj.black) {
  10292. bold = "900";
  10293. } else if (fontObj.bold) {
  10294. bold = "bold";
  10295. }
  10296. const italic = fontObj.italic ? "italic" : "normal";
  10297. if (size < 0) {
  10298. size = -size;
  10299. current.fontDirection = -1;
  10300. } else {
  10301. current.fontDirection = 1;
  10302. }
  10303. current.fontSize = size;
  10304. current.fontFamily = fontObj.loadedName;
  10305. current.fontWeight = bold;
  10306. current.fontStyle = italic;
  10307. current.tspan = this.svgFactory.createElement("svg:tspan");
  10308. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  10309. current.xcoords = [];
  10310. current.ycoords = [];
  10311. }
  10312. endText() {
  10313. const current = this.current;
  10314. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  10315. current.element = current.txtElement;
  10316. this.clip("nonzero");
  10317. this.endPath();
  10318. }
  10319. }
  10320. setLineWidth(width) {
  10321. if (width > 0) {
  10322. this.current.lineWidth = width;
  10323. }
  10324. }
  10325. setLineCap(style) {
  10326. this.current.lineCap = LINE_CAP_STYLES[style];
  10327. }
  10328. setLineJoin(style) {
  10329. this.current.lineJoin = LINE_JOIN_STYLES[style];
  10330. }
  10331. setMiterLimit(limit) {
  10332. this.current.miterLimit = limit;
  10333. }
  10334. setStrokeAlpha(strokeAlpha) {
  10335. this.current.strokeAlpha = strokeAlpha;
  10336. }
  10337. setStrokeRGBColor(r, g, b) {
  10338. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  10339. }
  10340. setFillAlpha(fillAlpha) {
  10341. this.current.fillAlpha = fillAlpha;
  10342. }
  10343. setFillRGBColor(r, g, b) {
  10344. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  10345. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  10346. this.current.xcoords = [];
  10347. this.current.ycoords = [];
  10348. }
  10349. setStrokeColorN(args) {
  10350. this.current.strokeColor = this._makeColorN_Pattern(args);
  10351. }
  10352. setFillColorN(args) {
  10353. this.current.fillColor = this._makeColorN_Pattern(args);
  10354. }
  10355. shadingFill(args) {
  10356. const width = this.viewport.width;
  10357. const height = this.viewport.height;
  10358. const inv = _util.Util.inverseTransform(this.transformMatrix);
  10359. const bl = _util.Util.applyTransform([0, 0], inv);
  10360. const br = _util.Util.applyTransform([0, height], inv);
  10361. const ul = _util.Util.applyTransform([width, 0], inv);
  10362. const ur = _util.Util.applyTransform([width, height], inv);
  10363. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  10364. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  10365. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  10366. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  10367. const rect = this.svgFactory.createElement("svg:rect");
  10368. rect.setAttributeNS(null, "x", x0);
  10369. rect.setAttributeNS(null, "y", y0);
  10370. rect.setAttributeNS(null, "width", x1 - x0);
  10371. rect.setAttributeNS(null, "height", y1 - y0);
  10372. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  10373. if (this.current.fillAlpha < 1) {
  10374. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  10375. }
  10376. this._ensureTransformGroup().appendChild(rect);
  10377. }
  10378. _makeColorN_Pattern(args) {
  10379. if (args[0] === "TilingPattern") {
  10380. return this._makeTilingPattern(args);
  10381. }
  10382. return this._makeShadingPattern(args);
  10383. }
  10384. _makeTilingPattern(args) {
  10385. const color = args[1];
  10386. const operatorList = args[2];
  10387. const matrix = args[3] || _util.IDENTITY_MATRIX;
  10388. const [x0, y0, x1, y1] = args[4];
  10389. const xstep = args[5];
  10390. const ystep = args[6];
  10391. const paintType = args[7];
  10392. const tilingId = `shading${shadingCount++}`;
  10393. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  10394. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  10395. const txstep = xstep * xscale;
  10396. const tystep = ystep * yscale;
  10397. const tiling = this.svgFactory.createElement("svg:pattern");
  10398. tiling.setAttributeNS(null, "id", tilingId);
  10399. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  10400. tiling.setAttributeNS(null, "width", txstep);
  10401. tiling.setAttributeNS(null, "height", tystep);
  10402. tiling.setAttributeNS(null, "x", `${tx0}`);
  10403. tiling.setAttributeNS(null, "y", `${ty0}`);
  10404. const svg = this.svg;
  10405. const transformMatrix = this.transformMatrix;
  10406. const fillColor = this.current.fillColor;
  10407. const strokeColor = this.current.strokeColor;
  10408. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  10409. this.svg = bbox;
  10410. this.transformMatrix = matrix;
  10411. if (paintType === 2) {
  10412. const cssColor = _util.Util.makeHexColor(...color);
  10413. this.current.fillColor = cssColor;
  10414. this.current.strokeColor = cssColor;
  10415. }
  10416. this.executeOpTree(this.convertOpList(operatorList));
  10417. this.svg = svg;
  10418. this.transformMatrix = transformMatrix;
  10419. this.current.fillColor = fillColor;
  10420. this.current.strokeColor = strokeColor;
  10421. tiling.appendChild(bbox.childNodes[0]);
  10422. this.defs.appendChild(tiling);
  10423. return `url(#${tilingId})`;
  10424. }
  10425. _makeShadingPattern(args) {
  10426. switch (args[0]) {
  10427. case "RadialAxial":
  10428. const shadingId = `shading${shadingCount++}`;
  10429. const colorStops = args[3];
  10430. let gradient;
  10431. switch (args[1]) {
  10432. case "axial":
  10433. const point0 = args[4];
  10434. const point1 = args[5];
  10435. gradient = this.svgFactory.createElement("svg:linearGradient");
  10436. gradient.setAttributeNS(null, "id", shadingId);
  10437. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  10438. gradient.setAttributeNS(null, "x1", point0[0]);
  10439. gradient.setAttributeNS(null, "y1", point0[1]);
  10440. gradient.setAttributeNS(null, "x2", point1[0]);
  10441. gradient.setAttributeNS(null, "y2", point1[1]);
  10442. break;
  10443. case "radial":
  10444. const focalPoint = args[4];
  10445. const circlePoint = args[5];
  10446. const focalRadius = args[6];
  10447. const circleRadius = args[7];
  10448. gradient = this.svgFactory.createElement("svg:radialGradient");
  10449. gradient.setAttributeNS(null, "id", shadingId);
  10450. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  10451. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  10452. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  10453. gradient.setAttributeNS(null, "r", circleRadius);
  10454. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  10455. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  10456. gradient.setAttributeNS(null, "fr", focalRadius);
  10457. break;
  10458. default:
  10459. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  10460. }
  10461. for (const colorStop of colorStops) {
  10462. const stop = this.svgFactory.createElement("svg:stop");
  10463. stop.setAttributeNS(null, "offset", colorStop[0]);
  10464. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  10465. gradient.appendChild(stop);
  10466. }
  10467. this.defs.appendChild(gradient);
  10468. return `url(#${shadingId})`;
  10469. case "Mesh":
  10470. (0, _util.warn)("Unimplemented pattern Mesh");
  10471. return null;
  10472. case "Dummy":
  10473. return "hotpink";
  10474. default:
  10475. throw new Error(`Unknown IR type: ${args[0]}`);
  10476. }
  10477. }
  10478. setDash(dashArray, dashPhase) {
  10479. this.current.dashArray = dashArray;
  10480. this.current.dashPhase = dashPhase;
  10481. }
  10482. constructPath(ops, args) {
  10483. const current = this.current;
  10484. let x = current.x,
  10485. y = current.y;
  10486. let d = [];
  10487. let j = 0;
  10488. for (const op of ops) {
  10489. switch (op | 0) {
  10490. case _util.OPS.rectangle:
  10491. x = args[j++];
  10492. y = args[j++];
  10493. const width = args[j++];
  10494. const height = args[j++];
  10495. const xw = x + width;
  10496. const yh = y + height;
  10497. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  10498. break;
  10499. case _util.OPS.moveTo:
  10500. x = args[j++];
  10501. y = args[j++];
  10502. d.push("M", pf(x), pf(y));
  10503. break;
  10504. case _util.OPS.lineTo:
  10505. x = args[j++];
  10506. y = args[j++];
  10507. d.push("L", pf(x), pf(y));
  10508. break;
  10509. case _util.OPS.curveTo:
  10510. x = args[j + 4];
  10511. y = args[j + 5];
  10512. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  10513. j += 6;
  10514. break;
  10515. case _util.OPS.curveTo2:
  10516. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  10517. x = args[j + 2];
  10518. y = args[j + 3];
  10519. j += 4;
  10520. break;
  10521. case _util.OPS.curveTo3:
  10522. x = args[j + 2];
  10523. y = args[j + 3];
  10524. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  10525. j += 4;
  10526. break;
  10527. case _util.OPS.closePath:
  10528. d.push("Z");
  10529. break;
  10530. }
  10531. }
  10532. d = d.join(" ");
  10533. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  10534. d = current.path.getAttributeNS(null, "d") + d;
  10535. } else {
  10536. current.path = this.svgFactory.createElement("svg:path");
  10537. this._ensureTransformGroup().appendChild(current.path);
  10538. }
  10539. current.path.setAttributeNS(null, "d", d);
  10540. current.path.setAttributeNS(null, "fill", "none");
  10541. current.element = current.path;
  10542. current.setCurrentPoint(x, y);
  10543. }
  10544. endPath() {
  10545. const current = this.current;
  10546. current.path = null;
  10547. if (!this.pendingClip) {
  10548. return;
  10549. }
  10550. if (!current.element) {
  10551. this.pendingClip = null;
  10552. return;
  10553. }
  10554. const clipId = `clippath${clipCount++}`;
  10555. const clipPath = this.svgFactory.createElement("svg:clipPath");
  10556. clipPath.setAttributeNS(null, "id", clipId);
  10557. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  10558. const clipElement = current.element.cloneNode(true);
  10559. if (this.pendingClip === "evenodd") {
  10560. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  10561. } else {
  10562. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  10563. }
  10564. this.pendingClip = null;
  10565. clipPath.appendChild(clipElement);
  10566. this.defs.appendChild(clipPath);
  10567. if (current.activeClipUrl) {
  10568. current.clipGroup = null;
  10569. for (const prev of this.extraStack) {
  10570. prev.clipGroup = null;
  10571. }
  10572. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  10573. }
  10574. current.activeClipUrl = `url(#${clipId})`;
  10575. this.tgrp = null;
  10576. }
  10577. clip(type) {
  10578. this.pendingClip = type;
  10579. }
  10580. closePath() {
  10581. const current = this.current;
  10582. if (current.path) {
  10583. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  10584. current.path.setAttributeNS(null, "d", d);
  10585. }
  10586. }
  10587. setLeading(leading) {
  10588. this.current.leading = -leading;
  10589. }
  10590. setTextRise(textRise) {
  10591. this.current.textRise = textRise;
  10592. }
  10593. setTextRenderingMode(textRenderingMode) {
  10594. this.current.textRenderingMode = textRenderingMode;
  10595. }
  10596. setHScale(scale) {
  10597. this.current.textHScale = scale / 100;
  10598. }
  10599. setRenderingIntent(intent) {}
  10600. setFlatness(flatness) {}
  10601. setGState(states) {
  10602. for (const [key, value] of states) {
  10603. switch (key) {
  10604. case "LW":
  10605. this.setLineWidth(value);
  10606. break;
  10607. case "LC":
  10608. this.setLineCap(value);
  10609. break;
  10610. case "LJ":
  10611. this.setLineJoin(value);
  10612. break;
  10613. case "ML":
  10614. this.setMiterLimit(value);
  10615. break;
  10616. case "D":
  10617. this.setDash(value[0], value[1]);
  10618. break;
  10619. case "RI":
  10620. this.setRenderingIntent(value);
  10621. break;
  10622. case "FL":
  10623. this.setFlatness(value);
  10624. break;
  10625. case "Font":
  10626. this.setFont(value);
  10627. break;
  10628. case "CA":
  10629. this.setStrokeAlpha(value);
  10630. break;
  10631. case "ca":
  10632. this.setFillAlpha(value);
  10633. break;
  10634. default:
  10635. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  10636. break;
  10637. }
  10638. }
  10639. }
  10640. fill() {
  10641. const current = this.current;
  10642. if (current.element) {
  10643. current.element.setAttributeNS(null, "fill", current.fillColor);
  10644. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  10645. this.endPath();
  10646. }
  10647. }
  10648. stroke() {
  10649. const current = this.current;
  10650. if (current.element) {
  10651. this._setStrokeAttributes(current.element);
  10652. current.element.setAttributeNS(null, "fill", "none");
  10653. this.endPath();
  10654. }
  10655. }
  10656. _setStrokeAttributes(element, lineWidthScale = 1) {
  10657. const current = this.current;
  10658. let dashArray = current.dashArray;
  10659. if (lineWidthScale !== 1 && dashArray.length > 0) {
  10660. dashArray = dashArray.map(function (value) {
  10661. return lineWidthScale * value;
  10662. });
  10663. }
  10664. element.setAttributeNS(null, "stroke", current.strokeColor);
  10665. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  10666. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  10667. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  10668. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  10669. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  10670. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  10671. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  10672. }
  10673. eoFill() {
  10674. if (this.current.element) {
  10675. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  10676. }
  10677. this.fill();
  10678. }
  10679. fillStroke() {
  10680. this.stroke();
  10681. this.fill();
  10682. }
  10683. eoFillStroke() {
  10684. if (this.current.element) {
  10685. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  10686. }
  10687. this.fillStroke();
  10688. }
  10689. closeStroke() {
  10690. this.closePath();
  10691. this.stroke();
  10692. }
  10693. closeFillStroke() {
  10694. this.closePath();
  10695. this.fillStroke();
  10696. }
  10697. closeEOFillStroke() {
  10698. this.closePath();
  10699. this.eoFillStroke();
  10700. }
  10701. paintSolidColorImageMask() {
  10702. const rect = this.svgFactory.createElement("svg:rect");
  10703. rect.setAttributeNS(null, "x", "0");
  10704. rect.setAttributeNS(null, "y", "0");
  10705. rect.setAttributeNS(null, "width", "1px");
  10706. rect.setAttributeNS(null, "height", "1px");
  10707. rect.setAttributeNS(null, "fill", this.current.fillColor);
  10708. this._ensureTransformGroup().appendChild(rect);
  10709. }
  10710. paintImageXObject(objId) {
  10711. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  10712. if (!imgData) {
  10713. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  10714. return;
  10715. }
  10716. this.paintInlineImageXObject(imgData);
  10717. }
  10718. paintInlineImageXObject(imgData, mask) {
  10719. const width = imgData.width;
  10720. const height = imgData.height;
  10721. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  10722. const cliprect = this.svgFactory.createElement("svg:rect");
  10723. cliprect.setAttributeNS(null, "x", "0");
  10724. cliprect.setAttributeNS(null, "y", "0");
  10725. cliprect.setAttributeNS(null, "width", pf(width));
  10726. cliprect.setAttributeNS(null, "height", pf(height));
  10727. this.current.element = cliprect;
  10728. this.clip("nonzero");
  10729. const imgEl = this.svgFactory.createElement("svg:image");
  10730. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  10731. imgEl.setAttributeNS(null, "x", "0");
  10732. imgEl.setAttributeNS(null, "y", pf(-height));
  10733. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  10734. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  10735. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  10736. if (mask) {
  10737. mask.appendChild(imgEl);
  10738. } else {
  10739. this._ensureTransformGroup().appendChild(imgEl);
  10740. }
  10741. }
  10742. paintImageMaskXObject(imgData) {
  10743. const current = this.current;
  10744. const width = imgData.width;
  10745. const height = imgData.height;
  10746. const fillColor = current.fillColor;
  10747. current.maskId = `mask${maskCount++}`;
  10748. const mask = this.svgFactory.createElement("svg:mask");
  10749. mask.setAttributeNS(null, "id", current.maskId);
  10750. const rect = this.svgFactory.createElement("svg:rect");
  10751. rect.setAttributeNS(null, "x", "0");
  10752. rect.setAttributeNS(null, "y", "0");
  10753. rect.setAttributeNS(null, "width", pf(width));
  10754. rect.setAttributeNS(null, "height", pf(height));
  10755. rect.setAttributeNS(null, "fill", fillColor);
  10756. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  10757. this.defs.appendChild(mask);
  10758. this._ensureTransformGroup().appendChild(rect);
  10759. this.paintInlineImageXObject(imgData, mask);
  10760. }
  10761. paintFormXObjectBegin(matrix, bbox) {
  10762. if (Array.isArray(matrix) && matrix.length === 6) {
  10763. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  10764. }
  10765. if (bbox) {
  10766. const width = bbox[2] - bbox[0];
  10767. const height = bbox[3] - bbox[1];
  10768. const cliprect = this.svgFactory.createElement("svg:rect");
  10769. cliprect.setAttributeNS(null, "x", bbox[0]);
  10770. cliprect.setAttributeNS(null, "y", bbox[1]);
  10771. cliprect.setAttributeNS(null, "width", pf(width));
  10772. cliprect.setAttributeNS(null, "height", pf(height));
  10773. this.current.element = cliprect;
  10774. this.clip("nonzero");
  10775. this.endPath();
  10776. }
  10777. }
  10778. paintFormXObjectEnd() {}
  10779. _initialize(viewport) {
  10780. const svg = this.svgFactory.create(viewport.width, viewport.height);
  10781. const definitions = this.svgFactory.createElement("svg:defs");
  10782. svg.appendChild(definitions);
  10783. this.defs = definitions;
  10784. const rootGroup = this.svgFactory.createElement("svg:g");
  10785. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  10786. svg.appendChild(rootGroup);
  10787. this.svg = rootGroup;
  10788. return svg;
  10789. }
  10790. _ensureClipGroup() {
  10791. if (!this.current.clipGroup) {
  10792. const clipGroup = this.svgFactory.createElement("svg:g");
  10793. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  10794. this.svg.appendChild(clipGroup);
  10795. this.current.clipGroup = clipGroup;
  10796. }
  10797. return this.current.clipGroup;
  10798. }
  10799. _ensureTransformGroup() {
  10800. if (!this.tgrp) {
  10801. this.tgrp = this.svgFactory.createElement("svg:g");
  10802. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  10803. if (this.current.activeClipUrl) {
  10804. this._ensureClipGroup().appendChild(this.tgrp);
  10805. } else {
  10806. this.svg.appendChild(this.tgrp);
  10807. }
  10808. }
  10809. return this.tgrp;
  10810. }
  10811. };
  10812. }
  10813. /***/ }),
  10814. /* 22 */
  10815. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10816. Object.defineProperty(exports, "__esModule", ({
  10817. value: true
  10818. }));
  10819. exports.XfaLayer = void 0;
  10820. var _util = __w_pdfjs_require__(2);
  10821. var _xfa_text = __w_pdfjs_require__(17);
  10822. class XfaLayer {
  10823. static setupStorage(html, id, element, storage, intent) {
  10824. const storedData = storage.getValue(id, {
  10825. value: null
  10826. });
  10827. switch (element.name) {
  10828. case "textarea":
  10829. if (storedData.value !== null) {
  10830. html.textContent = storedData.value;
  10831. }
  10832. if (intent === "print") {
  10833. break;
  10834. }
  10835. html.addEventListener("input", event => {
  10836. storage.setValue(id, {
  10837. value: event.target.value
  10838. });
  10839. });
  10840. break;
  10841. case "input":
  10842. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  10843. if (storedData.value === element.attributes.xfaOn) {
  10844. html.setAttribute("checked", true);
  10845. } else if (storedData.value === element.attributes.xfaOff) {
  10846. html.removeAttribute("checked");
  10847. }
  10848. if (intent === "print") {
  10849. break;
  10850. }
  10851. html.addEventListener("change", event => {
  10852. storage.setValue(id, {
  10853. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  10854. });
  10855. });
  10856. } else {
  10857. if (storedData.value !== null) {
  10858. html.setAttribute("value", storedData.value);
  10859. }
  10860. if (intent === "print") {
  10861. break;
  10862. }
  10863. html.addEventListener("input", event => {
  10864. storage.setValue(id, {
  10865. value: event.target.value
  10866. });
  10867. });
  10868. }
  10869. break;
  10870. case "select":
  10871. if (storedData.value !== null) {
  10872. for (const option of element.children) {
  10873. if (option.attributes.value === storedData.value) {
  10874. option.attributes.selected = true;
  10875. }
  10876. }
  10877. }
  10878. html.addEventListener("input", event => {
  10879. const options = event.target.options;
  10880. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  10881. storage.setValue(id, {
  10882. value
  10883. });
  10884. });
  10885. break;
  10886. }
  10887. }
  10888. static setAttributes({
  10889. html,
  10890. element,
  10891. storage = null,
  10892. intent,
  10893. linkService
  10894. }) {
  10895. const {
  10896. attributes
  10897. } = element;
  10898. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  10899. if (attributes.type === "radio") {
  10900. attributes.name = `${attributes.name}-${intent}`;
  10901. }
  10902. for (const [key, value] of Object.entries(attributes)) {
  10903. if (value === null || value === undefined || key === "dataId") {
  10904. continue;
  10905. }
  10906. if (key !== "style") {
  10907. if (key === "textContent") {
  10908. html.textContent = value;
  10909. } else if (key === "class") {
  10910. html.setAttribute(key, value.join(" "));
  10911. } else {
  10912. if (isHTMLAnchorElement && (key === "href" || key === "newWindow")) {
  10913. continue;
  10914. }
  10915. html.setAttribute(key, value);
  10916. }
  10917. } else {
  10918. Object.assign(html.style, value);
  10919. }
  10920. }
  10921. if (isHTMLAnchorElement) {
  10922. if (!linkService.addLinkAttributes) {
  10923. (0, _util.warn)("XfaLayer.setAttribute - missing `addLinkAttributes`-method on the `linkService`-instance.");
  10924. }
  10925. linkService.addLinkAttributes?.(html, attributes.href, attributes.newWindow);
  10926. }
  10927. if (storage && attributes.dataId) {
  10928. this.setupStorage(html, attributes.dataId, element, storage);
  10929. }
  10930. }
  10931. static render(parameters) {
  10932. const storage = parameters.annotationStorage;
  10933. const linkService = parameters.linkService;
  10934. const root = parameters.xfa;
  10935. const intent = parameters.intent || "display";
  10936. const rootHtml = document.createElement(root.name);
  10937. if (root.attributes) {
  10938. this.setAttributes({
  10939. html: rootHtml,
  10940. element: root,
  10941. intent,
  10942. linkService
  10943. });
  10944. }
  10945. const stack = [[root, -1, rootHtml]];
  10946. const rootDiv = parameters.div;
  10947. rootDiv.appendChild(rootHtml);
  10948. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  10949. rootDiv.style.transform = transform;
  10950. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  10951. const textDivs = [];
  10952. while (stack.length > 0) {
  10953. const [parent, i, html] = stack[stack.length - 1];
  10954. if (i + 1 === parent.children.length) {
  10955. stack.pop();
  10956. continue;
  10957. }
  10958. const child = parent.children[++stack[stack.length - 1][1]];
  10959. if (child === null) {
  10960. continue;
  10961. }
  10962. const {
  10963. name
  10964. } = child;
  10965. if (name === "#text") {
  10966. const node = document.createTextNode(child.value);
  10967. textDivs.push(node);
  10968. html.appendChild(node);
  10969. continue;
  10970. }
  10971. let childHtml;
  10972. if (child?.attributes?.xmlns) {
  10973. childHtml = document.createElementNS(child.attributes.xmlns, name);
  10974. } else {
  10975. childHtml = document.createElement(name);
  10976. }
  10977. html.appendChild(childHtml);
  10978. if (child.attributes) {
  10979. this.setAttributes({
  10980. html: childHtml,
  10981. element: child,
  10982. storage,
  10983. intent,
  10984. linkService
  10985. });
  10986. }
  10987. if (child.children && child.children.length > 0) {
  10988. stack.push([child, -1, childHtml]);
  10989. } else if (child.value) {
  10990. const node = document.createTextNode(child.value);
  10991. if (_xfa_text.XfaText.shouldBuildText(name)) {
  10992. textDivs.push(node);
  10993. }
  10994. childHtml.appendChild(node);
  10995. }
  10996. }
  10997. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  10998. el.setAttribute("readOnly", true);
  10999. }
  11000. return {
  11001. textDivs
  11002. };
  11003. }
  11004. static update(parameters) {
  11005. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  11006. parameters.div.style.transform = transform;
  11007. parameters.div.hidden = false;
  11008. }
  11009. }
  11010. exports.XfaLayer = XfaLayer;
  11011. /***/ }),
  11012. /* 23 */
  11013. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11014. Object.defineProperty(exports, "__esModule", ({
  11015. value: true
  11016. }));
  11017. exports.PDFNodeStream = void 0;
  11018. var _util = __w_pdfjs_require__(2);
  11019. var _network_utils = __w_pdfjs_require__(24);
  11020. ;
  11021. const fs = require("fs");
  11022. const http = require("http");
  11023. const https = require("https");
  11024. const url = require("url");
  11025. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  11026. function parseUrl(sourceUrl) {
  11027. const parsedUrl = url.parse(sourceUrl);
  11028. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  11029. return parsedUrl;
  11030. }
  11031. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  11032. return url.parse(`file:///${sourceUrl}`);
  11033. }
  11034. if (!parsedUrl.host) {
  11035. parsedUrl.protocol = "file:";
  11036. }
  11037. return parsedUrl;
  11038. }
  11039. class PDFNodeStream {
  11040. constructor(source) {
  11041. this.source = source;
  11042. this.url = parseUrl(source.url);
  11043. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  11044. this.isFsUrl = this.url.protocol === "file:";
  11045. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  11046. this._fullRequestReader = null;
  11047. this._rangeRequestReaders = [];
  11048. }
  11049. get _progressiveDataLength() {
  11050. return this._fullRequestReader?._loaded ?? 0;
  11051. }
  11052. getFullReader() {
  11053. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  11054. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  11055. return this._fullRequestReader;
  11056. }
  11057. getRangeReader(start, end) {
  11058. if (end <= this._progressiveDataLength) {
  11059. return null;
  11060. }
  11061. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  11062. this._rangeRequestReaders.push(rangeReader);
  11063. return rangeReader;
  11064. }
  11065. cancelAllRequests(reason) {
  11066. if (this._fullRequestReader) {
  11067. this._fullRequestReader.cancel(reason);
  11068. }
  11069. for (const reader of this._rangeRequestReaders.slice(0)) {
  11070. reader.cancel(reason);
  11071. }
  11072. }
  11073. }
  11074. exports.PDFNodeStream = PDFNodeStream;
  11075. class BaseFullReader {
  11076. constructor(stream) {
  11077. this._url = stream.url;
  11078. this._done = false;
  11079. this._storedError = null;
  11080. this.onProgress = null;
  11081. const source = stream.source;
  11082. this._contentLength = source.length;
  11083. this._loaded = 0;
  11084. this._filename = null;
  11085. this._disableRange = source.disableRange || false;
  11086. this._rangeChunkSize = source.rangeChunkSize;
  11087. if (!this._rangeChunkSize && !this._disableRange) {
  11088. this._disableRange = true;
  11089. }
  11090. this._isStreamingSupported = !source.disableStream;
  11091. this._isRangeSupported = !source.disableRange;
  11092. this._readableStream = null;
  11093. this._readCapability = (0, _util.createPromiseCapability)();
  11094. this._headersCapability = (0, _util.createPromiseCapability)();
  11095. }
  11096. get headersReady() {
  11097. return this._headersCapability.promise;
  11098. }
  11099. get filename() {
  11100. return this._filename;
  11101. }
  11102. get contentLength() {
  11103. return this._contentLength;
  11104. }
  11105. get isRangeSupported() {
  11106. return this._isRangeSupported;
  11107. }
  11108. get isStreamingSupported() {
  11109. return this._isStreamingSupported;
  11110. }
  11111. async read() {
  11112. await this._readCapability.promise;
  11113. if (this._done) {
  11114. return {
  11115. value: undefined,
  11116. done: true
  11117. };
  11118. }
  11119. if (this._storedError) {
  11120. throw this._storedError;
  11121. }
  11122. const chunk = this._readableStream.read();
  11123. if (chunk === null) {
  11124. this._readCapability = (0, _util.createPromiseCapability)();
  11125. return this.read();
  11126. }
  11127. this._loaded += chunk.length;
  11128. if (this.onProgress) {
  11129. this.onProgress({
  11130. loaded: this._loaded,
  11131. total: this._contentLength
  11132. });
  11133. }
  11134. const buffer = new Uint8Array(chunk).buffer;
  11135. return {
  11136. value: buffer,
  11137. done: false
  11138. };
  11139. }
  11140. cancel(reason) {
  11141. if (!this._readableStream) {
  11142. this._error(reason);
  11143. return;
  11144. }
  11145. this._readableStream.destroy(reason);
  11146. }
  11147. _error(reason) {
  11148. this._storedError = reason;
  11149. this._readCapability.resolve();
  11150. }
  11151. _setReadableStream(readableStream) {
  11152. this._readableStream = readableStream;
  11153. readableStream.on("readable", () => {
  11154. this._readCapability.resolve();
  11155. });
  11156. readableStream.on("end", () => {
  11157. readableStream.destroy();
  11158. this._done = true;
  11159. this._readCapability.resolve();
  11160. });
  11161. readableStream.on("error", reason => {
  11162. this._error(reason);
  11163. });
  11164. if (!this._isStreamingSupported && this._isRangeSupported) {
  11165. this._error(new _util.AbortException("streaming is disabled"));
  11166. }
  11167. if (this._storedError) {
  11168. this._readableStream.destroy(this._storedError);
  11169. }
  11170. }
  11171. }
  11172. class BaseRangeReader {
  11173. constructor(stream) {
  11174. this._url = stream.url;
  11175. this._done = false;
  11176. this._storedError = null;
  11177. this.onProgress = null;
  11178. this._loaded = 0;
  11179. this._readableStream = null;
  11180. this._readCapability = (0, _util.createPromiseCapability)();
  11181. const source = stream.source;
  11182. this._isStreamingSupported = !source.disableStream;
  11183. }
  11184. get isStreamingSupported() {
  11185. return this._isStreamingSupported;
  11186. }
  11187. async read() {
  11188. await this._readCapability.promise;
  11189. if (this._done) {
  11190. return {
  11191. value: undefined,
  11192. done: true
  11193. };
  11194. }
  11195. if (this._storedError) {
  11196. throw this._storedError;
  11197. }
  11198. const chunk = this._readableStream.read();
  11199. if (chunk === null) {
  11200. this._readCapability = (0, _util.createPromiseCapability)();
  11201. return this.read();
  11202. }
  11203. this._loaded += chunk.length;
  11204. if (this.onProgress) {
  11205. this.onProgress({
  11206. loaded: this._loaded
  11207. });
  11208. }
  11209. const buffer = new Uint8Array(chunk).buffer;
  11210. return {
  11211. value: buffer,
  11212. done: false
  11213. };
  11214. }
  11215. cancel(reason) {
  11216. if (!this._readableStream) {
  11217. this._error(reason);
  11218. return;
  11219. }
  11220. this._readableStream.destroy(reason);
  11221. }
  11222. _error(reason) {
  11223. this._storedError = reason;
  11224. this._readCapability.resolve();
  11225. }
  11226. _setReadableStream(readableStream) {
  11227. this._readableStream = readableStream;
  11228. readableStream.on("readable", () => {
  11229. this._readCapability.resolve();
  11230. });
  11231. readableStream.on("end", () => {
  11232. readableStream.destroy();
  11233. this._done = true;
  11234. this._readCapability.resolve();
  11235. });
  11236. readableStream.on("error", reason => {
  11237. this._error(reason);
  11238. });
  11239. if (this._storedError) {
  11240. this._readableStream.destroy(this._storedError);
  11241. }
  11242. }
  11243. }
  11244. function createRequestOptions(parsedUrl, headers) {
  11245. return {
  11246. protocol: parsedUrl.protocol,
  11247. auth: parsedUrl.auth,
  11248. host: parsedUrl.hostname,
  11249. port: parsedUrl.port,
  11250. path: parsedUrl.path,
  11251. method: "GET",
  11252. headers
  11253. };
  11254. }
  11255. class PDFNodeStreamFullReader extends BaseFullReader {
  11256. constructor(stream) {
  11257. super(stream);
  11258. const handleResponse = response => {
  11259. if (response.statusCode === 404) {
  11260. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  11261. this._storedError = error;
  11262. this._headersCapability.reject(error);
  11263. return;
  11264. }
  11265. this._headersCapability.resolve();
  11266. this._setReadableStream(response);
  11267. const getResponseHeader = name => {
  11268. return this._readableStream.headers[name.toLowerCase()];
  11269. };
  11270. const {
  11271. allowRangeRequests,
  11272. suggestedLength
  11273. } = (0, _network_utils.validateRangeRequestCapabilities)({
  11274. getResponseHeader,
  11275. isHttp: stream.isHttp,
  11276. rangeChunkSize: this._rangeChunkSize,
  11277. disableRange: this._disableRange
  11278. });
  11279. this._isRangeSupported = allowRangeRequests;
  11280. this._contentLength = suggestedLength || this._contentLength;
  11281. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  11282. };
  11283. this._request = null;
  11284. if (this._url.protocol === "http:") {
  11285. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  11286. } else {
  11287. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  11288. }
  11289. this._request.on("error", reason => {
  11290. this._storedError = reason;
  11291. this._headersCapability.reject(reason);
  11292. });
  11293. this._request.end();
  11294. }
  11295. }
  11296. class PDFNodeStreamRangeReader extends BaseRangeReader {
  11297. constructor(stream, start, end) {
  11298. super(stream);
  11299. this._httpHeaders = {};
  11300. for (const property in stream.httpHeaders) {
  11301. const value = stream.httpHeaders[property];
  11302. if (typeof value === "undefined") {
  11303. continue;
  11304. }
  11305. this._httpHeaders[property] = value;
  11306. }
  11307. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  11308. const handleResponse = response => {
  11309. if (response.statusCode === 404) {
  11310. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  11311. this._storedError = error;
  11312. return;
  11313. }
  11314. this._setReadableStream(response);
  11315. };
  11316. this._request = null;
  11317. if (this._url.protocol === "http:") {
  11318. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  11319. } else {
  11320. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  11321. }
  11322. this._request.on("error", reason => {
  11323. this._storedError = reason;
  11324. });
  11325. this._request.end();
  11326. }
  11327. }
  11328. class PDFNodeStreamFsFullReader extends BaseFullReader {
  11329. constructor(stream) {
  11330. super(stream);
  11331. let path = decodeURIComponent(this._url.path);
  11332. if (fileUriRegex.test(this._url.href)) {
  11333. path = path.replace(/^\//, "");
  11334. }
  11335. fs.lstat(path, (error, stat) => {
  11336. if (error) {
  11337. if (error.code === "ENOENT") {
  11338. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  11339. }
  11340. this._storedError = error;
  11341. this._headersCapability.reject(error);
  11342. return;
  11343. }
  11344. this._contentLength = stat.size;
  11345. this._setReadableStream(fs.createReadStream(path));
  11346. this._headersCapability.resolve();
  11347. });
  11348. }
  11349. }
  11350. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  11351. constructor(stream, start, end) {
  11352. super(stream);
  11353. let path = decodeURIComponent(this._url.path);
  11354. if (fileUriRegex.test(this._url.href)) {
  11355. path = path.replace(/^\//, "");
  11356. }
  11357. this._setReadableStream(fs.createReadStream(path, {
  11358. start,
  11359. end: end - 1
  11360. }));
  11361. }
  11362. }
  11363. /***/ }),
  11364. /* 24 */
  11365. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11366. Object.defineProperty(exports, "__esModule", ({
  11367. value: true
  11368. }));
  11369. exports.createResponseStatusError = createResponseStatusError;
  11370. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  11371. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  11372. exports.validateResponseStatus = validateResponseStatus;
  11373. var _util = __w_pdfjs_require__(2);
  11374. var _content_disposition = __w_pdfjs_require__(25);
  11375. var _display_utils = __w_pdfjs_require__(1);
  11376. function validateRangeRequestCapabilities({
  11377. getResponseHeader,
  11378. isHttp,
  11379. rangeChunkSize,
  11380. disableRange
  11381. }) {
  11382. (0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero");
  11383. const returnValues = {
  11384. allowRangeRequests: false,
  11385. suggestedLength: undefined
  11386. };
  11387. const length = parseInt(getResponseHeader("Content-Length"), 10);
  11388. if (!Number.isInteger(length)) {
  11389. return returnValues;
  11390. }
  11391. returnValues.suggestedLength = length;
  11392. if (length <= 2 * rangeChunkSize) {
  11393. return returnValues;
  11394. }
  11395. if (disableRange || !isHttp) {
  11396. return returnValues;
  11397. }
  11398. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  11399. return returnValues;
  11400. }
  11401. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  11402. if (contentEncoding !== "identity") {
  11403. return returnValues;
  11404. }
  11405. returnValues.allowRangeRequests = true;
  11406. return returnValues;
  11407. }
  11408. function extractFilenameFromHeader(getResponseHeader) {
  11409. const contentDisposition = getResponseHeader("Content-Disposition");
  11410. if (contentDisposition) {
  11411. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  11412. if (filename.includes("%")) {
  11413. try {
  11414. filename = decodeURIComponent(filename);
  11415. } catch (ex) {}
  11416. }
  11417. if ((0, _display_utils.isPdfFile)(filename)) {
  11418. return filename;
  11419. }
  11420. }
  11421. return null;
  11422. }
  11423. function createResponseStatusError(status, url) {
  11424. if (status === 404 || status === 0 && url.startsWith("file:")) {
  11425. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  11426. }
  11427. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  11428. }
  11429. function validateResponseStatus(status) {
  11430. return status === 200 || status === 206;
  11431. }
  11432. /***/ }),
  11433. /* 25 */
  11434. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11435. Object.defineProperty(exports, "__esModule", ({
  11436. value: true
  11437. }));
  11438. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  11439. var _util = __w_pdfjs_require__(2);
  11440. function getFilenameFromContentDispositionHeader(contentDisposition) {
  11441. let needsEncodingFixup = true;
  11442. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  11443. if (tmp) {
  11444. tmp = tmp[1];
  11445. let filename = rfc2616unquote(tmp);
  11446. filename = unescape(filename);
  11447. filename = rfc5987decode(filename);
  11448. filename = rfc2047decode(filename);
  11449. return fixupEncoding(filename);
  11450. }
  11451. tmp = rfc2231getparam(contentDisposition);
  11452. if (tmp) {
  11453. const filename = rfc2047decode(tmp);
  11454. return fixupEncoding(filename);
  11455. }
  11456. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  11457. if (tmp) {
  11458. tmp = tmp[1];
  11459. let filename = rfc2616unquote(tmp);
  11460. filename = rfc2047decode(filename);
  11461. return fixupEncoding(filename);
  11462. }
  11463. function toParamRegExp(attributePattern, flags) {
  11464. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  11465. }
  11466. function textdecode(encoding, value) {
  11467. if (encoding) {
  11468. if (!/^[\x00-\xFF]+$/.test(value)) {
  11469. return value;
  11470. }
  11471. try {
  11472. const decoder = new TextDecoder(encoding, {
  11473. fatal: true
  11474. });
  11475. const buffer = (0, _util.stringToBytes)(value);
  11476. value = decoder.decode(buffer);
  11477. needsEncodingFixup = false;
  11478. } catch (e) {
  11479. if (/^utf-?8$/i.test(encoding)) {
  11480. try {
  11481. value = decodeURIComponent(escape(value));
  11482. needsEncodingFixup = false;
  11483. } catch (err) {}
  11484. }
  11485. }
  11486. }
  11487. return value;
  11488. }
  11489. function fixupEncoding(value) {
  11490. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  11491. value = textdecode("utf-8", value);
  11492. if (needsEncodingFixup) {
  11493. value = textdecode("iso-8859-1", value);
  11494. }
  11495. }
  11496. return value;
  11497. }
  11498. function rfc2231getparam(contentDispositionStr) {
  11499. const matches = [];
  11500. let match;
  11501. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  11502. while ((match = iter.exec(contentDispositionStr)) !== null) {
  11503. let [, n, quot, part] = match;
  11504. n = parseInt(n, 10);
  11505. if (n in matches) {
  11506. if (n === 0) {
  11507. break;
  11508. }
  11509. continue;
  11510. }
  11511. matches[n] = [quot, part];
  11512. }
  11513. const parts = [];
  11514. for (let n = 0; n < matches.length; ++n) {
  11515. if (!(n in matches)) {
  11516. break;
  11517. }
  11518. let [quot, part] = matches[n];
  11519. part = rfc2616unquote(part);
  11520. if (quot) {
  11521. part = unescape(part);
  11522. if (n === 0) {
  11523. part = rfc5987decode(part);
  11524. }
  11525. }
  11526. parts.push(part);
  11527. }
  11528. return parts.join("");
  11529. }
  11530. function rfc2616unquote(value) {
  11531. if (value.startsWith('"')) {
  11532. const parts = value.slice(1).split('\\"');
  11533. for (let i = 0; i < parts.length; ++i) {
  11534. const quotindex = parts[i].indexOf('"');
  11535. if (quotindex !== -1) {
  11536. parts[i] = parts[i].slice(0, quotindex);
  11537. parts.length = i + 1;
  11538. }
  11539. parts[i] = parts[i].replace(/\\(.)/g, "$1");
  11540. }
  11541. value = parts.join('"');
  11542. }
  11543. return value;
  11544. }
  11545. function rfc5987decode(extvalue) {
  11546. const encodingend = extvalue.indexOf("'");
  11547. if (encodingend === -1) {
  11548. return extvalue;
  11549. }
  11550. const encoding = extvalue.slice(0, encodingend);
  11551. const langvalue = extvalue.slice(encodingend + 1);
  11552. const value = langvalue.replace(/^[^']*'/, "");
  11553. return textdecode(encoding, value);
  11554. }
  11555. function rfc2047decode(value) {
  11556. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  11557. return value;
  11558. }
  11559. return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  11560. if (encoding === "q" || encoding === "Q") {
  11561. text = text.replace(/_/g, " ");
  11562. text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  11563. return String.fromCharCode(parseInt(hex, 16));
  11564. });
  11565. return textdecode(charset, text);
  11566. }
  11567. try {
  11568. text = atob(text);
  11569. } catch (e) {}
  11570. return textdecode(charset, text);
  11571. });
  11572. }
  11573. return "";
  11574. }
  11575. /***/ }),
  11576. /* 26 */
  11577. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11578. Object.defineProperty(exports, "__esModule", ({
  11579. value: true
  11580. }));
  11581. exports.PDFNetworkStream = void 0;
  11582. var _util = __w_pdfjs_require__(2);
  11583. var _network_utils = __w_pdfjs_require__(24);
  11584. ;
  11585. const OK_RESPONSE = 200;
  11586. const PARTIAL_CONTENT_RESPONSE = 206;
  11587. function getArrayBuffer(xhr) {
  11588. const data = xhr.response;
  11589. if (typeof data !== "string") {
  11590. return data;
  11591. }
  11592. const array = (0, _util.stringToBytes)(data);
  11593. return array.buffer;
  11594. }
  11595. class NetworkManager {
  11596. constructor(url, args = {}) {
  11597. this.url = url;
  11598. this.isHttp = /^https?:/i.test(url);
  11599. this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
  11600. this.withCredentials = args.withCredentials || false;
  11601. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  11602. return new XMLHttpRequest();
  11603. };
  11604. this.currXhrId = 0;
  11605. this.pendingRequests = Object.create(null);
  11606. }
  11607. requestRange(begin, end, listeners) {
  11608. const args = {
  11609. begin,
  11610. end
  11611. };
  11612. for (const prop in listeners) {
  11613. args[prop] = listeners[prop];
  11614. }
  11615. return this.request(args);
  11616. }
  11617. requestFull(listeners) {
  11618. return this.request(listeners);
  11619. }
  11620. request(args) {
  11621. const xhr = this.getXhr();
  11622. const xhrId = this.currXhrId++;
  11623. const pendingRequest = this.pendingRequests[xhrId] = {
  11624. xhr
  11625. };
  11626. xhr.open("GET", this.url);
  11627. xhr.withCredentials = this.withCredentials;
  11628. for (const property in this.httpHeaders) {
  11629. const value = this.httpHeaders[property];
  11630. if (typeof value === "undefined") {
  11631. continue;
  11632. }
  11633. xhr.setRequestHeader(property, value);
  11634. }
  11635. if (this.isHttp && "begin" in args && "end" in args) {
  11636. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  11637. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  11638. } else {
  11639. pendingRequest.expectedStatus = OK_RESPONSE;
  11640. }
  11641. xhr.responseType = "arraybuffer";
  11642. if (args.onError) {
  11643. xhr.onerror = function (evt) {
  11644. args.onError(xhr.status);
  11645. };
  11646. }
  11647. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  11648. xhr.onprogress = this.onProgress.bind(this, xhrId);
  11649. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  11650. pendingRequest.onDone = args.onDone;
  11651. pendingRequest.onError = args.onError;
  11652. pendingRequest.onProgress = args.onProgress;
  11653. xhr.send(null);
  11654. return xhrId;
  11655. }
  11656. onProgress(xhrId, evt) {
  11657. const pendingRequest = this.pendingRequests[xhrId];
  11658. if (!pendingRequest) {
  11659. return;
  11660. }
  11661. pendingRequest.onProgress?.(evt);
  11662. }
  11663. onStateChange(xhrId, evt) {
  11664. const pendingRequest = this.pendingRequests[xhrId];
  11665. if (!pendingRequest) {
  11666. return;
  11667. }
  11668. const xhr = pendingRequest.xhr;
  11669. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  11670. pendingRequest.onHeadersReceived();
  11671. delete pendingRequest.onHeadersReceived;
  11672. }
  11673. if (xhr.readyState !== 4) {
  11674. return;
  11675. }
  11676. if (!(xhrId in this.pendingRequests)) {
  11677. return;
  11678. }
  11679. delete this.pendingRequests[xhrId];
  11680. if (xhr.status === 0 && this.isHttp) {
  11681. pendingRequest.onError?.(xhr.status);
  11682. return;
  11683. }
  11684. const xhrStatus = xhr.status || OK_RESPONSE;
  11685. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  11686. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  11687. pendingRequest.onError?.(xhr.status);
  11688. return;
  11689. }
  11690. const chunk = getArrayBuffer(xhr);
  11691. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  11692. const rangeHeader = xhr.getResponseHeader("Content-Range");
  11693. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  11694. pendingRequest.onDone({
  11695. begin: parseInt(matches[1], 10),
  11696. chunk
  11697. });
  11698. } else if (chunk) {
  11699. pendingRequest.onDone({
  11700. begin: 0,
  11701. chunk
  11702. });
  11703. } else {
  11704. pendingRequest.onError?.(xhr.status);
  11705. }
  11706. }
  11707. getRequestXhr(xhrId) {
  11708. return this.pendingRequests[xhrId].xhr;
  11709. }
  11710. isPendingRequest(xhrId) {
  11711. return xhrId in this.pendingRequests;
  11712. }
  11713. abortRequest(xhrId) {
  11714. const xhr = this.pendingRequests[xhrId].xhr;
  11715. delete this.pendingRequests[xhrId];
  11716. xhr.abort();
  11717. }
  11718. }
  11719. class PDFNetworkStream {
  11720. constructor(source) {
  11721. this._source = source;
  11722. this._manager = new NetworkManager(source.url, {
  11723. httpHeaders: source.httpHeaders,
  11724. withCredentials: source.withCredentials
  11725. });
  11726. this._rangeChunkSize = source.rangeChunkSize;
  11727. this._fullRequestReader = null;
  11728. this._rangeRequestReaders = [];
  11729. }
  11730. _onRangeRequestReaderClosed(reader) {
  11731. const i = this._rangeRequestReaders.indexOf(reader);
  11732. if (i >= 0) {
  11733. this._rangeRequestReaders.splice(i, 1);
  11734. }
  11735. }
  11736. getFullReader() {
  11737. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  11738. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  11739. return this._fullRequestReader;
  11740. }
  11741. getRangeReader(begin, end) {
  11742. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  11743. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  11744. this._rangeRequestReaders.push(reader);
  11745. return reader;
  11746. }
  11747. cancelAllRequests(reason) {
  11748. this._fullRequestReader?.cancel(reason);
  11749. for (const reader of this._rangeRequestReaders.slice(0)) {
  11750. reader.cancel(reason);
  11751. }
  11752. }
  11753. }
  11754. exports.PDFNetworkStream = PDFNetworkStream;
  11755. class PDFNetworkStreamFullRequestReader {
  11756. constructor(manager, source) {
  11757. this._manager = manager;
  11758. const args = {
  11759. onHeadersReceived: this._onHeadersReceived.bind(this),
  11760. onDone: this._onDone.bind(this),
  11761. onError: this._onError.bind(this),
  11762. onProgress: this._onProgress.bind(this)
  11763. };
  11764. this._url = source.url;
  11765. this._fullRequestId = manager.requestFull(args);
  11766. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  11767. this._disableRange = source.disableRange || false;
  11768. this._contentLength = source.length;
  11769. this._rangeChunkSize = source.rangeChunkSize;
  11770. if (!this._rangeChunkSize && !this._disableRange) {
  11771. this._disableRange = true;
  11772. }
  11773. this._isStreamingSupported = false;
  11774. this._isRangeSupported = false;
  11775. this._cachedChunks = [];
  11776. this._requests = [];
  11777. this._done = false;
  11778. this._storedError = undefined;
  11779. this._filename = null;
  11780. this.onProgress = null;
  11781. }
  11782. _onHeadersReceived() {
  11783. const fullRequestXhrId = this._fullRequestId;
  11784. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  11785. const getResponseHeader = name => {
  11786. return fullRequestXhr.getResponseHeader(name);
  11787. };
  11788. const {
  11789. allowRangeRequests,
  11790. suggestedLength
  11791. } = (0, _network_utils.validateRangeRequestCapabilities)({
  11792. getResponseHeader,
  11793. isHttp: this._manager.isHttp,
  11794. rangeChunkSize: this._rangeChunkSize,
  11795. disableRange: this._disableRange
  11796. });
  11797. if (allowRangeRequests) {
  11798. this._isRangeSupported = true;
  11799. }
  11800. this._contentLength = suggestedLength || this._contentLength;
  11801. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  11802. if (this._isRangeSupported) {
  11803. this._manager.abortRequest(fullRequestXhrId);
  11804. }
  11805. this._headersReceivedCapability.resolve();
  11806. }
  11807. _onDone(data) {
  11808. if (data) {
  11809. if (this._requests.length > 0) {
  11810. const requestCapability = this._requests.shift();
  11811. requestCapability.resolve({
  11812. value: data.chunk,
  11813. done: false
  11814. });
  11815. } else {
  11816. this._cachedChunks.push(data.chunk);
  11817. }
  11818. }
  11819. this._done = true;
  11820. if (this._cachedChunks.length > 0) {
  11821. return;
  11822. }
  11823. for (const requestCapability of this._requests) {
  11824. requestCapability.resolve({
  11825. value: undefined,
  11826. done: true
  11827. });
  11828. }
  11829. this._requests.length = 0;
  11830. }
  11831. _onError(status) {
  11832. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  11833. this._headersReceivedCapability.reject(this._storedError);
  11834. for (const requestCapability of this._requests) {
  11835. requestCapability.reject(this._storedError);
  11836. }
  11837. this._requests.length = 0;
  11838. this._cachedChunks.length = 0;
  11839. }
  11840. _onProgress(evt) {
  11841. this.onProgress?.({
  11842. loaded: evt.loaded,
  11843. total: evt.lengthComputable ? evt.total : this._contentLength
  11844. });
  11845. }
  11846. get filename() {
  11847. return this._filename;
  11848. }
  11849. get isRangeSupported() {
  11850. return this._isRangeSupported;
  11851. }
  11852. get isStreamingSupported() {
  11853. return this._isStreamingSupported;
  11854. }
  11855. get contentLength() {
  11856. return this._contentLength;
  11857. }
  11858. get headersReady() {
  11859. return this._headersReceivedCapability.promise;
  11860. }
  11861. async read() {
  11862. if (this._storedError) {
  11863. throw this._storedError;
  11864. }
  11865. if (this._cachedChunks.length > 0) {
  11866. const chunk = this._cachedChunks.shift();
  11867. return {
  11868. value: chunk,
  11869. done: false
  11870. };
  11871. }
  11872. if (this._done) {
  11873. return {
  11874. value: undefined,
  11875. done: true
  11876. };
  11877. }
  11878. const requestCapability = (0, _util.createPromiseCapability)();
  11879. this._requests.push(requestCapability);
  11880. return requestCapability.promise;
  11881. }
  11882. cancel(reason) {
  11883. this._done = true;
  11884. this._headersReceivedCapability.reject(reason);
  11885. for (const requestCapability of this._requests) {
  11886. requestCapability.resolve({
  11887. value: undefined,
  11888. done: true
  11889. });
  11890. }
  11891. this._requests.length = 0;
  11892. if (this._manager.isPendingRequest(this._fullRequestId)) {
  11893. this._manager.abortRequest(this._fullRequestId);
  11894. }
  11895. this._fullRequestReader = null;
  11896. }
  11897. }
  11898. class PDFNetworkStreamRangeRequestReader {
  11899. constructor(manager, begin, end) {
  11900. this._manager = manager;
  11901. const args = {
  11902. onDone: this._onDone.bind(this),
  11903. onError: this._onError.bind(this),
  11904. onProgress: this._onProgress.bind(this)
  11905. };
  11906. this._url = manager.url;
  11907. this._requestId = manager.requestRange(begin, end, args);
  11908. this._requests = [];
  11909. this._queuedChunk = null;
  11910. this._done = false;
  11911. this._storedError = undefined;
  11912. this.onProgress = null;
  11913. this.onClosed = null;
  11914. }
  11915. _close() {
  11916. this.onClosed?.(this);
  11917. }
  11918. _onDone(data) {
  11919. const chunk = data.chunk;
  11920. if (this._requests.length > 0) {
  11921. const requestCapability = this._requests.shift();
  11922. requestCapability.resolve({
  11923. value: chunk,
  11924. done: false
  11925. });
  11926. } else {
  11927. this._queuedChunk = chunk;
  11928. }
  11929. this._done = true;
  11930. for (const requestCapability of this._requests) {
  11931. requestCapability.resolve({
  11932. value: undefined,
  11933. done: true
  11934. });
  11935. }
  11936. this._requests.length = 0;
  11937. this._close();
  11938. }
  11939. _onError(status) {
  11940. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  11941. for (const requestCapability of this._requests) {
  11942. requestCapability.reject(this._storedError);
  11943. }
  11944. this._requests.length = 0;
  11945. this._queuedChunk = null;
  11946. }
  11947. _onProgress(evt) {
  11948. if (!this.isStreamingSupported) {
  11949. this.onProgress?.({
  11950. loaded: evt.loaded
  11951. });
  11952. }
  11953. }
  11954. get isStreamingSupported() {
  11955. return false;
  11956. }
  11957. async read() {
  11958. if (this._storedError) {
  11959. throw this._storedError;
  11960. }
  11961. if (this._queuedChunk !== null) {
  11962. const chunk = this._queuedChunk;
  11963. this._queuedChunk = null;
  11964. return {
  11965. value: chunk,
  11966. done: false
  11967. };
  11968. }
  11969. if (this._done) {
  11970. return {
  11971. value: undefined,
  11972. done: true
  11973. };
  11974. }
  11975. const requestCapability = (0, _util.createPromiseCapability)();
  11976. this._requests.push(requestCapability);
  11977. return requestCapability.promise;
  11978. }
  11979. cancel(reason) {
  11980. this._done = true;
  11981. for (const requestCapability of this._requests) {
  11982. requestCapability.resolve({
  11983. value: undefined,
  11984. done: true
  11985. });
  11986. }
  11987. this._requests.length = 0;
  11988. if (this._manager.isPendingRequest(this._requestId)) {
  11989. this._manager.abortRequest(this._requestId);
  11990. }
  11991. this._close();
  11992. }
  11993. }
  11994. /***/ }),
  11995. /* 27 */
  11996. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11997. Object.defineProperty(exports, "__esModule", ({
  11998. value: true
  11999. }));
  12000. exports.PDFFetchStream = void 0;
  12001. var _util = __w_pdfjs_require__(2);
  12002. var _network_utils = __w_pdfjs_require__(24);
  12003. ;
  12004. function createFetchOptions(headers, withCredentials, abortController) {
  12005. return {
  12006. method: "GET",
  12007. headers,
  12008. signal: abortController?.signal,
  12009. mode: "cors",
  12010. credentials: withCredentials ? "include" : "same-origin",
  12011. redirect: "follow"
  12012. };
  12013. }
  12014. function createHeaders(httpHeaders) {
  12015. const headers = new Headers();
  12016. for (const property in httpHeaders) {
  12017. const value = httpHeaders[property];
  12018. if (typeof value === "undefined") {
  12019. continue;
  12020. }
  12021. headers.append(property, value);
  12022. }
  12023. return headers;
  12024. }
  12025. class PDFFetchStream {
  12026. constructor(source) {
  12027. this.source = source;
  12028. this.isHttp = /^https?:/i.test(source.url);
  12029. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  12030. this._fullRequestReader = null;
  12031. this._rangeRequestReaders = [];
  12032. }
  12033. get _progressiveDataLength() {
  12034. return this._fullRequestReader?._loaded ?? 0;
  12035. }
  12036. getFullReader() {
  12037. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  12038. this._fullRequestReader = new PDFFetchStreamReader(this);
  12039. return this._fullRequestReader;
  12040. }
  12041. getRangeReader(begin, end) {
  12042. if (end <= this._progressiveDataLength) {
  12043. return null;
  12044. }
  12045. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  12046. this._rangeRequestReaders.push(reader);
  12047. return reader;
  12048. }
  12049. cancelAllRequests(reason) {
  12050. if (this._fullRequestReader) {
  12051. this._fullRequestReader.cancel(reason);
  12052. }
  12053. for (const reader of this._rangeRequestReaders.slice(0)) {
  12054. reader.cancel(reason);
  12055. }
  12056. }
  12057. }
  12058. exports.PDFFetchStream = PDFFetchStream;
  12059. class PDFFetchStreamReader {
  12060. constructor(stream) {
  12061. this._stream = stream;
  12062. this._reader = null;
  12063. this._loaded = 0;
  12064. this._filename = null;
  12065. const source = stream.source;
  12066. this._withCredentials = source.withCredentials || false;
  12067. this._contentLength = source.length;
  12068. this._headersCapability = (0, _util.createPromiseCapability)();
  12069. this._disableRange = source.disableRange || false;
  12070. this._rangeChunkSize = source.rangeChunkSize;
  12071. if (!this._rangeChunkSize && !this._disableRange) {
  12072. this._disableRange = true;
  12073. }
  12074. if (typeof AbortController !== "undefined") {
  12075. this._abortController = new AbortController();
  12076. }
  12077. this._isStreamingSupported = !source.disableStream;
  12078. this._isRangeSupported = !source.disableRange;
  12079. this._headers = createHeaders(this._stream.httpHeaders);
  12080. const url = source.url;
  12081. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  12082. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  12083. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  12084. }
  12085. this._reader = response.body.getReader();
  12086. this._headersCapability.resolve();
  12087. const getResponseHeader = name => {
  12088. return response.headers.get(name);
  12089. };
  12090. const {
  12091. allowRangeRequests,
  12092. suggestedLength
  12093. } = (0, _network_utils.validateRangeRequestCapabilities)({
  12094. getResponseHeader,
  12095. isHttp: this._stream.isHttp,
  12096. rangeChunkSize: this._rangeChunkSize,
  12097. disableRange: this._disableRange
  12098. });
  12099. this._isRangeSupported = allowRangeRequests;
  12100. this._contentLength = suggestedLength || this._contentLength;
  12101. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  12102. if (!this._isStreamingSupported && this._isRangeSupported) {
  12103. this.cancel(new _util.AbortException("Streaming is disabled."));
  12104. }
  12105. }).catch(this._headersCapability.reject);
  12106. this.onProgress = null;
  12107. }
  12108. get headersReady() {
  12109. return this._headersCapability.promise;
  12110. }
  12111. get filename() {
  12112. return this._filename;
  12113. }
  12114. get contentLength() {
  12115. return this._contentLength;
  12116. }
  12117. get isRangeSupported() {
  12118. return this._isRangeSupported;
  12119. }
  12120. get isStreamingSupported() {
  12121. return this._isStreamingSupported;
  12122. }
  12123. async read() {
  12124. await this._headersCapability.promise;
  12125. const {
  12126. value,
  12127. done
  12128. } = await this._reader.read();
  12129. if (done) {
  12130. return {
  12131. value,
  12132. done
  12133. };
  12134. }
  12135. this._loaded += value.byteLength;
  12136. if (this.onProgress) {
  12137. this.onProgress({
  12138. loaded: this._loaded,
  12139. total: this._contentLength
  12140. });
  12141. }
  12142. const buffer = new Uint8Array(value).buffer;
  12143. return {
  12144. value: buffer,
  12145. done: false
  12146. };
  12147. }
  12148. cancel(reason) {
  12149. if (this._reader) {
  12150. this._reader.cancel(reason);
  12151. }
  12152. if (this._abortController) {
  12153. this._abortController.abort();
  12154. }
  12155. }
  12156. }
  12157. class PDFFetchStreamRangeReader {
  12158. constructor(stream, begin, end) {
  12159. this._stream = stream;
  12160. this._reader = null;
  12161. this._loaded = 0;
  12162. const source = stream.source;
  12163. this._withCredentials = source.withCredentials || false;
  12164. this._readCapability = (0, _util.createPromiseCapability)();
  12165. this._isStreamingSupported = !source.disableStream;
  12166. if (typeof AbortController !== "undefined") {
  12167. this._abortController = new AbortController();
  12168. }
  12169. this._headers = createHeaders(this._stream.httpHeaders);
  12170. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  12171. const url = source.url;
  12172. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  12173. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  12174. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  12175. }
  12176. this._readCapability.resolve();
  12177. this._reader = response.body.getReader();
  12178. }).catch(this._readCapability.reject);
  12179. this.onProgress = null;
  12180. }
  12181. get isStreamingSupported() {
  12182. return this._isStreamingSupported;
  12183. }
  12184. async read() {
  12185. await this._readCapability.promise;
  12186. const {
  12187. value,
  12188. done
  12189. } = await this._reader.read();
  12190. if (done) {
  12191. return {
  12192. value,
  12193. done
  12194. };
  12195. }
  12196. this._loaded += value.byteLength;
  12197. if (this.onProgress) {
  12198. this.onProgress({
  12199. loaded: this._loaded
  12200. });
  12201. }
  12202. const buffer = new Uint8Array(value).buffer;
  12203. return {
  12204. value: buffer,
  12205. done: false
  12206. };
  12207. }
  12208. cancel(reason) {
  12209. if (this._reader) {
  12210. this._reader.cancel(reason);
  12211. }
  12212. if (this._abortController) {
  12213. this._abortController.abort();
  12214. }
  12215. }
  12216. }
  12217. /***/ })
  12218. /******/ ]);
  12219. /************************************************************************/
  12220. /******/ // The module cache
  12221. /******/ var __webpack_module_cache__ = {};
  12222. /******/
  12223. /******/ // The require function
  12224. /******/ function __w_pdfjs_require__(moduleId) {
  12225. /******/ // Check if module is in cache
  12226. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  12227. /******/ if (cachedModule !== undefined) {
  12228. /******/ return cachedModule.exports;
  12229. /******/ }
  12230. /******/ // Create a new module (and put it into the cache)
  12231. /******/ var module = __webpack_module_cache__[moduleId] = {
  12232. /******/ // no module.id needed
  12233. /******/ // no module.loaded needed
  12234. /******/ exports: {}
  12235. /******/ };
  12236. /******/
  12237. /******/ // Execute the module function
  12238. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  12239. /******/
  12240. /******/ // Return the exports of the module
  12241. /******/ return module.exports;
  12242. /******/ }
  12243. /******/
  12244. /************************************************************************/
  12245. var __webpack_exports__ = {};
  12246. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  12247. (() => {
  12248. var exports = __webpack_exports__;
  12249. Object.defineProperty(exports, "__esModule", ({
  12250. value: true
  12251. }));
  12252. Object.defineProperty(exports, "addLinkAttributes", ({
  12253. enumerable: true,
  12254. get: function () {
  12255. return _display_utils.addLinkAttributes;
  12256. }
  12257. }));
  12258. Object.defineProperty(exports, "getFilenameFromUrl", ({
  12259. enumerable: true,
  12260. get: function () {
  12261. return _display_utils.getFilenameFromUrl;
  12262. }
  12263. }));
  12264. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  12265. enumerable: true,
  12266. get: function () {
  12267. return _display_utils.getPdfFilenameFromUrl;
  12268. }
  12269. }));
  12270. Object.defineProperty(exports, "getXfaPageViewport", ({
  12271. enumerable: true,
  12272. get: function () {
  12273. return _display_utils.getXfaPageViewport;
  12274. }
  12275. }));
  12276. Object.defineProperty(exports, "isPdfFile", ({
  12277. enumerable: true,
  12278. get: function () {
  12279. return _display_utils.isPdfFile;
  12280. }
  12281. }));
  12282. Object.defineProperty(exports, "LinkTarget", ({
  12283. enumerable: true,
  12284. get: function () {
  12285. return _display_utils.LinkTarget;
  12286. }
  12287. }));
  12288. Object.defineProperty(exports, "loadScript", ({
  12289. enumerable: true,
  12290. get: function () {
  12291. return _display_utils.loadScript;
  12292. }
  12293. }));
  12294. Object.defineProperty(exports, "PDFDateString", ({
  12295. enumerable: true,
  12296. get: function () {
  12297. return _display_utils.PDFDateString;
  12298. }
  12299. }));
  12300. Object.defineProperty(exports, "PixelsPerInch", ({
  12301. enumerable: true,
  12302. get: function () {
  12303. return _display_utils.PixelsPerInch;
  12304. }
  12305. }));
  12306. Object.defineProperty(exports, "RenderingCancelledException", ({
  12307. enumerable: true,
  12308. get: function () {
  12309. return _display_utils.RenderingCancelledException;
  12310. }
  12311. }));
  12312. Object.defineProperty(exports, "AnnotationMode", ({
  12313. enumerable: true,
  12314. get: function () {
  12315. return _util.AnnotationMode;
  12316. }
  12317. }));
  12318. Object.defineProperty(exports, "CMapCompressionType", ({
  12319. enumerable: true,
  12320. get: function () {
  12321. return _util.CMapCompressionType;
  12322. }
  12323. }));
  12324. Object.defineProperty(exports, "createObjectURL", ({
  12325. enumerable: true,
  12326. get: function () {
  12327. return _util.createObjectURL;
  12328. }
  12329. }));
  12330. Object.defineProperty(exports, "createPromiseCapability", ({
  12331. enumerable: true,
  12332. get: function () {
  12333. return _util.createPromiseCapability;
  12334. }
  12335. }));
  12336. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  12337. enumerable: true,
  12338. get: function () {
  12339. return _util.createValidAbsoluteUrl;
  12340. }
  12341. }));
  12342. Object.defineProperty(exports, "InvalidPDFException", ({
  12343. enumerable: true,
  12344. get: function () {
  12345. return _util.InvalidPDFException;
  12346. }
  12347. }));
  12348. Object.defineProperty(exports, "MissingPDFException", ({
  12349. enumerable: true,
  12350. get: function () {
  12351. return _util.MissingPDFException;
  12352. }
  12353. }));
  12354. Object.defineProperty(exports, "OPS", ({
  12355. enumerable: true,
  12356. get: function () {
  12357. return _util.OPS;
  12358. }
  12359. }));
  12360. Object.defineProperty(exports, "PasswordResponses", ({
  12361. enumerable: true,
  12362. get: function () {
  12363. return _util.PasswordResponses;
  12364. }
  12365. }));
  12366. Object.defineProperty(exports, "PermissionFlag", ({
  12367. enumerable: true,
  12368. get: function () {
  12369. return _util.PermissionFlag;
  12370. }
  12371. }));
  12372. Object.defineProperty(exports, "removeNullCharacters", ({
  12373. enumerable: true,
  12374. get: function () {
  12375. return _util.removeNullCharacters;
  12376. }
  12377. }));
  12378. Object.defineProperty(exports, "shadow", ({
  12379. enumerable: true,
  12380. get: function () {
  12381. return _util.shadow;
  12382. }
  12383. }));
  12384. Object.defineProperty(exports, "UnexpectedResponseException", ({
  12385. enumerable: true,
  12386. get: function () {
  12387. return _util.UnexpectedResponseException;
  12388. }
  12389. }));
  12390. Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  12391. enumerable: true,
  12392. get: function () {
  12393. return _util.UNSUPPORTED_FEATURES;
  12394. }
  12395. }));
  12396. Object.defineProperty(exports, "Util", ({
  12397. enumerable: true,
  12398. get: function () {
  12399. return _util.Util;
  12400. }
  12401. }));
  12402. Object.defineProperty(exports, "VerbosityLevel", ({
  12403. enumerable: true,
  12404. get: function () {
  12405. return _util.VerbosityLevel;
  12406. }
  12407. }));
  12408. Object.defineProperty(exports, "build", ({
  12409. enumerable: true,
  12410. get: function () {
  12411. return _api.build;
  12412. }
  12413. }));
  12414. Object.defineProperty(exports, "getDocument", ({
  12415. enumerable: true,
  12416. get: function () {
  12417. return _api.getDocument;
  12418. }
  12419. }));
  12420. Object.defineProperty(exports, "LoopbackPort", ({
  12421. enumerable: true,
  12422. get: function () {
  12423. return _api.LoopbackPort;
  12424. }
  12425. }));
  12426. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  12427. enumerable: true,
  12428. get: function () {
  12429. return _api.PDFDataRangeTransport;
  12430. }
  12431. }));
  12432. Object.defineProperty(exports, "PDFWorker", ({
  12433. enumerable: true,
  12434. get: function () {
  12435. return _api.PDFWorker;
  12436. }
  12437. }));
  12438. Object.defineProperty(exports, "version", ({
  12439. enumerable: true,
  12440. get: function () {
  12441. return _api.version;
  12442. }
  12443. }));
  12444. Object.defineProperty(exports, "AnnotationLayer", ({
  12445. enumerable: true,
  12446. get: function () {
  12447. return _annotation_layer.AnnotationLayer;
  12448. }
  12449. }));
  12450. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  12451. enumerable: true,
  12452. get: function () {
  12453. return _worker_options.GlobalWorkerOptions;
  12454. }
  12455. }));
  12456. Object.defineProperty(exports, "renderTextLayer", ({
  12457. enumerable: true,
  12458. get: function () {
  12459. return _text_layer.renderTextLayer;
  12460. }
  12461. }));
  12462. Object.defineProperty(exports, "SVGGraphics", ({
  12463. enumerable: true,
  12464. get: function () {
  12465. return _svg.SVGGraphics;
  12466. }
  12467. }));
  12468. Object.defineProperty(exports, "XfaLayer", ({
  12469. enumerable: true,
  12470. get: function () {
  12471. return _xfa_layer.XfaLayer;
  12472. }
  12473. }));
  12474. var _display_utils = __w_pdfjs_require__(1);
  12475. var _util = __w_pdfjs_require__(2);
  12476. var _api = __w_pdfjs_require__(6);
  12477. var _annotation_layer = __w_pdfjs_require__(18);
  12478. var _worker_options = __w_pdfjs_require__(12);
  12479. var _is_node = __w_pdfjs_require__(4);
  12480. var _text_layer = __w_pdfjs_require__(20);
  12481. var _svg = __w_pdfjs_require__(21);
  12482. var _xfa_layer = __w_pdfjs_require__(22);
  12483. const pdfjsVersion = '2.11.338';
  12484. const pdfjsBuild = 'dedff3c98';
  12485. {
  12486. if (_is_node.isNodeJS) {
  12487. const {
  12488. PDFNodeStream
  12489. } = __w_pdfjs_require__(23);
  12490. (0, _api.setPDFNetworkStreamFactory)(params => {
  12491. return new PDFNodeStream(params);
  12492. });
  12493. } else {
  12494. const {
  12495. PDFNetworkStream
  12496. } = __w_pdfjs_require__(26);
  12497. const {
  12498. PDFFetchStream
  12499. } = __w_pdfjs_require__(27);
  12500. (0, _api.setPDFNetworkStreamFactory)(params => {
  12501. if ((0, _display_utils.isValidFetchUrl)(params.url)) {
  12502. return new PDFFetchStream(params);
  12503. }
  12504. return new PDFNetworkStream(params);
  12505. });
  12506. }
  12507. }
  12508. })();
  12509. /******/ return __webpack_exports__;
  12510. /******/ })()
  12511. ;
  12512. });
  12513. //# sourceMappingURL=pdf.js.map