pdf.js 386 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840
  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.PDFDateString = exports.PageViewport = exports.LinkTarget = exports.DOMSVGFactory = exports.DOMStandardFontDataFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = 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. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  55. const SVG_NS = "http://www.w3.org/2000/svg";
  56. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  57. constructor({
  58. ownerDocument = globalThis.document
  59. } = {}) {
  60. super();
  61. this._document = ownerDocument;
  62. }
  63. _createCanvas(width, height) {
  64. const canvas = this._document.createElement("canvas");
  65. canvas.width = width;
  66. canvas.height = height;
  67. return canvas;
  68. }
  69. }
  70. exports.DOMCanvasFactory = DOMCanvasFactory;
  71. async function fetchData(url, asTypedArray = false) {
  72. if (isValidFetchUrl(url, document.baseURI)) {
  73. const response = await fetch(url);
  74. if (!response.ok) {
  75. throw new Error(response.statusText);
  76. }
  77. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  78. }
  79. return new Promise((resolve, reject) => {
  80. const request = new XMLHttpRequest();
  81. request.open("GET", url, true);
  82. if (asTypedArray) {
  83. request.responseType = "arraybuffer";
  84. }
  85. request.onreadystatechange = () => {
  86. if (request.readyState !== XMLHttpRequest.DONE) {
  87. return;
  88. }
  89. if (request.status === 200 || request.status === 0) {
  90. let data;
  91. if (asTypedArray && request.response) {
  92. data = new Uint8Array(request.response);
  93. } else if (!asTypedArray && request.responseText) {
  94. data = (0, _util.stringToBytes)(request.responseText);
  95. }
  96. if (data) {
  97. resolve(data);
  98. return;
  99. }
  100. }
  101. reject(new Error(request.statusText));
  102. };
  103. request.send(null);
  104. });
  105. }
  106. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  107. _fetchData(url, compressionType) {
  108. return fetchData(url, this.isCompressed).then(data => {
  109. return {
  110. cMapData: data,
  111. compressionType
  112. };
  113. });
  114. }
  115. }
  116. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  117. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  118. _fetchData(url) {
  119. return fetchData(url, true);
  120. }
  121. }
  122. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  123. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  124. _createSVG(type) {
  125. return document.createElementNS(SVG_NS, type);
  126. }
  127. }
  128. exports.DOMSVGFactory = DOMSVGFactory;
  129. class PageViewport {
  130. constructor({
  131. viewBox,
  132. scale,
  133. rotation,
  134. offsetX = 0,
  135. offsetY = 0,
  136. dontFlip = false
  137. }) {
  138. this.viewBox = viewBox;
  139. this.scale = scale;
  140. this.rotation = rotation;
  141. this.offsetX = offsetX;
  142. this.offsetY = offsetY;
  143. const centerX = (viewBox[2] + viewBox[0]) / 2;
  144. const centerY = (viewBox[3] + viewBox[1]) / 2;
  145. let rotateA, rotateB, rotateC, rotateD;
  146. rotation %= 360;
  147. if (rotation < 0) {
  148. rotation += 360;
  149. }
  150. switch (rotation) {
  151. case 180:
  152. rotateA = -1;
  153. rotateB = 0;
  154. rotateC = 0;
  155. rotateD = 1;
  156. break;
  157. case 90:
  158. rotateA = 0;
  159. rotateB = 1;
  160. rotateC = 1;
  161. rotateD = 0;
  162. break;
  163. case 270:
  164. rotateA = 0;
  165. rotateB = -1;
  166. rotateC = -1;
  167. rotateD = 0;
  168. break;
  169. case 0:
  170. rotateA = 1;
  171. rotateB = 0;
  172. rotateC = 0;
  173. rotateD = -1;
  174. break;
  175. default:
  176. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  177. }
  178. if (dontFlip) {
  179. rotateC = -rotateC;
  180. rotateD = -rotateD;
  181. }
  182. let offsetCanvasX, offsetCanvasY;
  183. let width, height;
  184. if (rotateA === 0) {
  185. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  186. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  187. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  188. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  189. } else {
  190. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  191. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  192. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  193. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  194. }
  195. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  196. this.width = width;
  197. this.height = height;
  198. }
  199. clone({
  200. scale = this.scale,
  201. rotation = this.rotation,
  202. offsetX = this.offsetX,
  203. offsetY = this.offsetY,
  204. dontFlip = false
  205. } = {}) {
  206. return new PageViewport({
  207. viewBox: this.viewBox.slice(),
  208. scale,
  209. rotation,
  210. offsetX,
  211. offsetY,
  212. dontFlip
  213. });
  214. }
  215. convertToViewportPoint(x, y) {
  216. return _util.Util.applyTransform([x, y], this.transform);
  217. }
  218. convertToViewportRectangle(rect) {
  219. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  220. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  221. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  222. }
  223. convertToPdfPoint(x, y) {
  224. return _util.Util.applyInverseTransform([x, y], this.transform);
  225. }
  226. }
  227. exports.PageViewport = PageViewport;
  228. class RenderingCancelledException extends _util.BaseException {
  229. constructor(msg, type) {
  230. super(msg);
  231. this.type = type;
  232. }
  233. }
  234. exports.RenderingCancelledException = RenderingCancelledException;
  235. const LinkTarget = {
  236. NONE: 0,
  237. SELF: 1,
  238. BLANK: 2,
  239. PARENT: 3,
  240. TOP: 4
  241. };
  242. exports.LinkTarget = LinkTarget;
  243. function addLinkAttributes(link, {
  244. url,
  245. target,
  246. rel,
  247. enabled = true
  248. } = {}) {
  249. (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
  250. const urlNullRemoved = (0, _util.removeNullCharacters)(url);
  251. if (enabled) {
  252. link.href = link.title = urlNullRemoved;
  253. } else {
  254. link.href = "";
  255. link.title = `Disabled: ${urlNullRemoved}`;
  256. link.onclick = () => {
  257. return false;
  258. };
  259. }
  260. let targetStr = "";
  261. switch (target) {
  262. case LinkTarget.NONE:
  263. break;
  264. case LinkTarget.SELF:
  265. targetStr = "_self";
  266. break;
  267. case LinkTarget.BLANK:
  268. targetStr = "_blank";
  269. break;
  270. case LinkTarget.PARENT:
  271. targetStr = "_parent";
  272. break;
  273. case LinkTarget.TOP:
  274. targetStr = "_top";
  275. break;
  276. }
  277. link.target = targetStr;
  278. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  279. }
  280. function isDataScheme(url) {
  281. const ii = url.length;
  282. let i = 0;
  283. while (i < ii && url[i].trim() === "") {
  284. i++;
  285. }
  286. return url.substring(i, i + 5).toLowerCase() === "data:";
  287. }
  288. function isPdfFile(filename) {
  289. return typeof filename === "string" && /\.pdf$/i.test(filename);
  290. }
  291. function getFilenameFromUrl(url) {
  292. const anchor = url.indexOf("#");
  293. const query = url.indexOf("?");
  294. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  295. return url.substring(url.lastIndexOf("/", end) + 1, end);
  296. }
  297. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  298. if (typeof url !== "string") {
  299. return defaultFilename;
  300. }
  301. if (isDataScheme(url)) {
  302. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  303. return defaultFilename;
  304. }
  305. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  306. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  307. const splitURI = reURI.exec(url);
  308. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  309. if (suggestedFilename) {
  310. suggestedFilename = suggestedFilename[0];
  311. if (suggestedFilename.includes("%")) {
  312. try {
  313. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  314. } catch (ex) {}
  315. }
  316. }
  317. return suggestedFilename || defaultFilename;
  318. }
  319. class StatTimer {
  320. constructor() {
  321. this.started = Object.create(null);
  322. this.times = [];
  323. }
  324. time(name) {
  325. if (name in this.started) {
  326. (0, _util.warn)(`Timer is already running for ${name}`);
  327. }
  328. this.started[name] = Date.now();
  329. }
  330. timeEnd(name) {
  331. if (!(name in this.started)) {
  332. (0, _util.warn)(`Timer has not been started for ${name}`);
  333. }
  334. this.times.push({
  335. name,
  336. start: this.started[name],
  337. end: Date.now()
  338. });
  339. delete this.started[name];
  340. }
  341. toString() {
  342. const outBuf = [];
  343. let longest = 0;
  344. for (const time of this.times) {
  345. const name = time.name;
  346. if (name.length > longest) {
  347. longest = name.length;
  348. }
  349. }
  350. for (const time of this.times) {
  351. const duration = time.end - time.start;
  352. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  353. }
  354. return outBuf.join("");
  355. }
  356. }
  357. exports.StatTimer = StatTimer;
  358. function isValidFetchUrl(url, baseUrl) {
  359. try {
  360. const {
  361. protocol
  362. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  363. return protocol === "http:" || protocol === "https:";
  364. } catch (ex) {
  365. return false;
  366. }
  367. }
  368. function loadScript(src, removeScriptElement = false) {
  369. return new Promise((resolve, reject) => {
  370. const script = document.createElement("script");
  371. script.src = src;
  372. script.onload = function (evt) {
  373. if (removeScriptElement) {
  374. script.remove();
  375. }
  376. resolve(evt);
  377. };
  378. script.onerror = function () {
  379. reject(new Error(`Cannot load script at: ${script.src}`));
  380. };
  381. (document.head || document.documentElement).appendChild(script);
  382. });
  383. }
  384. function deprecated(details) {
  385. console.log("Deprecated API usage: " + details);
  386. }
  387. let pdfDateStringRegex;
  388. class PDFDateString {
  389. static toDateObject(input) {
  390. if (!input || !(0, _util.isString)(input)) {
  391. return null;
  392. }
  393. if (!pdfDateStringRegex) {
  394. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  395. }
  396. const matches = pdfDateStringRegex.exec(input);
  397. if (!matches) {
  398. return null;
  399. }
  400. const year = parseInt(matches[1], 10);
  401. let month = parseInt(matches[2], 10);
  402. month = month >= 1 && month <= 12 ? month - 1 : 0;
  403. let day = parseInt(matches[3], 10);
  404. day = day >= 1 && day <= 31 ? day : 1;
  405. let hour = parseInt(matches[4], 10);
  406. hour = hour >= 0 && hour <= 23 ? hour : 0;
  407. let minute = parseInt(matches[5], 10);
  408. minute = minute >= 0 && minute <= 59 ? minute : 0;
  409. let second = parseInt(matches[6], 10);
  410. second = second >= 0 && second <= 59 ? second : 0;
  411. const universalTimeRelation = matches[7] || "Z";
  412. let offsetHour = parseInt(matches[8], 10);
  413. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  414. let offsetMinute = parseInt(matches[9], 10) || 0;
  415. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  416. if (universalTimeRelation === "-") {
  417. hour += offsetHour;
  418. minute += offsetMinute;
  419. } else if (universalTimeRelation === "+") {
  420. hour -= offsetHour;
  421. minute -= offsetMinute;
  422. }
  423. return new Date(Date.UTC(year, month, day, hour, minute, second));
  424. }
  425. }
  426. exports.PDFDateString = PDFDateString;
  427. function getXfaPageViewport(xfaPage, {
  428. scale = 1,
  429. rotation = 0
  430. }) {
  431. const {
  432. width,
  433. height
  434. } = xfaPage.attributes.style;
  435. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  436. return new PageViewport({
  437. viewBox,
  438. scale,
  439. rotation
  440. });
  441. }
  442. /***/ }),
  443. /* 2 */
  444. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  445. Object.defineProperty(exports, "__esModule", ({
  446. value: true
  447. }));
  448. exports.arrayByteLength = arrayByteLength;
  449. exports.arraysToBytes = arraysToBytes;
  450. exports.assert = assert;
  451. exports.bytesToString = bytesToString;
  452. exports.createObjectURL = createObjectURL;
  453. exports.createPromiseCapability = createPromiseCapability;
  454. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  455. exports.escapeString = escapeString;
  456. exports.getModificationDate = getModificationDate;
  457. exports.getVerbosityLevel = getVerbosityLevel;
  458. exports.info = info;
  459. exports.isArrayBuffer = isArrayBuffer;
  460. exports.isArrayEqual = isArrayEqual;
  461. exports.isAscii = isAscii;
  462. exports.isBool = isBool;
  463. exports.isNum = isNum;
  464. exports.isSameOrigin = isSameOrigin;
  465. exports.isString = isString;
  466. exports.objectFromMap = objectFromMap;
  467. exports.objectSize = objectSize;
  468. exports.removeNullCharacters = removeNullCharacters;
  469. exports.setVerbosityLevel = setVerbosityLevel;
  470. exports.shadow = shadow;
  471. exports.string32 = string32;
  472. exports.stringToBytes = stringToBytes;
  473. exports.stringToPDFString = stringToPDFString;
  474. exports.stringToUTF16BEString = stringToUTF16BEString;
  475. exports.stringToUTF8String = stringToUTF8String;
  476. exports.unreachable = unreachable;
  477. exports.utf8StringToString = utf8StringToString;
  478. exports.warn = warn;
  479. exports.VerbosityLevel = exports.Util = exports.UNSUPPORTED_FEATURES = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = 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.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
  480. __w_pdfjs_require__(3);
  481. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  482. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  483. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  484. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  485. const PermissionFlag = {
  486. PRINT: 0x04,
  487. MODIFY_CONTENTS: 0x08,
  488. COPY: 0x10,
  489. MODIFY_ANNOTATIONS: 0x20,
  490. FILL_INTERACTIVE_FORMS: 0x100,
  491. COPY_FOR_ACCESSIBILITY: 0x200,
  492. ASSEMBLE: 0x400,
  493. PRINT_HIGH_QUALITY: 0x800
  494. };
  495. exports.PermissionFlag = PermissionFlag;
  496. const TextRenderingMode = {
  497. FILL: 0,
  498. STROKE: 1,
  499. FILL_STROKE: 2,
  500. INVISIBLE: 3,
  501. FILL_ADD_TO_PATH: 4,
  502. STROKE_ADD_TO_PATH: 5,
  503. FILL_STROKE_ADD_TO_PATH: 6,
  504. ADD_TO_PATH: 7,
  505. FILL_STROKE_MASK: 3,
  506. ADD_TO_PATH_FLAG: 4
  507. };
  508. exports.TextRenderingMode = TextRenderingMode;
  509. const ImageKind = {
  510. GRAYSCALE_1BPP: 1,
  511. RGB_24BPP: 2,
  512. RGBA_32BPP: 3
  513. };
  514. exports.ImageKind = ImageKind;
  515. const AnnotationType = {
  516. TEXT: 1,
  517. LINK: 2,
  518. FREETEXT: 3,
  519. LINE: 4,
  520. SQUARE: 5,
  521. CIRCLE: 6,
  522. POLYGON: 7,
  523. POLYLINE: 8,
  524. HIGHLIGHT: 9,
  525. UNDERLINE: 10,
  526. SQUIGGLY: 11,
  527. STRIKEOUT: 12,
  528. STAMP: 13,
  529. CARET: 14,
  530. INK: 15,
  531. POPUP: 16,
  532. FILEATTACHMENT: 17,
  533. SOUND: 18,
  534. MOVIE: 19,
  535. WIDGET: 20,
  536. SCREEN: 21,
  537. PRINTERMARK: 22,
  538. TRAPNET: 23,
  539. WATERMARK: 24,
  540. THREED: 25,
  541. REDACT: 26
  542. };
  543. exports.AnnotationType = AnnotationType;
  544. const AnnotationStateModelType = {
  545. MARKED: "Marked",
  546. REVIEW: "Review"
  547. };
  548. exports.AnnotationStateModelType = AnnotationStateModelType;
  549. const AnnotationMarkedState = {
  550. MARKED: "Marked",
  551. UNMARKED: "Unmarked"
  552. };
  553. exports.AnnotationMarkedState = AnnotationMarkedState;
  554. const AnnotationReviewState = {
  555. ACCEPTED: "Accepted",
  556. REJECTED: "Rejected",
  557. CANCELLED: "Cancelled",
  558. COMPLETED: "Completed",
  559. NONE: "None"
  560. };
  561. exports.AnnotationReviewState = AnnotationReviewState;
  562. const AnnotationReplyType = {
  563. GROUP: "Group",
  564. REPLY: "R"
  565. };
  566. exports.AnnotationReplyType = AnnotationReplyType;
  567. const AnnotationFlag = {
  568. INVISIBLE: 0x01,
  569. HIDDEN: 0x02,
  570. PRINT: 0x04,
  571. NOZOOM: 0x08,
  572. NOROTATE: 0x10,
  573. NOVIEW: 0x20,
  574. READONLY: 0x40,
  575. LOCKED: 0x80,
  576. TOGGLENOVIEW: 0x100,
  577. LOCKEDCONTENTS: 0x200
  578. };
  579. exports.AnnotationFlag = AnnotationFlag;
  580. const AnnotationFieldFlag = {
  581. READONLY: 0x0000001,
  582. REQUIRED: 0x0000002,
  583. NOEXPORT: 0x0000004,
  584. MULTILINE: 0x0001000,
  585. PASSWORD: 0x0002000,
  586. NOTOGGLETOOFF: 0x0004000,
  587. RADIO: 0x0008000,
  588. PUSHBUTTON: 0x0010000,
  589. COMBO: 0x0020000,
  590. EDIT: 0x0040000,
  591. SORT: 0x0080000,
  592. FILESELECT: 0x0100000,
  593. MULTISELECT: 0x0200000,
  594. DONOTSPELLCHECK: 0x0400000,
  595. DONOTSCROLL: 0x0800000,
  596. COMB: 0x1000000,
  597. RICHTEXT: 0x2000000,
  598. RADIOSINUNISON: 0x2000000,
  599. COMMITONSELCHANGE: 0x4000000
  600. };
  601. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  602. const AnnotationBorderStyleType = {
  603. SOLID: 1,
  604. DASHED: 2,
  605. BEVELED: 3,
  606. INSET: 4,
  607. UNDERLINE: 5
  608. };
  609. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  610. const AnnotationActionEventType = {
  611. E: "Mouse Enter",
  612. X: "Mouse Exit",
  613. D: "Mouse Down",
  614. U: "Mouse Up",
  615. Fo: "Focus",
  616. Bl: "Blur",
  617. PO: "PageOpen",
  618. PC: "PageClose",
  619. PV: "PageVisible",
  620. PI: "PageInvisible",
  621. K: "Keystroke",
  622. F: "Format",
  623. V: "Validate",
  624. C: "Calculate"
  625. };
  626. exports.AnnotationActionEventType = AnnotationActionEventType;
  627. const DocumentActionEventType = {
  628. WC: "WillClose",
  629. WS: "WillSave",
  630. DS: "DidSave",
  631. WP: "WillPrint",
  632. DP: "DidPrint"
  633. };
  634. exports.DocumentActionEventType = DocumentActionEventType;
  635. const PageActionEventType = {
  636. O: "PageOpen",
  637. C: "PageClose"
  638. };
  639. exports.PageActionEventType = PageActionEventType;
  640. const StreamType = {
  641. UNKNOWN: "UNKNOWN",
  642. FLATE: "FLATE",
  643. LZW: "LZW",
  644. DCT: "DCT",
  645. JPX: "JPX",
  646. JBIG: "JBIG",
  647. A85: "A85",
  648. AHX: "AHX",
  649. CCF: "CCF",
  650. RLX: "RLX"
  651. };
  652. exports.StreamType = StreamType;
  653. const FontType = {
  654. UNKNOWN: "UNKNOWN",
  655. TYPE1: "TYPE1",
  656. TYPE1STANDARD: "TYPE1STANDARD",
  657. TYPE1C: "TYPE1C",
  658. CIDFONTTYPE0: "CIDFONTTYPE0",
  659. CIDFONTTYPE0C: "CIDFONTTYPE0C",
  660. TRUETYPE: "TRUETYPE",
  661. CIDFONTTYPE2: "CIDFONTTYPE2",
  662. TYPE3: "TYPE3",
  663. OPENTYPE: "OPENTYPE",
  664. TYPE0: "TYPE0",
  665. MMTYPE1: "MMTYPE1"
  666. };
  667. exports.FontType = FontType;
  668. const VerbosityLevel = {
  669. ERRORS: 0,
  670. WARNINGS: 1,
  671. INFOS: 5
  672. };
  673. exports.VerbosityLevel = VerbosityLevel;
  674. const CMapCompressionType = {
  675. NONE: 0,
  676. BINARY: 1,
  677. STREAM: 2
  678. };
  679. exports.CMapCompressionType = CMapCompressionType;
  680. const OPS = {
  681. dependency: 1,
  682. setLineWidth: 2,
  683. setLineCap: 3,
  684. setLineJoin: 4,
  685. setMiterLimit: 5,
  686. setDash: 6,
  687. setRenderingIntent: 7,
  688. setFlatness: 8,
  689. setGState: 9,
  690. save: 10,
  691. restore: 11,
  692. transform: 12,
  693. moveTo: 13,
  694. lineTo: 14,
  695. curveTo: 15,
  696. curveTo2: 16,
  697. curveTo3: 17,
  698. closePath: 18,
  699. rectangle: 19,
  700. stroke: 20,
  701. closeStroke: 21,
  702. fill: 22,
  703. eoFill: 23,
  704. fillStroke: 24,
  705. eoFillStroke: 25,
  706. closeFillStroke: 26,
  707. closeEOFillStroke: 27,
  708. endPath: 28,
  709. clip: 29,
  710. eoClip: 30,
  711. beginText: 31,
  712. endText: 32,
  713. setCharSpacing: 33,
  714. setWordSpacing: 34,
  715. setHScale: 35,
  716. setLeading: 36,
  717. setFont: 37,
  718. setTextRenderingMode: 38,
  719. setTextRise: 39,
  720. moveText: 40,
  721. setLeadingMoveText: 41,
  722. setTextMatrix: 42,
  723. nextLine: 43,
  724. showText: 44,
  725. showSpacedText: 45,
  726. nextLineShowText: 46,
  727. nextLineSetSpacingShowText: 47,
  728. setCharWidth: 48,
  729. setCharWidthAndBounds: 49,
  730. setStrokeColorSpace: 50,
  731. setFillColorSpace: 51,
  732. setStrokeColor: 52,
  733. setStrokeColorN: 53,
  734. setFillColor: 54,
  735. setFillColorN: 55,
  736. setStrokeGray: 56,
  737. setFillGray: 57,
  738. setStrokeRGBColor: 58,
  739. setFillRGBColor: 59,
  740. setStrokeCMYKColor: 60,
  741. setFillCMYKColor: 61,
  742. shadingFill: 62,
  743. beginInlineImage: 63,
  744. beginImageData: 64,
  745. endInlineImage: 65,
  746. paintXObject: 66,
  747. markPoint: 67,
  748. markPointProps: 68,
  749. beginMarkedContent: 69,
  750. beginMarkedContentProps: 70,
  751. endMarkedContent: 71,
  752. beginCompat: 72,
  753. endCompat: 73,
  754. paintFormXObjectBegin: 74,
  755. paintFormXObjectEnd: 75,
  756. beginGroup: 76,
  757. endGroup: 77,
  758. beginAnnotations: 78,
  759. endAnnotations: 79,
  760. beginAnnotation: 80,
  761. endAnnotation: 81,
  762. paintJpegXObject: 82,
  763. paintImageMaskXObject: 83,
  764. paintImageMaskXObjectGroup: 84,
  765. paintImageXObject: 85,
  766. paintInlineImageXObject: 86,
  767. paintInlineImageXObjectGroup: 87,
  768. paintImageXObjectRepeat: 88,
  769. paintImageMaskXObjectRepeat: 89,
  770. paintSolidColorImageMask: 90,
  771. constructPath: 91
  772. };
  773. exports.OPS = OPS;
  774. const UNSUPPORTED_FEATURES = {
  775. unknown: "unknown",
  776. forms: "forms",
  777. javaScript: "javaScript",
  778. signatures: "signatures",
  779. smask: "smask",
  780. shadingPattern: "shadingPattern",
  781. font: "font",
  782. errorTilingPattern: "errorTilingPattern",
  783. errorExtGState: "errorExtGState",
  784. errorXObject: "errorXObject",
  785. errorFontLoadType3: "errorFontLoadType3",
  786. errorFontState: "errorFontState",
  787. errorFontMissing: "errorFontMissing",
  788. errorFontTranslate: "errorFontTranslate",
  789. errorColorSpace: "errorColorSpace",
  790. errorOperatorList: "errorOperatorList",
  791. errorFontToUnicode: "errorFontToUnicode",
  792. errorFontLoadNative: "errorFontLoadNative",
  793. errorFontBuildPath: "errorFontBuildPath",
  794. errorFontGetPath: "errorFontGetPath",
  795. errorMarkedContent: "errorMarkedContent"
  796. };
  797. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  798. const PasswordResponses = {
  799. NEED_PASSWORD: 1,
  800. INCORRECT_PASSWORD: 2
  801. };
  802. exports.PasswordResponses = PasswordResponses;
  803. let verbosity = VerbosityLevel.WARNINGS;
  804. function setVerbosityLevel(level) {
  805. if (Number.isInteger(level)) {
  806. verbosity = level;
  807. }
  808. }
  809. function getVerbosityLevel() {
  810. return verbosity;
  811. }
  812. function info(msg) {
  813. if (verbosity >= VerbosityLevel.INFOS) {
  814. console.log(`Info: ${msg}`);
  815. }
  816. }
  817. function warn(msg) {
  818. if (verbosity >= VerbosityLevel.WARNINGS) {
  819. console.log(`Warning: ${msg}`);
  820. }
  821. }
  822. function unreachable(msg) {
  823. throw new Error(msg);
  824. }
  825. function assert(cond, msg) {
  826. if (!cond) {
  827. unreachable(msg);
  828. }
  829. }
  830. function isSameOrigin(baseUrl, otherUrl) {
  831. let base;
  832. try {
  833. base = new URL(baseUrl);
  834. if (!base.origin || base.origin === "null") {
  835. return false;
  836. }
  837. } catch (e) {
  838. return false;
  839. }
  840. const other = new URL(otherUrl, base);
  841. return base.origin === other.origin;
  842. }
  843. function _isValidProtocol(url) {
  844. if (!url) {
  845. return false;
  846. }
  847. switch (url.protocol) {
  848. case "http:":
  849. case "https:":
  850. case "ftp:":
  851. case "mailto:":
  852. case "tel:":
  853. return true;
  854. default:
  855. return false;
  856. }
  857. }
  858. function createValidAbsoluteUrl(url, baseUrl) {
  859. if (!url) {
  860. return null;
  861. }
  862. try {
  863. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  864. if (_isValidProtocol(absoluteUrl)) {
  865. return absoluteUrl;
  866. }
  867. } catch (ex) {}
  868. return null;
  869. }
  870. function shadow(obj, prop, value) {
  871. Object.defineProperty(obj, prop, {
  872. value,
  873. enumerable: true,
  874. configurable: true,
  875. writable: false
  876. });
  877. return value;
  878. }
  879. const BaseException = function BaseExceptionClosure() {
  880. function BaseException(message) {
  881. if (this.constructor === BaseException) {
  882. unreachable("Cannot initialize BaseException.");
  883. }
  884. this.message = message;
  885. this.name = this.constructor.name;
  886. }
  887. BaseException.prototype = new Error();
  888. BaseException.constructor = BaseException;
  889. return BaseException;
  890. }();
  891. exports.BaseException = BaseException;
  892. class PasswordException extends BaseException {
  893. constructor(msg, code) {
  894. super(msg);
  895. this.code = code;
  896. }
  897. }
  898. exports.PasswordException = PasswordException;
  899. class UnknownErrorException extends BaseException {
  900. constructor(msg, details) {
  901. super(msg);
  902. this.details = details;
  903. }
  904. }
  905. exports.UnknownErrorException = UnknownErrorException;
  906. class InvalidPDFException extends BaseException {}
  907. exports.InvalidPDFException = InvalidPDFException;
  908. class MissingPDFException extends BaseException {}
  909. exports.MissingPDFException = MissingPDFException;
  910. class UnexpectedResponseException extends BaseException {
  911. constructor(msg, status) {
  912. super(msg);
  913. this.status = status;
  914. }
  915. }
  916. exports.UnexpectedResponseException = UnexpectedResponseException;
  917. class FormatError extends BaseException {}
  918. exports.FormatError = FormatError;
  919. class AbortException extends BaseException {}
  920. exports.AbortException = AbortException;
  921. const NullCharactersRegExp = /\x00/g;
  922. function removeNullCharacters(str) {
  923. if (typeof str !== "string") {
  924. warn("The argument for removeNullCharacters must be a string.");
  925. return str;
  926. }
  927. return str.replace(NullCharactersRegExp, "");
  928. }
  929. function bytesToString(bytes) {
  930. assert(bytes !== null && typeof bytes === "object" && bytes.length !== undefined, "Invalid argument for bytesToString");
  931. const length = bytes.length;
  932. const MAX_ARGUMENT_COUNT = 8192;
  933. if (length < MAX_ARGUMENT_COUNT) {
  934. return String.fromCharCode.apply(null, bytes);
  935. }
  936. const strBuf = [];
  937. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  938. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  939. const chunk = bytes.subarray(i, chunkEnd);
  940. strBuf.push(String.fromCharCode.apply(null, chunk));
  941. }
  942. return strBuf.join("");
  943. }
  944. function stringToBytes(str) {
  945. assert(typeof str === "string", "Invalid argument for stringToBytes");
  946. const length = str.length;
  947. const bytes = new Uint8Array(length);
  948. for (let i = 0; i < length; ++i) {
  949. bytes[i] = str.charCodeAt(i) & 0xff;
  950. }
  951. return bytes;
  952. }
  953. function arrayByteLength(arr) {
  954. if (arr.length !== undefined) {
  955. return arr.length;
  956. }
  957. assert(arr.byteLength !== undefined, "arrayByteLength - invalid argument.");
  958. return arr.byteLength;
  959. }
  960. function arraysToBytes(arr) {
  961. const length = arr.length;
  962. if (length === 1 && arr[0] instanceof Uint8Array) {
  963. return arr[0];
  964. }
  965. let resultLength = 0;
  966. for (let i = 0; i < length; i++) {
  967. resultLength += arrayByteLength(arr[i]);
  968. }
  969. let pos = 0;
  970. const data = new Uint8Array(resultLength);
  971. for (let i = 0; i < length; i++) {
  972. let item = arr[i];
  973. if (!(item instanceof Uint8Array)) {
  974. if (typeof item === "string") {
  975. item = stringToBytes(item);
  976. } else {
  977. item = new Uint8Array(item);
  978. }
  979. }
  980. const itemLength = item.byteLength;
  981. data.set(item, pos);
  982. pos += itemLength;
  983. }
  984. return data;
  985. }
  986. function string32(value) {
  987. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  988. }
  989. function objectSize(obj) {
  990. return Object.keys(obj).length;
  991. }
  992. function objectFromMap(map) {
  993. const obj = Object.create(null);
  994. for (const [key, value] of map) {
  995. obj[key] = value;
  996. }
  997. return obj;
  998. }
  999. function isLittleEndian() {
  1000. const buffer8 = new Uint8Array(4);
  1001. buffer8[0] = 1;
  1002. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  1003. return view32[0] === 1;
  1004. }
  1005. const IsLittleEndianCached = {
  1006. get value() {
  1007. return shadow(this, "value", isLittleEndian());
  1008. }
  1009. };
  1010. exports.IsLittleEndianCached = IsLittleEndianCached;
  1011. function isEvalSupported() {
  1012. try {
  1013. new Function("");
  1014. return true;
  1015. } catch (e) {
  1016. return false;
  1017. }
  1018. }
  1019. const IsEvalSupportedCached = {
  1020. get value() {
  1021. return shadow(this, "value", isEvalSupported());
  1022. }
  1023. };
  1024. exports.IsEvalSupportedCached = IsEvalSupportedCached;
  1025. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  1026. class Util {
  1027. static makeHexColor(r, g, b) {
  1028. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  1029. }
  1030. static transform(m1, m2) {
  1031. 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]];
  1032. }
  1033. static applyTransform(p, m) {
  1034. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  1035. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  1036. return [xt, yt];
  1037. }
  1038. static applyInverseTransform(p, m) {
  1039. const d = m[0] * m[3] - m[1] * m[2];
  1040. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  1041. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  1042. return [xt, yt];
  1043. }
  1044. static getAxialAlignedBoundingBox(r, m) {
  1045. const p1 = Util.applyTransform(r, m);
  1046. const p2 = Util.applyTransform(r.slice(2, 4), m);
  1047. const p3 = Util.applyTransform([r[0], r[3]], m);
  1048. const p4 = Util.applyTransform([r[2], r[1]], m);
  1049. 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])];
  1050. }
  1051. static inverseTransform(m) {
  1052. const d = m[0] * m[3] - m[1] * m[2];
  1053. 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];
  1054. }
  1055. static apply3dTransform(m, v) {
  1056. 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]];
  1057. }
  1058. static singularValueDecompose2dScale(m) {
  1059. const transpose = [m[0], m[2], m[1], m[3]];
  1060. const a = m[0] * transpose[0] + m[1] * transpose[2];
  1061. const b = m[0] * transpose[1] + m[1] * transpose[3];
  1062. const c = m[2] * transpose[0] + m[3] * transpose[2];
  1063. const d = m[2] * transpose[1] + m[3] * transpose[3];
  1064. const first = (a + d) / 2;
  1065. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  1066. const sx = first + second || 1;
  1067. const sy = first - second || 1;
  1068. return [Math.sqrt(sx), Math.sqrt(sy)];
  1069. }
  1070. static normalizeRect(rect) {
  1071. const r = rect.slice(0);
  1072. if (rect[0] > rect[2]) {
  1073. r[0] = rect[2];
  1074. r[2] = rect[0];
  1075. }
  1076. if (rect[1] > rect[3]) {
  1077. r[1] = rect[3];
  1078. r[3] = rect[1];
  1079. }
  1080. return r;
  1081. }
  1082. static intersect(rect1, rect2) {
  1083. function compare(a, b) {
  1084. return a - b;
  1085. }
  1086. const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
  1087. const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare);
  1088. const result = [];
  1089. rect1 = Util.normalizeRect(rect1);
  1090. rect2 = Util.normalizeRect(rect2);
  1091. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  1092. result[0] = orderedX[1];
  1093. result[2] = orderedX[2];
  1094. } else {
  1095. return null;
  1096. }
  1097. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  1098. result[1] = orderedY[1];
  1099. result[3] = orderedY[2];
  1100. } else {
  1101. return null;
  1102. }
  1103. return result;
  1104. }
  1105. }
  1106. exports.Util = Util;
  1107. 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];
  1108. function stringToPDFString(str) {
  1109. const length = str.length,
  1110. strBuf = [];
  1111. if (str[0] === "\xFE" && str[1] === "\xFF") {
  1112. for (let i = 2; i < length; i += 2) {
  1113. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1114. }
  1115. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  1116. for (let i = 2; i < length; i += 2) {
  1117. strBuf.push(String.fromCharCode(str.charCodeAt(i + 1) << 8 | str.charCodeAt(i)));
  1118. }
  1119. } else {
  1120. for (let i = 0; i < length; ++i) {
  1121. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  1122. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1123. }
  1124. }
  1125. return strBuf.join("");
  1126. }
  1127. function escapeString(str) {
  1128. return str.replace(/([()\\\n\r])/g, match => {
  1129. if (match === "\n") {
  1130. return "\\n";
  1131. } else if (match === "\r") {
  1132. return "\\r";
  1133. }
  1134. return `\\${match}`;
  1135. });
  1136. }
  1137. function isAscii(str) {
  1138. return /^[\x00-\x7F]*$/.test(str);
  1139. }
  1140. function stringToUTF16BEString(str) {
  1141. const buf = ["\xFE\xFF"];
  1142. for (let i = 0, ii = str.length; i < ii; i++) {
  1143. const char = str.charCodeAt(i);
  1144. buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
  1145. }
  1146. return buf.join("");
  1147. }
  1148. function stringToUTF8String(str) {
  1149. return decodeURIComponent(escape(str));
  1150. }
  1151. function utf8StringToString(str) {
  1152. return unescape(encodeURIComponent(str));
  1153. }
  1154. function isBool(v) {
  1155. return typeof v === "boolean";
  1156. }
  1157. function isNum(v) {
  1158. return typeof v === "number";
  1159. }
  1160. function isString(v) {
  1161. return typeof v === "string";
  1162. }
  1163. function isArrayBuffer(v) {
  1164. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  1165. }
  1166. function isArrayEqual(arr1, arr2) {
  1167. if (arr1.length !== arr2.length) {
  1168. return false;
  1169. }
  1170. for (let i = 0, ii = arr1.length; i < ii; i++) {
  1171. if (arr1[i] !== arr2[i]) {
  1172. return false;
  1173. }
  1174. }
  1175. return true;
  1176. }
  1177. function getModificationDate(date = new Date()) {
  1178. 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")];
  1179. return buffer.join("");
  1180. }
  1181. function createPromiseCapability() {
  1182. const capability = Object.create(null);
  1183. let isSettled = false;
  1184. Object.defineProperty(capability, "settled", {
  1185. get() {
  1186. return isSettled;
  1187. }
  1188. });
  1189. capability.promise = new Promise(function (resolve, reject) {
  1190. capability.resolve = function (data) {
  1191. isSettled = true;
  1192. resolve(data);
  1193. };
  1194. capability.reject = function (reason) {
  1195. isSettled = true;
  1196. reject(reason);
  1197. };
  1198. });
  1199. return capability;
  1200. }
  1201. function createObjectURL(data, contentType = "", forceDataSchema = false) {
  1202. if (URL.createObjectURL && !forceDataSchema) {
  1203. return URL.createObjectURL(new Blob([data], {
  1204. type: contentType
  1205. }));
  1206. }
  1207. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1208. let buffer = `data:${contentType};base64,`;
  1209. for (let i = 0, ii = data.length; i < ii; i += 3) {
  1210. const b1 = data[i] & 0xff;
  1211. const b2 = data[i + 1] & 0xff;
  1212. const b3 = data[i + 2] & 0xff;
  1213. const d1 = b1 >> 2,
  1214. d2 = (b1 & 3) << 4 | b2 >> 4;
  1215. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  1216. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  1217. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1218. }
  1219. return buffer;
  1220. }
  1221. /***/ }),
  1222. /* 3 */
  1223. /***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
  1224. var _is_node = __w_pdfjs_require__(4);
  1225. ;
  1226. /***/ }),
  1227. /* 4 */
  1228. /***/ ((__unused_webpack_module, exports) => {
  1229. Object.defineProperty(exports, "__esModule", ({
  1230. value: true
  1231. }));
  1232. exports.isNodeJS = void 0;
  1233. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  1234. exports.isNodeJS = isNodeJS;
  1235. /***/ }),
  1236. /* 5 */
  1237. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1238. Object.defineProperty(exports, "__esModule", ({
  1239. value: true
  1240. }));
  1241. exports.BaseSVGFactory = exports.BaseStandardFontDataFactory = exports.BaseCMapReaderFactory = exports.BaseCanvasFactory = void 0;
  1242. var _util = __w_pdfjs_require__(2);
  1243. class BaseCanvasFactory {
  1244. constructor() {
  1245. if (this.constructor === BaseCanvasFactory) {
  1246. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  1247. }
  1248. }
  1249. create(width, height) {
  1250. if (width <= 0 || height <= 0) {
  1251. throw new Error("Invalid canvas size");
  1252. }
  1253. const canvas = this._createCanvas(width, height);
  1254. return {
  1255. canvas,
  1256. context: canvas.getContext("2d")
  1257. };
  1258. }
  1259. reset(canvasAndContext, width, height) {
  1260. if (!canvasAndContext.canvas) {
  1261. throw new Error("Canvas is not specified");
  1262. }
  1263. if (width <= 0 || height <= 0) {
  1264. throw new Error("Invalid canvas size");
  1265. }
  1266. canvasAndContext.canvas.width = width;
  1267. canvasAndContext.canvas.height = height;
  1268. }
  1269. destroy(canvasAndContext) {
  1270. if (!canvasAndContext.canvas) {
  1271. throw new Error("Canvas is not specified");
  1272. }
  1273. canvasAndContext.canvas.width = 0;
  1274. canvasAndContext.canvas.height = 0;
  1275. canvasAndContext.canvas = null;
  1276. canvasAndContext.context = null;
  1277. }
  1278. _createCanvas(width, height) {
  1279. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  1280. }
  1281. }
  1282. exports.BaseCanvasFactory = BaseCanvasFactory;
  1283. class BaseCMapReaderFactory {
  1284. constructor({
  1285. baseUrl = null,
  1286. isCompressed = false
  1287. }) {
  1288. if (this.constructor === BaseCMapReaderFactory) {
  1289. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  1290. }
  1291. this.baseUrl = baseUrl;
  1292. this.isCompressed = isCompressed;
  1293. }
  1294. async fetch({
  1295. name
  1296. }) {
  1297. if (!this.baseUrl) {
  1298. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  1299. }
  1300. if (!name) {
  1301. throw new Error("CMap name must be specified.");
  1302. }
  1303. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  1304. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  1305. return this._fetchData(url, compressionType).catch(reason => {
  1306. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  1307. });
  1308. }
  1309. _fetchData(url, compressionType) {
  1310. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  1311. }
  1312. }
  1313. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  1314. class BaseStandardFontDataFactory {
  1315. constructor({
  1316. baseUrl = null
  1317. }) {
  1318. if (this.constructor === BaseStandardFontDataFactory) {
  1319. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  1320. }
  1321. this.baseUrl = baseUrl;
  1322. }
  1323. async fetch({
  1324. filename
  1325. }) {
  1326. if (!this.baseUrl) {
  1327. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  1328. }
  1329. if (!filename) {
  1330. throw new Error("Font filename must be specified.");
  1331. }
  1332. const url = `${this.baseUrl}${filename}`;
  1333. return this._fetchData(url).catch(reason => {
  1334. throw new Error(`Unable to load font data at: ${url}`);
  1335. });
  1336. }
  1337. _fetchData(url) {
  1338. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  1339. }
  1340. }
  1341. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  1342. class BaseSVGFactory {
  1343. constructor() {
  1344. if (this.constructor === BaseSVGFactory) {
  1345. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  1346. }
  1347. }
  1348. create(width, height) {
  1349. if (width <= 0 || height <= 0) {
  1350. throw new Error("Invalid SVG dimensions");
  1351. }
  1352. const svg = this._createSVG("svg:svg");
  1353. svg.setAttribute("version", "1.1");
  1354. svg.setAttribute("width", `${width}px`);
  1355. svg.setAttribute("height", `${height}px`);
  1356. svg.setAttribute("preserveAspectRatio", "none");
  1357. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  1358. return svg;
  1359. }
  1360. createElement(type) {
  1361. if (typeof type !== "string") {
  1362. throw new Error("Invalid SVG element type");
  1363. }
  1364. return this._createSVG(type);
  1365. }
  1366. _createSVG(type) {
  1367. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  1368. }
  1369. }
  1370. exports.BaseSVGFactory = BaseSVGFactory;
  1371. /***/ }),
  1372. /* 6 */
  1373. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1374. Object.defineProperty(exports, "__esModule", ({
  1375. value: true
  1376. }));
  1377. exports.getDocument = getDocument;
  1378. exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
  1379. exports.version = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCMapReaderFactory = exports.DefaultCanvasFactory = exports.build = void 0;
  1380. var _util = __w_pdfjs_require__(2);
  1381. var _display_utils = __w_pdfjs_require__(1);
  1382. var _font_loader = __w_pdfjs_require__(7);
  1383. var _node_utils = __w_pdfjs_require__(8);
  1384. var _annotation_storage = __w_pdfjs_require__(9);
  1385. var _canvas = __w_pdfjs_require__(10);
  1386. var _worker_options = __w_pdfjs_require__(12);
  1387. var _is_node = __w_pdfjs_require__(4);
  1388. var _message_handler = __w_pdfjs_require__(13);
  1389. var _metadata = __w_pdfjs_require__(14);
  1390. var _optional_content_config = __w_pdfjs_require__(15);
  1391. var _transport_stream = __w_pdfjs_require__(16);
  1392. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  1393. const RENDERING_CANCELLED_TIMEOUT = 100;
  1394. const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
  1395. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  1396. const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
  1397. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  1398. const DefaultStandardFontDataFactory = _is_node.isNodeJS ? _node_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory;
  1399. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  1400. let createPDFNetworkStream;
  1401. function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
  1402. createPDFNetworkStream = pdfNetworkStreamFactory;
  1403. }
  1404. function getDocument(src) {
  1405. const task = new PDFDocumentLoadingTask();
  1406. let source;
  1407. if (typeof src === "string" || src instanceof URL) {
  1408. source = {
  1409. url: src
  1410. };
  1411. } else if ((0, _util.isArrayBuffer)(src)) {
  1412. source = {
  1413. data: src
  1414. };
  1415. } else if (src instanceof PDFDataRangeTransport) {
  1416. source = {
  1417. range: src
  1418. };
  1419. } else {
  1420. if (typeof src !== "object") {
  1421. throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
  1422. }
  1423. if (!src.url && !src.data && !src.range) {
  1424. throw new Error("Invalid parameter object: need either .data, .range or .url");
  1425. }
  1426. source = src;
  1427. }
  1428. const params = Object.create(null);
  1429. let rangeTransport = null,
  1430. worker = null;
  1431. for (const key in source) {
  1432. const value = source[key];
  1433. switch (key) {
  1434. case "url":
  1435. if (typeof window !== "undefined") {
  1436. try {
  1437. params[key] = new URL(value, window.location).href;
  1438. continue;
  1439. } catch (ex) {
  1440. (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
  1441. }
  1442. } else if (typeof value === "string" || value instanceof URL) {
  1443. params[key] = value.toString();
  1444. continue;
  1445. }
  1446. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1447. case "range":
  1448. rangeTransport = value;
  1449. continue;
  1450. case "worker":
  1451. worker = value;
  1452. continue;
  1453. case "data":
  1454. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
  1455. params[key] = new Uint8Array(value);
  1456. } else if (value instanceof Uint8Array) {
  1457. break;
  1458. } else if (typeof value === "string") {
  1459. params[key] = (0, _util.stringToBytes)(value);
  1460. } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
  1461. params[key] = new Uint8Array(value);
  1462. } else if ((0, _util.isArrayBuffer)(value)) {
  1463. params[key] = new Uint8Array(value);
  1464. } else {
  1465. throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
  1466. }
  1467. continue;
  1468. }
  1469. params[key] = value;
  1470. }
  1471. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  1472. params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
  1473. params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
  1474. params.ignoreErrors = params.stopAtErrors !== true;
  1475. params.fontExtraProperties = params.fontExtraProperties === true;
  1476. params.pdfBug = params.pdfBug === true;
  1477. params.enableXfa = params.enableXfa === true;
  1478. if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
  1479. params.docBaseUrl = null;
  1480. }
  1481. if (!Number.isInteger(params.maxImageSize)) {
  1482. params.maxImageSize = -1;
  1483. }
  1484. if (typeof params.useWorkerFetch !== "boolean") {
  1485. params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
  1486. }
  1487. if (typeof params.isEvalSupported !== "boolean") {
  1488. params.isEvalSupported = true;
  1489. }
  1490. if (typeof params.disableFontFace !== "boolean") {
  1491. params.disableFontFace = _is_node.isNodeJS;
  1492. }
  1493. if (typeof params.useSystemFonts !== "boolean") {
  1494. params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
  1495. }
  1496. if (typeof params.ownerDocument === "undefined") {
  1497. params.ownerDocument = globalThis.document;
  1498. }
  1499. if (typeof params.disableRange !== "boolean") {
  1500. params.disableRange = false;
  1501. }
  1502. if (typeof params.disableStream !== "boolean") {
  1503. params.disableStream = false;
  1504. }
  1505. if (typeof params.disableAutoFetch !== "boolean") {
  1506. params.disableAutoFetch = false;
  1507. }
  1508. (0, _util.setVerbosityLevel)(params.verbosity);
  1509. if (!worker) {
  1510. const workerParams = {
  1511. verbosity: params.verbosity,
  1512. port: _worker_options.GlobalWorkerOptions.workerPort
  1513. };
  1514. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  1515. task._worker = worker;
  1516. }
  1517. const docId = task.docId;
  1518. worker.promise.then(function () {
  1519. if (task.destroyed) {
  1520. throw new Error("Loading aborted");
  1521. }
  1522. const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
  1523. const networkStreamPromise = new Promise(function (resolve) {
  1524. let networkStream;
  1525. if (rangeTransport) {
  1526. networkStream = new _transport_stream.PDFDataTransportStream({
  1527. length: params.length,
  1528. initialData: params.initialData,
  1529. progressiveDone: params.progressiveDone,
  1530. contentDispositionFilename: params.contentDispositionFilename,
  1531. disableRange: params.disableRange,
  1532. disableStream: params.disableStream
  1533. }, rangeTransport);
  1534. } else if (!params.data) {
  1535. networkStream = createPDFNetworkStream({
  1536. url: params.url,
  1537. length: params.length,
  1538. httpHeaders: params.httpHeaders,
  1539. withCredentials: params.withCredentials,
  1540. rangeChunkSize: params.rangeChunkSize,
  1541. disableRange: params.disableRange,
  1542. disableStream: params.disableStream
  1543. });
  1544. }
  1545. resolve(networkStream);
  1546. });
  1547. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1548. if (task.destroyed) {
  1549. throw new Error("Loading aborted");
  1550. }
  1551. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1552. messageHandler.postMessageTransfers = worker.postMessageTransfers;
  1553. const transport = new WorkerTransport(messageHandler, task, networkStream, params);
  1554. task._transport = transport;
  1555. messageHandler.send("Ready", null);
  1556. });
  1557. }).catch(task._capability.reject);
  1558. return task;
  1559. }
  1560. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  1561. if (worker.destroyed) {
  1562. return Promise.reject(new Error("Worker was destroyed"));
  1563. }
  1564. if (pdfDataRangeTransport) {
  1565. source.length = pdfDataRangeTransport.length;
  1566. source.initialData = pdfDataRangeTransport.initialData;
  1567. source.progressiveDone = pdfDataRangeTransport.progressiveDone;
  1568. source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
  1569. }
  1570. return worker.messageHandler.sendWithPromise("GetDocRequest", {
  1571. docId,
  1572. apiVersion: '2.10.377',
  1573. source: {
  1574. data: source.data,
  1575. url: source.url,
  1576. password: source.password,
  1577. disableAutoFetch: source.disableAutoFetch,
  1578. rangeChunkSize: source.rangeChunkSize,
  1579. length: source.length
  1580. },
  1581. maxImageSize: source.maxImageSize,
  1582. disableFontFace: source.disableFontFace,
  1583. postMessageTransfers: worker.postMessageTransfers,
  1584. docBaseUrl: source.docBaseUrl,
  1585. ignoreErrors: source.ignoreErrors,
  1586. isEvalSupported: source.isEvalSupported,
  1587. fontExtraProperties: source.fontExtraProperties,
  1588. enableXfa: source.enableXfa,
  1589. useSystemFonts: source.useSystemFonts,
  1590. cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
  1591. standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
  1592. }).then(function (workerId) {
  1593. if (worker.destroyed) {
  1594. throw new Error("Worker was destroyed");
  1595. }
  1596. return workerId;
  1597. });
  1598. }
  1599. const PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  1600. let nextDocumentId = 0;
  1601. class PDFDocumentLoadingTask {
  1602. constructor() {
  1603. this._capability = (0, _util.createPromiseCapability)();
  1604. this._transport = null;
  1605. this._worker = null;
  1606. this.docId = "d" + nextDocumentId++;
  1607. this.destroyed = false;
  1608. this.onPassword = null;
  1609. this.onProgress = null;
  1610. this.onUnsupportedFeature = null;
  1611. }
  1612. get promise() {
  1613. return this._capability.promise;
  1614. }
  1615. destroy() {
  1616. this.destroyed = true;
  1617. const transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  1618. return transportDestroyed.then(() => {
  1619. this._transport = null;
  1620. if (this._worker) {
  1621. this._worker.destroy();
  1622. this._worker = null;
  1623. }
  1624. });
  1625. }
  1626. }
  1627. return PDFDocumentLoadingTask;
  1628. }();
  1629. class PDFDataRangeTransport {
  1630. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1631. this.length = length;
  1632. this.initialData = initialData;
  1633. this.progressiveDone = progressiveDone;
  1634. this.contentDispositionFilename = contentDispositionFilename;
  1635. this._rangeListeners = [];
  1636. this._progressListeners = [];
  1637. this._progressiveReadListeners = [];
  1638. this._progressiveDoneListeners = [];
  1639. this._readyCapability = (0, _util.createPromiseCapability)();
  1640. }
  1641. addRangeListener(listener) {
  1642. this._rangeListeners.push(listener);
  1643. }
  1644. addProgressListener(listener) {
  1645. this._progressListeners.push(listener);
  1646. }
  1647. addProgressiveReadListener(listener) {
  1648. this._progressiveReadListeners.push(listener);
  1649. }
  1650. addProgressiveDoneListener(listener) {
  1651. this._progressiveDoneListeners.push(listener);
  1652. }
  1653. onDataRange(begin, chunk) {
  1654. for (const listener of this._rangeListeners) {
  1655. listener(begin, chunk);
  1656. }
  1657. }
  1658. onDataProgress(loaded, total) {
  1659. this._readyCapability.promise.then(() => {
  1660. for (const listener of this._progressListeners) {
  1661. listener(loaded, total);
  1662. }
  1663. });
  1664. }
  1665. onDataProgressiveRead(chunk) {
  1666. this._readyCapability.promise.then(() => {
  1667. for (const listener of this._progressiveReadListeners) {
  1668. listener(chunk);
  1669. }
  1670. });
  1671. }
  1672. onDataProgressiveDone() {
  1673. this._readyCapability.promise.then(() => {
  1674. for (const listener of this._progressiveDoneListeners) {
  1675. listener();
  1676. }
  1677. });
  1678. }
  1679. transportReady() {
  1680. this._readyCapability.resolve();
  1681. }
  1682. requestDataRange(begin, end) {
  1683. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1684. }
  1685. abort() {}
  1686. }
  1687. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1688. class PDFDocumentProxy {
  1689. constructor(pdfInfo, transport) {
  1690. this._pdfInfo = pdfInfo;
  1691. this._transport = transport;
  1692. Object.defineProperty(this, "fingerprint", {
  1693. get() {
  1694. (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
  1695. return this.fingerprints[0];
  1696. }
  1697. });
  1698. }
  1699. get annotationStorage() {
  1700. return this._transport.annotationStorage;
  1701. }
  1702. get numPages() {
  1703. return this._pdfInfo.numPages;
  1704. }
  1705. get fingerprints() {
  1706. return this._pdfInfo.fingerprints;
  1707. }
  1708. get isPureXfa() {
  1709. return !!this._transport._htmlForXfa;
  1710. }
  1711. get allXfaHtml() {
  1712. return this._transport._htmlForXfa;
  1713. }
  1714. getPage(pageNumber) {
  1715. return this._transport.getPage(pageNumber);
  1716. }
  1717. getPageIndex(ref) {
  1718. return this._transport.getPageIndex(ref);
  1719. }
  1720. getDestinations() {
  1721. return this._transport.getDestinations();
  1722. }
  1723. getDestination(id) {
  1724. return this._transport.getDestination(id);
  1725. }
  1726. getPageLabels() {
  1727. return this._transport.getPageLabels();
  1728. }
  1729. getPageLayout() {
  1730. return this._transport.getPageLayout();
  1731. }
  1732. getPageMode() {
  1733. return this._transport.getPageMode();
  1734. }
  1735. getViewerPreferences() {
  1736. return this._transport.getViewerPreferences();
  1737. }
  1738. getOpenAction() {
  1739. return this._transport.getOpenAction();
  1740. }
  1741. getAttachments() {
  1742. return this._transport.getAttachments();
  1743. }
  1744. getJavaScript() {
  1745. return this._transport.getJavaScript();
  1746. }
  1747. getJSActions() {
  1748. return this._transport.getDocJSActions();
  1749. }
  1750. getOutline() {
  1751. return this._transport.getOutline();
  1752. }
  1753. getOptionalContentConfig() {
  1754. return this._transport.getOptionalContentConfig();
  1755. }
  1756. getPermissions() {
  1757. return this._transport.getPermissions();
  1758. }
  1759. getMetadata() {
  1760. return this._transport.getMetadata();
  1761. }
  1762. getMarkInfo() {
  1763. return this._transport.getMarkInfo();
  1764. }
  1765. getData() {
  1766. return this._transport.getData();
  1767. }
  1768. getDownloadInfo() {
  1769. return this._transport.downloadInfoCapability.promise;
  1770. }
  1771. getStats() {
  1772. return this._transport.getStats();
  1773. }
  1774. cleanup(keepLoadedFonts = false) {
  1775. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1776. }
  1777. destroy() {
  1778. return this.loadingTask.destroy();
  1779. }
  1780. get loadingParams() {
  1781. return this._transport.loadingParams;
  1782. }
  1783. get loadingTask() {
  1784. return this._transport.loadingTask;
  1785. }
  1786. saveDocument() {
  1787. if (this._transport.annotationStorage.size <= 0) {
  1788. (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  1789. }
  1790. return this._transport.saveDocument();
  1791. }
  1792. getFieldObjects() {
  1793. return this._transport.getFieldObjects();
  1794. }
  1795. hasJSActions() {
  1796. return this._transport.hasJSActions();
  1797. }
  1798. getCalculationOrderIds() {
  1799. return this._transport.getCalculationOrderIds();
  1800. }
  1801. }
  1802. exports.PDFDocumentProxy = PDFDocumentProxy;
  1803. class PDFPageProxy {
  1804. constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
  1805. this._pageIndex = pageIndex;
  1806. this._pageInfo = pageInfo;
  1807. this._ownerDocument = ownerDocument;
  1808. this._transport = transport;
  1809. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1810. this._pdfBug = pdfBug;
  1811. this.commonObjs = transport.commonObjs;
  1812. this.objs = new PDFObjects();
  1813. this.cleanupAfterRender = false;
  1814. this.pendingCleanup = false;
  1815. this._intentStates = new Map();
  1816. this.destroyed = false;
  1817. }
  1818. get pageNumber() {
  1819. return this._pageIndex + 1;
  1820. }
  1821. get rotate() {
  1822. return this._pageInfo.rotate;
  1823. }
  1824. get ref() {
  1825. return this._pageInfo.ref;
  1826. }
  1827. get userUnit() {
  1828. return this._pageInfo.userUnit;
  1829. }
  1830. get view() {
  1831. return this._pageInfo.view;
  1832. }
  1833. getViewport({
  1834. scale,
  1835. rotation = this.rotate,
  1836. offsetX = 0,
  1837. offsetY = 0,
  1838. dontFlip = false
  1839. } = {}) {
  1840. return new _display_utils.PageViewport({
  1841. viewBox: this.view,
  1842. scale,
  1843. rotation,
  1844. offsetX,
  1845. offsetY,
  1846. dontFlip
  1847. });
  1848. }
  1849. getAnnotations({
  1850. intent = null
  1851. } = {}) {
  1852. const renderingIntent = intent === "display" || intent === "print" ? intent : null;
  1853. if (!this._annotationsPromise || this._annotationsIntent !== renderingIntent) {
  1854. this._annotationsPromise = this._transport.getAnnotations(this._pageIndex, renderingIntent);
  1855. this._annotationsIntent = renderingIntent;
  1856. }
  1857. return this._annotationsPromise;
  1858. }
  1859. getJSActions() {
  1860. return this._jsActionsPromise || (this._jsActionsPromise = this._transport.getPageJSActions(this._pageIndex));
  1861. }
  1862. async getXfa() {
  1863. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  1864. }
  1865. render({
  1866. canvasContext,
  1867. viewport,
  1868. intent = "display",
  1869. renderInteractiveForms = false,
  1870. transform = null,
  1871. imageLayer = null,
  1872. canvasFactory = null,
  1873. background = null,
  1874. includeAnnotationStorage = false,
  1875. optionalContentConfigPromise = null
  1876. }) {
  1877. var _intentState;
  1878. if (this._stats) {
  1879. this._stats.time("Overall");
  1880. }
  1881. const renderingIntent = intent === "print" ? "print" : "display";
  1882. this.pendingCleanup = false;
  1883. if (!optionalContentConfigPromise) {
  1884. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1885. }
  1886. let intentState = this._intentStates.get(renderingIntent);
  1887. if (!intentState) {
  1888. intentState = Object.create(null);
  1889. this._intentStates.set(renderingIntent, intentState);
  1890. }
  1891. if (intentState.streamReaderCancelTimeout) {
  1892. clearTimeout(intentState.streamReaderCancelTimeout);
  1893. intentState.streamReaderCancelTimeout = null;
  1894. }
  1895. const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
  1896. ownerDocument: this._ownerDocument
  1897. });
  1898. const annotationStorage = includeAnnotationStorage ? this._transport.annotationStorage.serializable : null;
  1899. if (!intentState.displayReadyCapability) {
  1900. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  1901. intentState.operatorList = {
  1902. fnArray: [],
  1903. argsArray: [],
  1904. lastChunk: false
  1905. };
  1906. if (this._stats) {
  1907. this._stats.time("Page Request");
  1908. }
  1909. this._pumpOperatorList({
  1910. pageIndex: this._pageIndex,
  1911. intent: renderingIntent,
  1912. renderInteractiveForms: renderInteractiveForms === true,
  1913. annotationStorage
  1914. });
  1915. }
  1916. const complete = error => {
  1917. intentState.renderTasks.delete(internalRenderTask);
  1918. if (this.cleanupAfterRender || renderingIntent === "print") {
  1919. this.pendingCleanup = true;
  1920. }
  1921. this._tryCleanup();
  1922. if (error) {
  1923. internalRenderTask.capability.reject(error);
  1924. this._abortOperatorList({
  1925. intentState,
  1926. reason: error
  1927. });
  1928. } else {
  1929. internalRenderTask.capability.resolve();
  1930. }
  1931. if (this._stats) {
  1932. this._stats.timeEnd("Rendering");
  1933. this._stats.timeEnd("Overall");
  1934. }
  1935. };
  1936. const internalRenderTask = new InternalRenderTask({
  1937. callback: complete,
  1938. params: {
  1939. canvasContext,
  1940. viewport,
  1941. transform,
  1942. imageLayer,
  1943. background
  1944. },
  1945. objs: this.objs,
  1946. commonObjs: this.commonObjs,
  1947. operatorList: intentState.operatorList,
  1948. pageIndex: this._pageIndex,
  1949. canvasFactory: canvasFactoryInstance,
  1950. useRequestAnimationFrame: renderingIntent !== "print",
  1951. pdfBug: this._pdfBug
  1952. });
  1953. ((_intentState = intentState).renderTasks || (_intentState.renderTasks = new Set())).add(internalRenderTask);
  1954. const renderTask = internalRenderTask.task;
  1955. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  1956. if (this.pendingCleanup) {
  1957. complete();
  1958. return;
  1959. }
  1960. if (this._stats) {
  1961. this._stats.time("Rendering");
  1962. }
  1963. internalRenderTask.initializeGraphics({
  1964. transparency,
  1965. optionalContentConfig
  1966. });
  1967. internalRenderTask.operatorListChanged();
  1968. }).catch(complete);
  1969. return renderTask;
  1970. }
  1971. getOperatorList({
  1972. intent = "display"
  1973. } = {}) {
  1974. function operatorListChanged() {
  1975. if (intentState.operatorList.lastChunk) {
  1976. intentState.opListReadCapability.resolve(intentState.operatorList);
  1977. intentState.renderTasks.delete(opListTask);
  1978. }
  1979. }
  1980. const renderingIntent = `oplist-${intent === "print" ? "print" : "display"}`;
  1981. let intentState = this._intentStates.get(renderingIntent);
  1982. if (!intentState) {
  1983. intentState = Object.create(null);
  1984. this._intentStates.set(renderingIntent, intentState);
  1985. }
  1986. let opListTask;
  1987. if (!intentState.opListReadCapability) {
  1988. var _intentState2;
  1989. opListTask = Object.create(null);
  1990. opListTask.operatorListChanged = operatorListChanged;
  1991. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  1992. ((_intentState2 = intentState).renderTasks || (_intentState2.renderTasks = new Set())).add(opListTask);
  1993. intentState.operatorList = {
  1994. fnArray: [],
  1995. argsArray: [],
  1996. lastChunk: false
  1997. };
  1998. if (this._stats) {
  1999. this._stats.time("Page Request");
  2000. }
  2001. this._pumpOperatorList({
  2002. pageIndex: this._pageIndex,
  2003. intent: renderingIntent
  2004. });
  2005. }
  2006. return intentState.opListReadCapability.promise;
  2007. }
  2008. streamTextContent({
  2009. normalizeWhitespace = false,
  2010. disableCombineTextItems = false,
  2011. includeMarkedContent = false
  2012. } = {}) {
  2013. const TEXT_CONTENT_CHUNK_SIZE = 100;
  2014. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  2015. pageIndex: this._pageIndex,
  2016. normalizeWhitespace: normalizeWhitespace === true,
  2017. combineTextItems: disableCombineTextItems !== true,
  2018. includeMarkedContent: includeMarkedContent === true
  2019. }, {
  2020. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  2021. size(textContent) {
  2022. return textContent.items.length;
  2023. }
  2024. });
  2025. }
  2026. getTextContent(params = {}) {
  2027. const readableStream = this.streamTextContent(params);
  2028. return new Promise(function (resolve, reject) {
  2029. function pump() {
  2030. reader.read().then(function ({
  2031. value,
  2032. done
  2033. }) {
  2034. if (done) {
  2035. resolve(textContent);
  2036. return;
  2037. }
  2038. Object.assign(textContent.styles, value.styles);
  2039. textContent.items.push(...value.items);
  2040. pump();
  2041. }, reject);
  2042. }
  2043. const reader = readableStream.getReader();
  2044. const textContent = {
  2045. items: [],
  2046. styles: Object.create(null)
  2047. };
  2048. pump();
  2049. });
  2050. }
  2051. getStructTree() {
  2052. return this._structTreePromise || (this._structTreePromise = this._transport.getStructTree(this._pageIndex));
  2053. }
  2054. _destroy() {
  2055. this.destroyed = true;
  2056. this._transport.pageCache[this._pageIndex] = null;
  2057. const waitOn = [];
  2058. for (const [intent, intentState] of this._intentStates) {
  2059. this._abortOperatorList({
  2060. intentState,
  2061. reason: new Error("Page was destroyed."),
  2062. force: true
  2063. });
  2064. if (intent.startsWith("oplist-")) {
  2065. continue;
  2066. }
  2067. for (const internalRenderTask of intentState.renderTasks) {
  2068. waitOn.push(internalRenderTask.completed);
  2069. internalRenderTask.cancel();
  2070. }
  2071. }
  2072. this.objs.clear();
  2073. this._annotationsPromise = null;
  2074. this._jsActionsPromise = null;
  2075. this._structTreePromise = null;
  2076. this.pendingCleanup = false;
  2077. return Promise.all(waitOn);
  2078. }
  2079. cleanup(resetStats = false) {
  2080. this.pendingCleanup = true;
  2081. return this._tryCleanup(resetStats);
  2082. }
  2083. _tryCleanup(resetStats = false) {
  2084. if (!this.pendingCleanup) {
  2085. return false;
  2086. }
  2087. for (const {
  2088. renderTasks,
  2089. operatorList
  2090. } of this._intentStates.values()) {
  2091. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  2092. return false;
  2093. }
  2094. }
  2095. this._intentStates.clear();
  2096. this.objs.clear();
  2097. this._annotationsPromise = null;
  2098. this._jsActionsPromise = null;
  2099. this._structTreePromise = null;
  2100. if (resetStats && this._stats) {
  2101. this._stats = new _display_utils.StatTimer();
  2102. }
  2103. this.pendingCleanup = false;
  2104. return true;
  2105. }
  2106. _startRenderPage(transparency, intent) {
  2107. const intentState = this._intentStates.get(intent);
  2108. if (!intentState) {
  2109. return;
  2110. }
  2111. if (this._stats) {
  2112. this._stats.timeEnd("Page Request");
  2113. }
  2114. if (intentState.displayReadyCapability) {
  2115. intentState.displayReadyCapability.resolve(transparency);
  2116. }
  2117. }
  2118. _renderPageChunk(operatorListChunk, intentState) {
  2119. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2120. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2121. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  2122. }
  2123. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2124. for (const internalRenderTask of intentState.renderTasks) {
  2125. internalRenderTask.operatorListChanged();
  2126. }
  2127. if (operatorListChunk.lastChunk) {
  2128. this._tryCleanup();
  2129. }
  2130. }
  2131. _pumpOperatorList(args) {
  2132. (0, _util.assert)(args.intent, 'PDFPageProxy._pumpOperatorList: Expected "intent" argument.');
  2133. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", args);
  2134. const reader = readableStream.getReader();
  2135. const intentState = this._intentStates.get(args.intent);
  2136. intentState.streamReader = reader;
  2137. const pump = () => {
  2138. reader.read().then(({
  2139. value,
  2140. done
  2141. }) => {
  2142. if (done) {
  2143. intentState.streamReader = null;
  2144. return;
  2145. }
  2146. if (this._transport.destroyed) {
  2147. return;
  2148. }
  2149. this._renderPageChunk(value, intentState);
  2150. pump();
  2151. }, reason => {
  2152. intentState.streamReader = null;
  2153. if (this._transport.destroyed) {
  2154. return;
  2155. }
  2156. if (intentState.operatorList) {
  2157. intentState.operatorList.lastChunk = true;
  2158. for (const internalRenderTask of intentState.renderTasks) {
  2159. internalRenderTask.operatorListChanged();
  2160. }
  2161. this._tryCleanup();
  2162. }
  2163. if (intentState.displayReadyCapability) {
  2164. intentState.displayReadyCapability.reject(reason);
  2165. } else if (intentState.opListReadCapability) {
  2166. intentState.opListReadCapability.reject(reason);
  2167. } else {
  2168. throw reason;
  2169. }
  2170. });
  2171. };
  2172. pump();
  2173. }
  2174. _abortOperatorList({
  2175. intentState,
  2176. reason,
  2177. force = false
  2178. }) {
  2179. (0, _util.assert)(reason instanceof Error || typeof reason === "object" && reason !== null, 'PDFPageProxy._abortOperatorList: Expected "reason" argument.');
  2180. if (!intentState.streamReader) {
  2181. return;
  2182. }
  2183. if (!force) {
  2184. if (intentState.renderTasks.size > 0) {
  2185. return;
  2186. }
  2187. if (reason instanceof _display_utils.RenderingCancelledException) {
  2188. intentState.streamReaderCancelTimeout = setTimeout(() => {
  2189. this._abortOperatorList({
  2190. intentState,
  2191. reason,
  2192. force: true
  2193. });
  2194. intentState.streamReaderCancelTimeout = null;
  2195. }, RENDERING_CANCELLED_TIMEOUT);
  2196. return;
  2197. }
  2198. }
  2199. intentState.streamReader.cancel(new _util.AbortException(reason?.message));
  2200. intentState.streamReader = null;
  2201. if (this._transport.destroyed) {
  2202. return;
  2203. }
  2204. for (const [intent, curIntentState] of this._intentStates) {
  2205. if (curIntentState === intentState) {
  2206. this._intentStates.delete(intent);
  2207. break;
  2208. }
  2209. }
  2210. this.cleanup();
  2211. }
  2212. get stats() {
  2213. return this._stats;
  2214. }
  2215. }
  2216. exports.PDFPageProxy = PDFPageProxy;
  2217. class LoopbackPort {
  2218. constructor() {
  2219. this._listeners = [];
  2220. this._deferred = Promise.resolve(undefined);
  2221. }
  2222. postMessage(obj, transfers) {
  2223. function cloneValue(value) {
  2224. if (typeof value === "function" || typeof value === "symbol" || value instanceof URL) {
  2225. throw new Error(`LoopbackPort.postMessage - cannot clone: ${value?.toString()}`);
  2226. }
  2227. if (typeof value !== "object" || value === null) {
  2228. return value;
  2229. }
  2230. if (cloned.has(value)) {
  2231. return cloned.get(value);
  2232. }
  2233. let buffer, result;
  2234. if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) {
  2235. if (transfers?.includes(buffer)) {
  2236. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  2237. } else {
  2238. result = new value.constructor(value);
  2239. }
  2240. cloned.set(value, result);
  2241. return result;
  2242. }
  2243. if (value instanceof Map) {
  2244. result = new Map();
  2245. cloned.set(value, result);
  2246. for (const [key, val] of value) {
  2247. result.set(key, cloneValue(val));
  2248. }
  2249. return result;
  2250. }
  2251. if (value instanceof Set) {
  2252. result = new Set();
  2253. cloned.set(value, result);
  2254. for (const val of value) {
  2255. result.add(cloneValue(val));
  2256. }
  2257. return result;
  2258. }
  2259. result = Array.isArray(value) ? [] : Object.create(null);
  2260. cloned.set(value, result);
  2261. for (const i in value) {
  2262. let desc,
  2263. p = value;
  2264. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  2265. p = Object.getPrototypeOf(p);
  2266. }
  2267. if (typeof desc.value === "undefined") {
  2268. continue;
  2269. }
  2270. if (typeof desc.value === "function" && !value.hasOwnProperty?.(i)) {
  2271. continue;
  2272. }
  2273. result[i] = cloneValue(desc.value);
  2274. }
  2275. return result;
  2276. }
  2277. const cloned = new WeakMap();
  2278. const event = {
  2279. data: cloneValue(obj)
  2280. };
  2281. this._deferred.then(() => {
  2282. for (const listener of this._listeners) {
  2283. listener.call(this, event);
  2284. }
  2285. });
  2286. }
  2287. addEventListener(name, listener) {
  2288. this._listeners.push(listener);
  2289. }
  2290. removeEventListener(name, listener) {
  2291. const i = this._listeners.indexOf(listener);
  2292. this._listeners.splice(i, 1);
  2293. }
  2294. terminate() {
  2295. this._listeners.length = 0;
  2296. }
  2297. }
  2298. exports.LoopbackPort = LoopbackPort;
  2299. const PDFWorker = function PDFWorkerClosure() {
  2300. const pdfWorkerPorts = new WeakMap();
  2301. let isWorkerDisabled = false;
  2302. let fallbackWorkerSrc;
  2303. let nextFakeWorkerId = 0;
  2304. let fakeWorkerCapability;
  2305. if (_is_node.isNodeJS && typeof require === "function") {
  2306. isWorkerDisabled = true;
  2307. fallbackWorkerSrc = "./pdf.worker.js";
  2308. } else if (typeof document === "object" && "currentScript" in document) {
  2309. const pdfjsFilePath = document.currentScript?.src;
  2310. if (pdfjsFilePath) {
  2311. fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  2312. }
  2313. }
  2314. function getWorkerSrc() {
  2315. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  2316. return _worker_options.GlobalWorkerOptions.workerSrc;
  2317. }
  2318. if (typeof fallbackWorkerSrc !== "undefined") {
  2319. if (!_is_node.isNodeJS) {
  2320. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  2321. }
  2322. return fallbackWorkerSrc;
  2323. }
  2324. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  2325. }
  2326. function getMainThreadWorkerMessageHandler() {
  2327. let mainWorkerMessageHandler;
  2328. try {
  2329. mainWorkerMessageHandler = globalThis.pdfjsWorker?.WorkerMessageHandler;
  2330. } catch (ex) {}
  2331. return mainWorkerMessageHandler || null;
  2332. }
  2333. function setupFakeWorkerGlobal() {
  2334. if (fakeWorkerCapability) {
  2335. return fakeWorkerCapability.promise;
  2336. }
  2337. fakeWorkerCapability = (0, _util.createPromiseCapability)();
  2338. const loader = async function () {
  2339. const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler();
  2340. if (mainWorkerMessageHandler) {
  2341. return mainWorkerMessageHandler;
  2342. }
  2343. if (_is_node.isNodeJS && typeof require === "function") {
  2344. const worker = eval("require")(getWorkerSrc());
  2345. return worker.WorkerMessageHandler;
  2346. }
  2347. await (0, _display_utils.loadScript)(getWorkerSrc());
  2348. return window.pdfjsWorker.WorkerMessageHandler;
  2349. };
  2350. loader().then(fakeWorkerCapability.resolve, fakeWorkerCapability.reject);
  2351. return fakeWorkerCapability.promise;
  2352. }
  2353. function createCDNWrapper(url) {
  2354. const wrapper = "importScripts('" + url + "');";
  2355. return URL.createObjectURL(new Blob([wrapper]));
  2356. }
  2357. class PDFWorker {
  2358. constructor({
  2359. name = null,
  2360. port = null,
  2361. verbosity = (0, _util.getVerbosityLevel)()
  2362. } = {}) {
  2363. if (port && pdfWorkerPorts.has(port)) {
  2364. throw new Error("Cannot use more than one PDFWorker per port");
  2365. }
  2366. this.name = name;
  2367. this.destroyed = false;
  2368. this.postMessageTransfers = true;
  2369. this.verbosity = verbosity;
  2370. this._readyCapability = (0, _util.createPromiseCapability)();
  2371. this._port = null;
  2372. this._webWorker = null;
  2373. this._messageHandler = null;
  2374. if (port) {
  2375. pdfWorkerPorts.set(port, this);
  2376. this._initializeFromPort(port);
  2377. return;
  2378. }
  2379. this._initialize();
  2380. }
  2381. get promise() {
  2382. return this._readyCapability.promise;
  2383. }
  2384. get port() {
  2385. return this._port;
  2386. }
  2387. get messageHandler() {
  2388. return this._messageHandler;
  2389. }
  2390. _initializeFromPort(port) {
  2391. this._port = port;
  2392. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  2393. this._messageHandler.on("ready", function () {});
  2394. this._readyCapability.resolve();
  2395. }
  2396. _initialize() {
  2397. if (typeof Worker !== "undefined" && !isWorkerDisabled && !getMainThreadWorkerMessageHandler()) {
  2398. let workerSrc = getWorkerSrc();
  2399. try {
  2400. if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) {
  2401. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  2402. }
  2403. const worker = new Worker(workerSrc);
  2404. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  2405. const terminateEarly = () => {
  2406. worker.removeEventListener("error", onWorkerError);
  2407. messageHandler.destroy();
  2408. worker.terminate();
  2409. if (this.destroyed) {
  2410. this._readyCapability.reject(new Error("Worker was destroyed"));
  2411. } else {
  2412. this._setupFakeWorker();
  2413. }
  2414. };
  2415. const onWorkerError = () => {
  2416. if (!this._webWorker) {
  2417. terminateEarly();
  2418. }
  2419. };
  2420. worker.addEventListener("error", onWorkerError);
  2421. messageHandler.on("test", data => {
  2422. worker.removeEventListener("error", onWorkerError);
  2423. if (this.destroyed) {
  2424. terminateEarly();
  2425. return;
  2426. }
  2427. if (data) {
  2428. this._messageHandler = messageHandler;
  2429. this._port = worker;
  2430. this._webWorker = worker;
  2431. if (!data.supportTransfers) {
  2432. this.postMessageTransfers = false;
  2433. }
  2434. this._readyCapability.resolve();
  2435. messageHandler.send("configure", {
  2436. verbosity: this.verbosity
  2437. });
  2438. } else {
  2439. this._setupFakeWorker();
  2440. messageHandler.destroy();
  2441. worker.terminate();
  2442. }
  2443. });
  2444. messageHandler.on("ready", data => {
  2445. worker.removeEventListener("error", onWorkerError);
  2446. if (this.destroyed) {
  2447. terminateEarly();
  2448. return;
  2449. }
  2450. try {
  2451. sendTest();
  2452. } catch (e) {
  2453. this._setupFakeWorker();
  2454. }
  2455. });
  2456. const sendTest = () => {
  2457. const testObj = new Uint8Array([this.postMessageTransfers ? 255 : 0]);
  2458. try {
  2459. messageHandler.send("test", testObj, [testObj.buffer]);
  2460. } catch (ex) {
  2461. (0, _util.warn)("Cannot use postMessage transfers.");
  2462. testObj[0] = 0;
  2463. messageHandler.send("test", testObj);
  2464. }
  2465. };
  2466. sendTest();
  2467. return;
  2468. } catch (e) {
  2469. (0, _util.info)("The worker has been disabled.");
  2470. }
  2471. }
  2472. this._setupFakeWorker();
  2473. }
  2474. _setupFakeWorker() {
  2475. if (!isWorkerDisabled) {
  2476. (0, _util.warn)("Setting up fake worker.");
  2477. isWorkerDisabled = true;
  2478. }
  2479. setupFakeWorkerGlobal().then(WorkerMessageHandler => {
  2480. if (this.destroyed) {
  2481. this._readyCapability.reject(new Error("Worker was destroyed"));
  2482. return;
  2483. }
  2484. const port = new LoopbackPort();
  2485. this._port = port;
  2486. const id = "fake" + nextFakeWorkerId++;
  2487. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  2488. WorkerMessageHandler.setup(workerHandler, port);
  2489. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  2490. this._messageHandler = messageHandler;
  2491. this._readyCapability.resolve();
  2492. messageHandler.send("configure", {
  2493. verbosity: this.verbosity
  2494. });
  2495. }).catch(reason => {
  2496. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  2497. });
  2498. }
  2499. destroy() {
  2500. this.destroyed = true;
  2501. if (this._webWorker) {
  2502. this._webWorker.terminate();
  2503. this._webWorker = null;
  2504. }
  2505. pdfWorkerPorts.delete(this._port);
  2506. this._port = null;
  2507. if (this._messageHandler) {
  2508. this._messageHandler.destroy();
  2509. this._messageHandler = null;
  2510. }
  2511. }
  2512. static fromPort(params) {
  2513. if (!params || !params.port) {
  2514. throw new Error("PDFWorker.fromPort - invalid method signature.");
  2515. }
  2516. if (pdfWorkerPorts.has(params.port)) {
  2517. return pdfWorkerPorts.get(params.port);
  2518. }
  2519. return new PDFWorker(params);
  2520. }
  2521. static getWorkerSrc() {
  2522. return getWorkerSrc();
  2523. }
  2524. }
  2525. return PDFWorker;
  2526. }();
  2527. exports.PDFWorker = PDFWorker;
  2528. class WorkerTransport {
  2529. constructor(messageHandler, loadingTask, networkStream, params) {
  2530. this.messageHandler = messageHandler;
  2531. this.loadingTask = loadingTask;
  2532. this.commonObjs = new PDFObjects();
  2533. this.fontLoader = new _font_loader.FontLoader({
  2534. docId: loadingTask.docId,
  2535. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2536. ownerDocument: params.ownerDocument,
  2537. styleElement: params.styleElement
  2538. });
  2539. this._params = params;
  2540. if (!params.useWorkerFetch) {
  2541. this.CMapReaderFactory = new params.CMapReaderFactory({
  2542. baseUrl: params.cMapUrl,
  2543. isCompressed: params.cMapPacked
  2544. });
  2545. this.StandardFontDataFactory = new params.StandardFontDataFactory({
  2546. baseUrl: params.standardFontDataUrl
  2547. });
  2548. }
  2549. this.destroyed = false;
  2550. this.destroyCapability = null;
  2551. this._passwordCapability = null;
  2552. this._networkStream = networkStream;
  2553. this._fullReader = null;
  2554. this._lastProgress = null;
  2555. this.pageCache = [];
  2556. this.pagePromises = [];
  2557. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  2558. this.setupMessageHandler();
  2559. }
  2560. get annotationStorage() {
  2561. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2562. }
  2563. destroy() {
  2564. if (this.destroyCapability) {
  2565. return this.destroyCapability.promise;
  2566. }
  2567. this.destroyed = true;
  2568. this.destroyCapability = (0, _util.createPromiseCapability)();
  2569. if (this._passwordCapability) {
  2570. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2571. }
  2572. const waitOn = [];
  2573. for (const page of this.pageCache) {
  2574. if (page) {
  2575. waitOn.push(page._destroy());
  2576. }
  2577. }
  2578. this.pageCache.length = 0;
  2579. this.pagePromises.length = 0;
  2580. if (this.hasOwnProperty("annotationStorage")) {
  2581. this.annotationStorage.resetModified();
  2582. }
  2583. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2584. waitOn.push(terminated);
  2585. Promise.all(waitOn).then(() => {
  2586. this.commonObjs.clear();
  2587. this.fontLoader.clear();
  2588. this._hasJSActionsPromise = null;
  2589. if (this._networkStream) {
  2590. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2591. }
  2592. if (this.messageHandler) {
  2593. this.messageHandler.destroy();
  2594. this.messageHandler = null;
  2595. }
  2596. this.destroyCapability.resolve();
  2597. }, this.destroyCapability.reject);
  2598. return this.destroyCapability.promise;
  2599. }
  2600. setupMessageHandler() {
  2601. const {
  2602. messageHandler,
  2603. loadingTask
  2604. } = this;
  2605. messageHandler.on("GetReader", (data, sink) => {
  2606. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2607. this._fullReader = this._networkStream.getFullReader();
  2608. this._fullReader.onProgress = evt => {
  2609. this._lastProgress = {
  2610. loaded: evt.loaded,
  2611. total: evt.total
  2612. };
  2613. };
  2614. sink.onPull = () => {
  2615. this._fullReader.read().then(function ({
  2616. value,
  2617. done
  2618. }) {
  2619. if (done) {
  2620. sink.close();
  2621. return;
  2622. }
  2623. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
  2624. sink.enqueue(new Uint8Array(value), 1, [value]);
  2625. }).catch(reason => {
  2626. sink.error(reason);
  2627. });
  2628. };
  2629. sink.onCancel = reason => {
  2630. this._fullReader.cancel(reason);
  2631. sink.ready.catch(readyReason => {
  2632. if (this.destroyed) {
  2633. return;
  2634. }
  2635. throw readyReason;
  2636. });
  2637. };
  2638. });
  2639. messageHandler.on("ReaderHeadersReady", data => {
  2640. const headersCapability = (0, _util.createPromiseCapability)();
  2641. const fullReader = this._fullReader;
  2642. fullReader.headersReady.then(() => {
  2643. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2644. if (this._lastProgress && loadingTask.onProgress) {
  2645. loadingTask.onProgress(this._lastProgress);
  2646. }
  2647. fullReader.onProgress = evt => {
  2648. if (loadingTask.onProgress) {
  2649. loadingTask.onProgress({
  2650. loaded: evt.loaded,
  2651. total: evt.total
  2652. });
  2653. }
  2654. };
  2655. }
  2656. headersCapability.resolve({
  2657. isStreamingSupported: fullReader.isStreamingSupported,
  2658. isRangeSupported: fullReader.isRangeSupported,
  2659. contentLength: fullReader.contentLength
  2660. });
  2661. }, headersCapability.reject);
  2662. return headersCapability.promise;
  2663. });
  2664. messageHandler.on("GetRangeReader", (data, sink) => {
  2665. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2666. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2667. if (!rangeReader) {
  2668. sink.close();
  2669. return;
  2670. }
  2671. sink.onPull = () => {
  2672. rangeReader.read().then(function ({
  2673. value,
  2674. done
  2675. }) {
  2676. if (done) {
  2677. sink.close();
  2678. return;
  2679. }
  2680. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
  2681. sink.enqueue(new Uint8Array(value), 1, [value]);
  2682. }).catch(reason => {
  2683. sink.error(reason);
  2684. });
  2685. };
  2686. sink.onCancel = reason => {
  2687. rangeReader.cancel(reason);
  2688. sink.ready.catch(readyReason => {
  2689. if (this.destroyed) {
  2690. return;
  2691. }
  2692. throw readyReason;
  2693. });
  2694. };
  2695. });
  2696. messageHandler.on("GetDoc", ({
  2697. pdfInfo
  2698. }) => {
  2699. this._numPages = pdfInfo.numPages;
  2700. this._htmlForXfa = pdfInfo.htmlForXfa;
  2701. delete pdfInfo.htmlForXfa;
  2702. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2703. });
  2704. messageHandler.on("DocException", function (ex) {
  2705. let reason;
  2706. switch (ex.name) {
  2707. case "PasswordException":
  2708. reason = new _util.PasswordException(ex.message, ex.code);
  2709. break;
  2710. case "InvalidPDFException":
  2711. reason = new _util.InvalidPDFException(ex.message);
  2712. break;
  2713. case "MissingPDFException":
  2714. reason = new _util.MissingPDFException(ex.message);
  2715. break;
  2716. case "UnexpectedResponseException":
  2717. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2718. break;
  2719. case "UnknownErrorException":
  2720. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2721. break;
  2722. }
  2723. if (!(reason instanceof Error)) {
  2724. const msg = "DocException - expected a valid Error.";
  2725. (0, _util.warn)(msg);
  2726. }
  2727. loadingTask._capability.reject(reason);
  2728. });
  2729. messageHandler.on("PasswordRequest", exception => {
  2730. this._passwordCapability = (0, _util.createPromiseCapability)();
  2731. if (loadingTask.onPassword) {
  2732. const updatePassword = password => {
  2733. this._passwordCapability.resolve({
  2734. password
  2735. });
  2736. };
  2737. try {
  2738. loadingTask.onPassword(updatePassword, exception.code);
  2739. } catch (ex) {
  2740. this._passwordCapability.reject(ex);
  2741. }
  2742. } else {
  2743. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2744. }
  2745. return this._passwordCapability.promise;
  2746. });
  2747. messageHandler.on("DataLoaded", data => {
  2748. if (loadingTask.onProgress) {
  2749. loadingTask.onProgress({
  2750. loaded: data.length,
  2751. total: data.length
  2752. });
  2753. }
  2754. this.downloadInfoCapability.resolve(data);
  2755. });
  2756. messageHandler.on("StartRenderPage", data => {
  2757. if (this.destroyed) {
  2758. return;
  2759. }
  2760. const page = this.pageCache[data.pageIndex];
  2761. page._startRenderPage(data.transparency, data.intent);
  2762. });
  2763. messageHandler.on("commonobj", data => {
  2764. if (this.destroyed) {
  2765. return;
  2766. }
  2767. const [id, type, exportedData] = data;
  2768. if (this.commonObjs.has(id)) {
  2769. return;
  2770. }
  2771. switch (type) {
  2772. case "Font":
  2773. const params = this._params;
  2774. if ("error" in exportedData) {
  2775. const exportedError = exportedData.error;
  2776. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2777. this.commonObjs.resolve(id, exportedError);
  2778. break;
  2779. }
  2780. let fontRegistry = null;
  2781. if (params.pdfBug && globalThis.FontInspector?.enabled) {
  2782. fontRegistry = {
  2783. registerFont(font, url) {
  2784. globalThis.FontInspector.fontAdded(font, url);
  2785. }
  2786. };
  2787. }
  2788. const font = new _font_loader.FontFaceObject(exportedData, {
  2789. isEvalSupported: params.isEvalSupported,
  2790. disableFontFace: params.disableFontFace,
  2791. ignoreErrors: params.ignoreErrors,
  2792. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2793. fontRegistry
  2794. });
  2795. this.fontLoader.bind(font).catch(reason => {
  2796. return messageHandler.sendWithPromise("FontFallback", {
  2797. id
  2798. });
  2799. }).finally(() => {
  2800. if (!params.fontExtraProperties && font.data) {
  2801. font.data = null;
  2802. }
  2803. this.commonObjs.resolve(id, font);
  2804. });
  2805. break;
  2806. case "FontPath":
  2807. case "Image":
  2808. this.commonObjs.resolve(id, exportedData);
  2809. break;
  2810. default:
  2811. throw new Error(`Got unknown common object type ${type}`);
  2812. }
  2813. });
  2814. messageHandler.on("obj", data => {
  2815. if (this.destroyed) {
  2816. return undefined;
  2817. }
  2818. const [id, pageIndex, type, imageData] = data;
  2819. const pageProxy = this.pageCache[pageIndex];
  2820. if (pageProxy.objs.has(id)) {
  2821. return undefined;
  2822. }
  2823. switch (type) {
  2824. case "Image":
  2825. pageProxy.objs.resolve(id, imageData);
  2826. const MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2827. if (imageData?.data?.length > MAX_IMAGE_SIZE_TO_STORE) {
  2828. pageProxy.cleanupAfterRender = true;
  2829. }
  2830. break;
  2831. case "Pattern":
  2832. pageProxy.objs.resolve(id, imageData);
  2833. break;
  2834. default:
  2835. throw new Error(`Got unknown object type ${type}`);
  2836. }
  2837. return undefined;
  2838. });
  2839. messageHandler.on("DocProgress", data => {
  2840. if (this.destroyed) {
  2841. return;
  2842. }
  2843. if (loadingTask.onProgress) {
  2844. loadingTask.onProgress({
  2845. loaded: data.loaded,
  2846. total: data.total
  2847. });
  2848. }
  2849. });
  2850. messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
  2851. messageHandler.on("FetchBuiltInCMap", data => {
  2852. if (this.destroyed) {
  2853. return Promise.reject(new Error("Worker was destroyed."));
  2854. }
  2855. if (!this.CMapReaderFactory) {
  2856. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  2857. }
  2858. return this.CMapReaderFactory.fetch(data);
  2859. });
  2860. messageHandler.on("FetchStandardFontData", data => {
  2861. if (this.destroyed) {
  2862. return Promise.reject(new Error("Worker was destroyed."));
  2863. }
  2864. if (!this.StandardFontDataFactory) {
  2865. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  2866. }
  2867. return this.StandardFontDataFactory.fetch(data);
  2868. });
  2869. }
  2870. _onUnsupportedFeature({
  2871. featureId
  2872. }) {
  2873. if (this.destroyed) {
  2874. return;
  2875. }
  2876. if (this.loadingTask.onUnsupportedFeature) {
  2877. this.loadingTask.onUnsupportedFeature(featureId);
  2878. }
  2879. }
  2880. getData() {
  2881. return this.messageHandler.sendWithPromise("GetData", null);
  2882. }
  2883. getPage(pageNumber) {
  2884. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  2885. return Promise.reject(new Error("Invalid page request"));
  2886. }
  2887. const pageIndex = pageNumber - 1;
  2888. if (pageIndex in this.pagePromises) {
  2889. return this.pagePromises[pageIndex];
  2890. }
  2891. const promise = this.messageHandler.sendWithPromise("GetPage", {
  2892. pageIndex
  2893. }).then(pageInfo => {
  2894. if (this.destroyed) {
  2895. throw new Error("Transport destroyed");
  2896. }
  2897. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
  2898. this.pageCache[pageIndex] = page;
  2899. return page;
  2900. });
  2901. this.pagePromises[pageIndex] = promise;
  2902. return promise;
  2903. }
  2904. getPageIndex(ref) {
  2905. return this.messageHandler.sendWithPromise("GetPageIndex", {
  2906. ref
  2907. }).catch(function (reason) {
  2908. return Promise.reject(new Error(reason));
  2909. });
  2910. }
  2911. getAnnotations(pageIndex, intent) {
  2912. return this.messageHandler.sendWithPromise("GetAnnotations", {
  2913. pageIndex,
  2914. intent
  2915. });
  2916. }
  2917. saveDocument() {
  2918. return this.messageHandler.sendWithPromise("SaveDocument", {
  2919. isPureXfa: !!this._htmlForXfa,
  2920. numPages: this._numPages,
  2921. annotationStorage: this.annotationStorage.serializable,
  2922. filename: this._fullReader?.filename ?? null
  2923. }).finally(() => {
  2924. this.annotationStorage.resetModified();
  2925. });
  2926. }
  2927. getFieldObjects() {
  2928. return this.messageHandler.sendWithPromise("GetFieldObjects", null);
  2929. }
  2930. hasJSActions() {
  2931. return this._hasJSActionsPromise || (this._hasJSActionsPromise = this.messageHandler.sendWithPromise("HasJSActions", null));
  2932. }
  2933. getCalculationOrderIds() {
  2934. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  2935. }
  2936. getDestinations() {
  2937. return this.messageHandler.sendWithPromise("GetDestinations", null);
  2938. }
  2939. getDestination(id) {
  2940. if (typeof id !== "string") {
  2941. return Promise.reject(new Error("Invalid destination request."));
  2942. }
  2943. return this.messageHandler.sendWithPromise("GetDestination", {
  2944. id
  2945. });
  2946. }
  2947. getPageLabels() {
  2948. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  2949. }
  2950. getPageLayout() {
  2951. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  2952. }
  2953. getPageMode() {
  2954. return this.messageHandler.sendWithPromise("GetPageMode", null);
  2955. }
  2956. getViewerPreferences() {
  2957. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  2958. }
  2959. getOpenAction() {
  2960. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  2961. }
  2962. getAttachments() {
  2963. return this.messageHandler.sendWithPromise("GetAttachments", null);
  2964. }
  2965. getJavaScript() {
  2966. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  2967. }
  2968. getDocJSActions() {
  2969. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  2970. }
  2971. getPageJSActions(pageIndex) {
  2972. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  2973. pageIndex
  2974. });
  2975. }
  2976. getStructTree(pageIndex) {
  2977. return this.messageHandler.sendWithPromise("GetStructTree", {
  2978. pageIndex
  2979. });
  2980. }
  2981. getOutline() {
  2982. return this.messageHandler.sendWithPromise("GetOutline", null);
  2983. }
  2984. getOptionalContentConfig() {
  2985. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  2986. return new _optional_content_config.OptionalContentConfig(results);
  2987. });
  2988. }
  2989. getPermissions() {
  2990. return this.messageHandler.sendWithPromise("GetPermissions", null);
  2991. }
  2992. getMetadata() {
  2993. return this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
  2994. return {
  2995. info: results[0],
  2996. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  2997. contentDispositionFilename: this._fullReader?.filename ?? null,
  2998. contentLength: this._fullReader?.contentLength ?? null
  2999. };
  3000. });
  3001. }
  3002. getMarkInfo() {
  3003. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  3004. }
  3005. getStats() {
  3006. return this.messageHandler.sendWithPromise("GetStats", null);
  3007. }
  3008. async startCleanup(keepLoadedFonts = false) {
  3009. await this.messageHandler.sendWithPromise("Cleanup", null);
  3010. if (this.destroyed) {
  3011. return;
  3012. }
  3013. for (let i = 0, ii = this.pageCache.length; i < ii; i++) {
  3014. const page = this.pageCache[i];
  3015. if (!page) {
  3016. continue;
  3017. }
  3018. const cleanupSuccessful = page.cleanup();
  3019. if (!cleanupSuccessful) {
  3020. throw new Error(`startCleanup: Page ${i + 1} is currently rendering.`);
  3021. }
  3022. }
  3023. this.commonObjs.clear();
  3024. if (!keepLoadedFonts) {
  3025. this.fontLoader.clear();
  3026. }
  3027. this._hasJSActionsPromise = null;
  3028. }
  3029. get loadingParams() {
  3030. const params = this._params;
  3031. return (0, _util.shadow)(this, "loadingParams", {
  3032. disableAutoFetch: params.disableAutoFetch
  3033. });
  3034. }
  3035. }
  3036. class PDFObjects {
  3037. constructor() {
  3038. this._objs = Object.create(null);
  3039. }
  3040. _ensureObj(objId) {
  3041. if (this._objs[objId]) {
  3042. return this._objs[objId];
  3043. }
  3044. return this._objs[objId] = {
  3045. capability: (0, _util.createPromiseCapability)(),
  3046. data: null,
  3047. resolved: false
  3048. };
  3049. }
  3050. get(objId, callback = null) {
  3051. if (callback) {
  3052. this._ensureObj(objId).capability.promise.then(callback);
  3053. return null;
  3054. }
  3055. const obj = this._objs[objId];
  3056. if (!obj || !obj.resolved) {
  3057. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  3058. }
  3059. return obj.data;
  3060. }
  3061. has(objId) {
  3062. const obj = this._objs[objId];
  3063. return obj?.resolved || false;
  3064. }
  3065. resolve(objId, data) {
  3066. const obj = this._ensureObj(objId);
  3067. obj.resolved = true;
  3068. obj.data = data;
  3069. obj.capability.resolve(data);
  3070. }
  3071. clear() {
  3072. this._objs = Object.create(null);
  3073. }
  3074. }
  3075. class RenderTask {
  3076. constructor(internalRenderTask) {
  3077. this._internalRenderTask = internalRenderTask;
  3078. this.onContinue = null;
  3079. }
  3080. get promise() {
  3081. return this._internalRenderTask.capability.promise;
  3082. }
  3083. cancel() {
  3084. this._internalRenderTask.cancel();
  3085. }
  3086. }
  3087. const InternalRenderTask = function InternalRenderTaskClosure() {
  3088. const canvasInRendering = new WeakSet();
  3089. class InternalRenderTask {
  3090. constructor({
  3091. callback,
  3092. params,
  3093. objs,
  3094. commonObjs,
  3095. operatorList,
  3096. pageIndex,
  3097. canvasFactory,
  3098. useRequestAnimationFrame = false,
  3099. pdfBug = false
  3100. }) {
  3101. this.callback = callback;
  3102. this.params = params;
  3103. this.objs = objs;
  3104. this.commonObjs = commonObjs;
  3105. this.operatorListIdx = null;
  3106. this.operatorList = operatorList;
  3107. this._pageIndex = pageIndex;
  3108. this.canvasFactory = canvasFactory;
  3109. this._pdfBug = pdfBug;
  3110. this.running = false;
  3111. this.graphicsReadyCallback = null;
  3112. this.graphicsReady = false;
  3113. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  3114. this.cancelled = false;
  3115. this.capability = (0, _util.createPromiseCapability)();
  3116. this.task = new RenderTask(this);
  3117. this._cancelBound = this.cancel.bind(this);
  3118. this._continueBound = this._continue.bind(this);
  3119. this._scheduleNextBound = this._scheduleNext.bind(this);
  3120. this._nextBound = this._next.bind(this);
  3121. this._canvas = params.canvasContext.canvas;
  3122. }
  3123. get completed() {
  3124. return this.capability.promise.catch(function () {});
  3125. }
  3126. initializeGraphics({
  3127. transparency = false,
  3128. optionalContentConfig
  3129. }) {
  3130. if (this.cancelled) {
  3131. return;
  3132. }
  3133. if (this._canvas) {
  3134. if (canvasInRendering.has(this._canvas)) {
  3135. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  3136. }
  3137. canvasInRendering.add(this._canvas);
  3138. }
  3139. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  3140. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  3141. this.stepper.init(this.operatorList);
  3142. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  3143. }
  3144. const {
  3145. canvasContext,
  3146. viewport,
  3147. transform,
  3148. imageLayer,
  3149. background
  3150. } = this.params;
  3151. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig);
  3152. this.gfx.beginDrawing({
  3153. transform,
  3154. viewport,
  3155. transparency,
  3156. background
  3157. });
  3158. this.operatorListIdx = 0;
  3159. this.graphicsReady = true;
  3160. if (this.graphicsReadyCallback) {
  3161. this.graphicsReadyCallback();
  3162. }
  3163. }
  3164. cancel(error = null) {
  3165. this.running = false;
  3166. this.cancelled = true;
  3167. if (this.gfx) {
  3168. this.gfx.endDrawing();
  3169. }
  3170. if (this._canvas) {
  3171. canvasInRendering.delete(this._canvas);
  3172. }
  3173. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
  3174. }
  3175. operatorListChanged() {
  3176. if (!this.graphicsReady) {
  3177. if (!this.graphicsReadyCallback) {
  3178. this.graphicsReadyCallback = this._continueBound;
  3179. }
  3180. return;
  3181. }
  3182. if (this.stepper) {
  3183. this.stepper.updateOperatorList(this.operatorList);
  3184. }
  3185. if (this.running) {
  3186. return;
  3187. }
  3188. this._continue();
  3189. }
  3190. _continue() {
  3191. this.running = true;
  3192. if (this.cancelled) {
  3193. return;
  3194. }
  3195. if (this.task.onContinue) {
  3196. this.task.onContinue(this._scheduleNextBound);
  3197. } else {
  3198. this._scheduleNext();
  3199. }
  3200. }
  3201. _scheduleNext() {
  3202. if (this._useRequestAnimationFrame) {
  3203. window.requestAnimationFrame(() => {
  3204. this._nextBound().catch(this._cancelBound);
  3205. });
  3206. } else {
  3207. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  3208. }
  3209. }
  3210. async _next() {
  3211. if (this.cancelled) {
  3212. return;
  3213. }
  3214. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  3215. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  3216. this.running = false;
  3217. if (this.operatorList.lastChunk) {
  3218. this.gfx.endDrawing();
  3219. if (this._canvas) {
  3220. canvasInRendering.delete(this._canvas);
  3221. }
  3222. this.callback();
  3223. }
  3224. }
  3225. }
  3226. }
  3227. return InternalRenderTask;
  3228. }();
  3229. const version = '2.10.377';
  3230. exports.version = version;
  3231. const build = '156762c48';
  3232. exports.build = build;
  3233. /***/ }),
  3234. /* 7 */
  3235. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3236. Object.defineProperty(exports, "__esModule", ({
  3237. value: true
  3238. }));
  3239. exports.FontLoader = exports.FontFaceObject = void 0;
  3240. var _util = __w_pdfjs_require__(2);
  3241. class BaseFontLoader {
  3242. constructor({
  3243. docId,
  3244. onUnsupportedFeature,
  3245. ownerDocument = globalThis.document,
  3246. styleElement = null
  3247. }) {
  3248. if (this.constructor === BaseFontLoader) {
  3249. (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
  3250. }
  3251. this.docId = docId;
  3252. this._onUnsupportedFeature = onUnsupportedFeature;
  3253. this._document = ownerDocument;
  3254. this.nativeFontFaces = [];
  3255. this.styleElement = null;
  3256. }
  3257. addNativeFontFace(nativeFontFace) {
  3258. this.nativeFontFaces.push(nativeFontFace);
  3259. this._document.fonts.add(nativeFontFace);
  3260. }
  3261. insertRule(rule) {
  3262. let styleElement = this.styleElement;
  3263. if (!styleElement) {
  3264. styleElement = this.styleElement = this._document.createElement("style");
  3265. styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
  3266. this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
  3267. }
  3268. const styleSheet = styleElement.sheet;
  3269. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  3270. }
  3271. clear() {
  3272. for (const nativeFontFace of this.nativeFontFaces) {
  3273. this._document.fonts.delete(nativeFontFace);
  3274. }
  3275. this.nativeFontFaces.length = 0;
  3276. if (this.styleElement) {
  3277. this.styleElement.remove();
  3278. this.styleElement = null;
  3279. }
  3280. }
  3281. async bind(font) {
  3282. if (font.attached || font.missingFile) {
  3283. return;
  3284. }
  3285. font.attached = true;
  3286. if (this.isFontLoadingAPISupported) {
  3287. const nativeFontFace = font.createNativeFontFace();
  3288. if (nativeFontFace) {
  3289. this.addNativeFontFace(nativeFontFace);
  3290. try {
  3291. await nativeFontFace.loaded;
  3292. } catch (ex) {
  3293. this._onUnsupportedFeature({
  3294. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  3295. });
  3296. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  3297. font.disableFontFace = true;
  3298. throw ex;
  3299. }
  3300. }
  3301. return;
  3302. }
  3303. const rule = font.createFontFaceRule();
  3304. if (rule) {
  3305. this.insertRule(rule);
  3306. if (this.isSyncFontLoadingSupported) {
  3307. return;
  3308. }
  3309. await new Promise(resolve => {
  3310. const request = this._queueLoadingCallback(resolve);
  3311. this._prepareFontLoadEvent([rule], [font], request);
  3312. });
  3313. }
  3314. }
  3315. _queueLoadingCallback(callback) {
  3316. (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
  3317. }
  3318. get isFontLoadingAPISupported() {
  3319. const hasFonts = !!this._document?.fonts;
  3320. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  3321. }
  3322. get isSyncFontLoadingSupported() {
  3323. (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
  3324. }
  3325. get _loadTestFont() {
  3326. (0, _util.unreachable)("Abstract method `_loadTestFont`.");
  3327. }
  3328. _prepareFontLoadEvent(rules, fontsToLoad, request) {
  3329. (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
  3330. }
  3331. }
  3332. let FontLoader;
  3333. exports.FontLoader = FontLoader;
  3334. {
  3335. exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
  3336. constructor(params) {
  3337. super(params);
  3338. this.loadingContext = {
  3339. requests: [],
  3340. nextRequestId: 0
  3341. };
  3342. this.loadTestFontId = 0;
  3343. }
  3344. get isSyncFontLoadingSupported() {
  3345. let supported = false;
  3346. if (typeof navigator === "undefined") {
  3347. supported = true;
  3348. } else {
  3349. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  3350. if (m?.[1] >= 14) {
  3351. supported = true;
  3352. }
  3353. }
  3354. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  3355. }
  3356. _queueLoadingCallback(callback) {
  3357. function completeRequest() {
  3358. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  3359. request.done = true;
  3360. while (context.requests.length > 0 && context.requests[0].done) {
  3361. const otherRequest = context.requests.shift();
  3362. setTimeout(otherRequest.callback, 0);
  3363. }
  3364. }
  3365. const context = this.loadingContext;
  3366. const request = {
  3367. id: `pdfjs-font-loading-${context.nextRequestId++}`,
  3368. done: false,
  3369. complete: completeRequest,
  3370. callback
  3371. };
  3372. context.requests.push(request);
  3373. return request;
  3374. }
  3375. get _loadTestFont() {
  3376. const getLoadTestFont = function () {
  3377. 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==");
  3378. };
  3379. return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
  3380. }
  3381. _prepareFontLoadEvent(rules, fonts, request) {
  3382. function int32(data, offset) {
  3383. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  3384. }
  3385. function spliceString(s, offset, remove, insert) {
  3386. const chunk1 = s.substring(0, offset);
  3387. const chunk2 = s.substring(offset + remove);
  3388. return chunk1 + insert + chunk2;
  3389. }
  3390. let i, ii;
  3391. const canvas = this._document.createElement("canvas");
  3392. canvas.width = 1;
  3393. canvas.height = 1;
  3394. const ctx = canvas.getContext("2d");
  3395. let called = 0;
  3396. function isFontReady(name, callback) {
  3397. called++;
  3398. if (called > 30) {
  3399. (0, _util.warn)("Load test font never loaded.");
  3400. callback();
  3401. return;
  3402. }
  3403. ctx.font = "30px " + name;
  3404. ctx.fillText(".", 0, 20);
  3405. const imageData = ctx.getImageData(0, 0, 1, 1);
  3406. if (imageData.data[3] > 0) {
  3407. callback();
  3408. return;
  3409. }
  3410. setTimeout(isFontReady.bind(null, name, callback));
  3411. }
  3412. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  3413. let data = this._loadTestFont;
  3414. const COMMENT_OFFSET = 976;
  3415. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  3416. const CFF_CHECKSUM_OFFSET = 16;
  3417. const XXXX_VALUE = 0x58585858;
  3418. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  3419. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  3420. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  3421. }
  3422. if (i < loadTestFontId.length) {
  3423. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  3424. }
  3425. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  3426. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  3427. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  3428. this.insertRule(rule);
  3429. const names = [];
  3430. for (const font of fonts) {
  3431. names.push(font.loadedName);
  3432. }
  3433. names.push(loadTestFontId);
  3434. const div = this._document.createElement("div");
  3435. div.style.visibility = "hidden";
  3436. div.style.width = div.style.height = "10px";
  3437. div.style.position = "absolute";
  3438. div.style.top = div.style.left = "0px";
  3439. for (const name of names) {
  3440. const span = this._document.createElement("span");
  3441. span.textContent = "Hi";
  3442. span.style.fontFamily = name;
  3443. div.appendChild(span);
  3444. }
  3445. this._document.body.appendChild(div);
  3446. isFontReady(loadTestFontId, () => {
  3447. this._document.body.removeChild(div);
  3448. request.complete();
  3449. });
  3450. }
  3451. };
  3452. }
  3453. class FontFaceObject {
  3454. constructor(translatedData, {
  3455. isEvalSupported = true,
  3456. disableFontFace = false,
  3457. ignoreErrors = false,
  3458. onUnsupportedFeature,
  3459. fontRegistry = null
  3460. }) {
  3461. this.compiledGlyphs = Object.create(null);
  3462. for (const i in translatedData) {
  3463. this[i] = translatedData[i];
  3464. }
  3465. this.isEvalSupported = isEvalSupported !== false;
  3466. this.disableFontFace = disableFontFace === true;
  3467. this.ignoreErrors = ignoreErrors === true;
  3468. this._onUnsupportedFeature = onUnsupportedFeature;
  3469. this.fontRegistry = fontRegistry;
  3470. }
  3471. createNativeFontFace() {
  3472. if (!this.data || this.disableFontFace) {
  3473. return null;
  3474. }
  3475. let nativeFontFace;
  3476. if (!this.cssFontInfo) {
  3477. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  3478. } else {
  3479. const css = {
  3480. weight: this.cssFontInfo.fontWeight
  3481. };
  3482. if (this.cssFontInfo.italicAngle) {
  3483. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  3484. }
  3485. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  3486. }
  3487. if (this.fontRegistry) {
  3488. this.fontRegistry.registerFont(this);
  3489. }
  3490. return nativeFontFace;
  3491. }
  3492. createFontFaceRule() {
  3493. if (!this.data || this.disableFontFace) {
  3494. return null;
  3495. }
  3496. const data = (0, _util.bytesToString)(this.data);
  3497. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  3498. let rule;
  3499. if (!this.cssFontInfo) {
  3500. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  3501. } else {
  3502. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  3503. if (this.cssFontInfo.italicAngle) {
  3504. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  3505. }
  3506. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  3507. }
  3508. if (this.fontRegistry) {
  3509. this.fontRegistry.registerFont(this, url);
  3510. }
  3511. return rule;
  3512. }
  3513. getPathGenerator(objs, character) {
  3514. if (this.compiledGlyphs[character] !== undefined) {
  3515. return this.compiledGlyphs[character];
  3516. }
  3517. let cmds;
  3518. try {
  3519. cmds = objs.get(this.loadedName + "_path_" + character);
  3520. } catch (ex) {
  3521. if (!this.ignoreErrors) {
  3522. throw ex;
  3523. }
  3524. this._onUnsupportedFeature({
  3525. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  3526. });
  3527. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  3528. return this.compiledGlyphs[character] = function (c, size) {};
  3529. }
  3530. if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
  3531. const jsBuf = [];
  3532. for (const current of cmds) {
  3533. const args = current.args !== undefined ? current.args.join(",") : "";
  3534. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  3535. }
  3536. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  3537. }
  3538. return this.compiledGlyphs[character] = function (c, size) {
  3539. for (const current of cmds) {
  3540. if (current.cmd === "scale") {
  3541. current.args = [size, -size];
  3542. }
  3543. c[current.cmd].apply(c, current.args);
  3544. }
  3545. };
  3546. }
  3547. }
  3548. exports.FontFaceObject = FontFaceObject;
  3549. /***/ }),
  3550. /* 8 */
  3551. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3552. Object.defineProperty(exports, "__esModule", ({
  3553. value: true
  3554. }));
  3555. exports.NodeStandardFontDataFactory = exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = void 0;
  3556. var _base_factory = __w_pdfjs_require__(5);
  3557. var _is_node = __w_pdfjs_require__(4);
  3558. var _util = __w_pdfjs_require__(2);
  3559. let NodeCanvasFactory = class {
  3560. constructor() {
  3561. (0, _util.unreachable)("Not implemented: NodeCanvasFactory");
  3562. }
  3563. };
  3564. exports.NodeCanvasFactory = NodeCanvasFactory;
  3565. let NodeCMapReaderFactory = class {
  3566. constructor() {
  3567. (0, _util.unreachable)("Not implemented: NodeCMapReaderFactory");
  3568. }
  3569. };
  3570. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  3571. let NodeStandardFontDataFactory = class {
  3572. constructor() {
  3573. (0, _util.unreachable)("Not implemented: NodeStandardFontDataFactory");
  3574. }
  3575. };
  3576. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  3577. if (_is_node.isNodeJS) {
  3578. const fetchData = function (url) {
  3579. return new Promise((resolve, reject) => {
  3580. const fs = require("fs");
  3581. fs.readFile(url, (error, data) => {
  3582. if (error || !data) {
  3583. reject(new Error(error));
  3584. return;
  3585. }
  3586. resolve(new Uint8Array(data));
  3587. });
  3588. });
  3589. };
  3590. exports.NodeCanvasFactory = NodeCanvasFactory = class extends _base_factory.BaseCanvasFactory {
  3591. _createCanvas(width, height) {
  3592. const Canvas = require("canvas");
  3593. return Canvas.createCanvas(width, height);
  3594. }
  3595. };
  3596. exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _base_factory.BaseCMapReaderFactory {
  3597. _fetchData(url, compressionType) {
  3598. return fetchData(url).then(data => {
  3599. return {
  3600. cMapData: data,
  3601. compressionType
  3602. };
  3603. });
  3604. }
  3605. };
  3606. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory = class extends _base_factory.BaseStandardFontDataFactory {
  3607. _fetchData(url) {
  3608. return fetchData(url);
  3609. }
  3610. };
  3611. }
  3612. /***/ }),
  3613. /* 9 */
  3614. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3615. Object.defineProperty(exports, "__esModule", ({
  3616. value: true
  3617. }));
  3618. exports.AnnotationStorage = void 0;
  3619. var _util = __w_pdfjs_require__(2);
  3620. class AnnotationStorage {
  3621. constructor() {
  3622. this._storage = new Map();
  3623. this._modified = false;
  3624. this.onSetModified = null;
  3625. this.onResetModified = null;
  3626. }
  3627. getValue(key, defaultValue) {
  3628. const obj = this._storage.get(key);
  3629. return obj !== undefined ? obj : defaultValue;
  3630. }
  3631. setValue(key, value) {
  3632. const obj = this._storage.get(key);
  3633. let modified = false;
  3634. if (obj !== undefined) {
  3635. for (const [entry, val] of Object.entries(value)) {
  3636. if (obj[entry] !== val) {
  3637. modified = true;
  3638. obj[entry] = val;
  3639. }
  3640. }
  3641. } else {
  3642. this._storage.set(key, value);
  3643. modified = true;
  3644. }
  3645. if (modified) {
  3646. this._setModified();
  3647. }
  3648. }
  3649. getAll() {
  3650. return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
  3651. }
  3652. get size() {
  3653. return this._storage.size;
  3654. }
  3655. _setModified() {
  3656. if (!this._modified) {
  3657. this._modified = true;
  3658. if (typeof this.onSetModified === "function") {
  3659. this.onSetModified();
  3660. }
  3661. }
  3662. }
  3663. resetModified() {
  3664. if (this._modified) {
  3665. this._modified = false;
  3666. if (typeof this.onResetModified === "function") {
  3667. this.onResetModified();
  3668. }
  3669. }
  3670. }
  3671. get serializable() {
  3672. return this._storage.size > 0 ? this._storage : null;
  3673. }
  3674. }
  3675. exports.AnnotationStorage = AnnotationStorage;
  3676. /***/ }),
  3677. /* 10 */
  3678. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3679. Object.defineProperty(exports, "__esModule", ({
  3680. value: true
  3681. }));
  3682. exports.CanvasGraphics = void 0;
  3683. var _util = __w_pdfjs_require__(2);
  3684. var _pattern_helper = __w_pdfjs_require__(11);
  3685. const MIN_FONT_SIZE = 16;
  3686. const MAX_FONT_SIZE = 100;
  3687. const MAX_GROUP_SIZE = 4096;
  3688. const COMPILE_TYPE3_GLYPHS = true;
  3689. const MAX_SIZE_TO_COMPILE = 1000;
  3690. const FULL_CHUNK_HEIGHT = 16;
  3691. const LINEWIDTH_SCALE_FACTOR = 1.000001;
  3692. function addContextCurrentTransform(ctx) {
  3693. if (ctx.mozCurrentTransform) {
  3694. return;
  3695. }
  3696. ctx._originalSave = ctx.save;
  3697. ctx._originalRestore = ctx.restore;
  3698. ctx._originalRotate = ctx.rotate;
  3699. ctx._originalScale = ctx.scale;
  3700. ctx._originalTranslate = ctx.translate;
  3701. ctx._originalTransform = ctx.transform;
  3702. ctx._originalSetTransform = ctx.setTransform;
  3703. ctx._originalResetTransform = ctx.resetTransform;
  3704. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  3705. ctx._transformStack = [];
  3706. try {
  3707. const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth");
  3708. ctx._setLineWidth = desc.set;
  3709. ctx._getLineWidth = desc.get;
  3710. Object.defineProperty(ctx, "lineWidth", {
  3711. set: function setLineWidth(width) {
  3712. this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR);
  3713. },
  3714. get: function getLineWidth() {
  3715. return this._getLineWidth();
  3716. }
  3717. });
  3718. } catch (_) {}
  3719. Object.defineProperty(ctx, "mozCurrentTransform", {
  3720. get: function getCurrentTransform() {
  3721. return this._transformMatrix;
  3722. }
  3723. });
  3724. Object.defineProperty(ctx, "mozCurrentTransformInverse", {
  3725. get: function getCurrentTransformInverse() {
  3726. const [a, b, c, d, e, f] = this._transformMatrix;
  3727. const ad_bc = a * d - b * c;
  3728. const bc_ad = b * c - a * d;
  3729. 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];
  3730. }
  3731. });
  3732. ctx.save = function ctxSave() {
  3733. const old = this._transformMatrix;
  3734. this._transformStack.push(old);
  3735. this._transformMatrix = old.slice(0, 6);
  3736. this._originalSave();
  3737. };
  3738. ctx.restore = function ctxRestore() {
  3739. const prev = this._transformStack.pop();
  3740. if (prev) {
  3741. this._transformMatrix = prev;
  3742. this._originalRestore();
  3743. }
  3744. };
  3745. ctx.translate = function ctxTranslate(x, y) {
  3746. const m = this._transformMatrix;
  3747. m[4] = m[0] * x + m[2] * y + m[4];
  3748. m[5] = m[1] * x + m[3] * y + m[5];
  3749. this._originalTranslate(x, y);
  3750. };
  3751. ctx.scale = function ctxScale(x, y) {
  3752. const m = this._transformMatrix;
  3753. m[0] *= x;
  3754. m[1] *= x;
  3755. m[2] *= y;
  3756. m[3] *= y;
  3757. this._originalScale(x, y);
  3758. };
  3759. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3760. const m = this._transformMatrix;
  3761. 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]];
  3762. ctx._originalTransform(a, b, c, d, e, f);
  3763. };
  3764. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3765. this._transformMatrix = [a, b, c, d, e, f];
  3766. ctx._originalSetTransform(a, b, c, d, e, f);
  3767. };
  3768. ctx.resetTransform = function ctxResetTransform() {
  3769. this._transformMatrix = [1, 0, 0, 1, 0, 0];
  3770. ctx._originalResetTransform();
  3771. };
  3772. ctx.rotate = function ctxRotate(angle) {
  3773. const cosValue = Math.cos(angle);
  3774. const sinValue = Math.sin(angle);
  3775. const m = this._transformMatrix;
  3776. 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]];
  3777. this._originalRotate(angle);
  3778. };
  3779. }
  3780. class CachedCanvases {
  3781. constructor(canvasFactory) {
  3782. this.canvasFactory = canvasFactory;
  3783. this.cache = Object.create(null);
  3784. }
  3785. getCanvas(id, width, height, trackTransform) {
  3786. let canvasEntry;
  3787. if (this.cache[id] !== undefined) {
  3788. canvasEntry = this.cache[id];
  3789. this.canvasFactory.reset(canvasEntry, width, height);
  3790. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3791. } else {
  3792. canvasEntry = this.canvasFactory.create(width, height);
  3793. this.cache[id] = canvasEntry;
  3794. }
  3795. if (trackTransform) {
  3796. addContextCurrentTransform(canvasEntry.context);
  3797. }
  3798. return canvasEntry;
  3799. }
  3800. clear() {
  3801. for (const id in this.cache) {
  3802. const canvasEntry = this.cache[id];
  3803. this.canvasFactory.destroy(canvasEntry);
  3804. delete this.cache[id];
  3805. }
  3806. }
  3807. }
  3808. function compileType3Glyph(imgData) {
  3809. const POINT_TO_PROCESS_LIMIT = 1000;
  3810. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3811. const width = imgData.width,
  3812. height = imgData.height,
  3813. width1 = width + 1;
  3814. let i, ii, j, j0;
  3815. const points = new Uint8Array(width1 * (height + 1));
  3816. const lineSize = width + 7 & ~7,
  3817. data0 = imgData.data;
  3818. const data = new Uint8Array(lineSize * height);
  3819. let pos = 0;
  3820. for (i = 0, ii = data0.length; i < ii; i++) {
  3821. const elem = data0[i];
  3822. let mask = 128;
  3823. while (mask > 0) {
  3824. data[pos++] = elem & mask ? 0 : 255;
  3825. mask >>= 1;
  3826. }
  3827. }
  3828. let count = 0;
  3829. pos = 0;
  3830. if (data[pos] !== 0) {
  3831. points[0] = 1;
  3832. ++count;
  3833. }
  3834. for (j = 1; j < width; j++) {
  3835. if (data[pos] !== data[pos + 1]) {
  3836. points[j] = data[pos] ? 2 : 1;
  3837. ++count;
  3838. }
  3839. pos++;
  3840. }
  3841. if (data[pos] !== 0) {
  3842. points[j] = 2;
  3843. ++count;
  3844. }
  3845. for (i = 1; i < height; i++) {
  3846. pos = i * lineSize;
  3847. j0 = i * width1;
  3848. if (data[pos - lineSize] !== data[pos]) {
  3849. points[j0] = data[pos] ? 1 : 8;
  3850. ++count;
  3851. }
  3852. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3853. for (j = 1; j < width; j++) {
  3854. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  3855. if (POINT_TYPES[sum]) {
  3856. points[j0 + j] = POINT_TYPES[sum];
  3857. ++count;
  3858. }
  3859. pos++;
  3860. }
  3861. if (data[pos - lineSize] !== data[pos]) {
  3862. points[j0 + j] = data[pos] ? 2 : 4;
  3863. ++count;
  3864. }
  3865. if (count > POINT_TO_PROCESS_LIMIT) {
  3866. return null;
  3867. }
  3868. }
  3869. pos = lineSize * (height - 1);
  3870. j0 = i * width1;
  3871. if (data[pos] !== 0) {
  3872. points[j0] = 8;
  3873. ++count;
  3874. }
  3875. for (j = 1; j < width; j++) {
  3876. if (data[pos] !== data[pos + 1]) {
  3877. points[j0 + j] = data[pos] ? 4 : 8;
  3878. ++count;
  3879. }
  3880. pos++;
  3881. }
  3882. if (data[pos] !== 0) {
  3883. points[j0 + j] = 4;
  3884. ++count;
  3885. }
  3886. if (count > POINT_TO_PROCESS_LIMIT) {
  3887. return null;
  3888. }
  3889. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3890. const outlines = [];
  3891. for (i = 0; count && i <= height; i++) {
  3892. let p = i * width1;
  3893. const end = p + width;
  3894. while (p < end && !points[p]) {
  3895. p++;
  3896. }
  3897. if (p === end) {
  3898. continue;
  3899. }
  3900. const coords = [p % width1, i];
  3901. const p0 = p;
  3902. let type = points[p];
  3903. do {
  3904. const step = steps[type];
  3905. do {
  3906. p += step;
  3907. } while (!points[p]);
  3908. const pp = points[p];
  3909. if (pp !== 5 && pp !== 10) {
  3910. type = pp;
  3911. points[p] = 0;
  3912. } else {
  3913. type = pp & 0x33 * type >> 4;
  3914. points[p] &= type >> 2 | type << 2;
  3915. }
  3916. coords.push(p % width1, p / width1 | 0);
  3917. if (!points[p]) {
  3918. --count;
  3919. }
  3920. } while (p0 !== p);
  3921. outlines.push(coords);
  3922. --i;
  3923. }
  3924. const drawOutline = function (c) {
  3925. c.save();
  3926. c.scale(1 / width, -1 / height);
  3927. c.translate(0, -height);
  3928. c.beginPath();
  3929. for (let k = 0, kk = outlines.length; k < kk; k++) {
  3930. const o = outlines[k];
  3931. c.moveTo(o[0], o[1]);
  3932. for (let l = 2, ll = o.length; l < ll; l += 2) {
  3933. c.lineTo(o[l], o[l + 1]);
  3934. }
  3935. }
  3936. c.fill();
  3937. c.beginPath();
  3938. c.restore();
  3939. };
  3940. return drawOutline;
  3941. }
  3942. class CanvasExtraState {
  3943. constructor() {
  3944. this.alphaIsShape = false;
  3945. this.fontSize = 0;
  3946. this.fontSizeScale = 1;
  3947. this.textMatrix = _util.IDENTITY_MATRIX;
  3948. this.textMatrixScale = 1;
  3949. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  3950. this.leading = 0;
  3951. this.x = 0;
  3952. this.y = 0;
  3953. this.lineX = 0;
  3954. this.lineY = 0;
  3955. this.charSpacing = 0;
  3956. this.wordSpacing = 0;
  3957. this.textHScale = 1;
  3958. this.textRenderingMode = _util.TextRenderingMode.FILL;
  3959. this.textRise = 0;
  3960. this.fillColor = "#000000";
  3961. this.strokeColor = "#000000";
  3962. this.patternFill = false;
  3963. this.fillAlpha = 1;
  3964. this.strokeAlpha = 1;
  3965. this.lineWidth = 1;
  3966. this.activeSMask = null;
  3967. this.resumeSMaskCtx = null;
  3968. this.transferMaps = null;
  3969. }
  3970. clone() {
  3971. return Object.create(this);
  3972. }
  3973. setCurrentPoint(x, y) {
  3974. this.x = x;
  3975. this.y = y;
  3976. }
  3977. }
  3978. const CanvasGraphics = function CanvasGraphicsClosure() {
  3979. const EXECUTION_TIME = 15;
  3980. const EXECUTION_STEPS = 10;
  3981. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  3982. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  3983. ctx.putImageData(imgData, 0, 0);
  3984. return;
  3985. }
  3986. const height = imgData.height,
  3987. width = imgData.width;
  3988. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3989. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3990. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3991. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3992. let srcPos = 0,
  3993. destPos;
  3994. const src = imgData.data;
  3995. const dest = chunkImgData.data;
  3996. let i, j, thisChunkHeight, elemsInThisChunk;
  3997. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  3998. if (transferMaps) {
  3999. switch (transferMaps.length) {
  4000. case 1:
  4001. transferMapRed = transferMaps[0];
  4002. transferMapGreen = transferMaps[0];
  4003. transferMapBlue = transferMaps[0];
  4004. transferMapGray = transferMaps[0];
  4005. break;
  4006. case 4:
  4007. transferMapRed = transferMaps[0];
  4008. transferMapGreen = transferMaps[1];
  4009. transferMapBlue = transferMaps[2];
  4010. transferMapGray = transferMaps[3];
  4011. break;
  4012. }
  4013. }
  4014. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  4015. const srcLength = src.byteLength;
  4016. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  4017. const dest32DataLength = dest32.length;
  4018. const fullSrcDiff = width + 7 >> 3;
  4019. let white = 0xffffffff;
  4020. let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff;
  4021. if (transferMapGray) {
  4022. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  4023. [white, black] = [black, white];
  4024. }
  4025. }
  4026. for (i = 0; i < totalChunks; i++) {
  4027. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  4028. destPos = 0;
  4029. for (j = 0; j < thisChunkHeight; j++) {
  4030. const srcDiff = srcLength - srcPos;
  4031. let k = 0;
  4032. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  4033. const kEndUnrolled = kEnd & ~7;
  4034. let mask = 0;
  4035. let srcByte = 0;
  4036. for (; k < kEndUnrolled; k += 8) {
  4037. srcByte = src[srcPos++];
  4038. dest32[destPos++] = srcByte & 128 ? white : black;
  4039. dest32[destPos++] = srcByte & 64 ? white : black;
  4040. dest32[destPos++] = srcByte & 32 ? white : black;
  4041. dest32[destPos++] = srcByte & 16 ? white : black;
  4042. dest32[destPos++] = srcByte & 8 ? white : black;
  4043. dest32[destPos++] = srcByte & 4 ? white : black;
  4044. dest32[destPos++] = srcByte & 2 ? white : black;
  4045. dest32[destPos++] = srcByte & 1 ? white : black;
  4046. }
  4047. for (; k < kEnd; k++) {
  4048. if (mask === 0) {
  4049. srcByte = src[srcPos++];
  4050. mask = 128;
  4051. }
  4052. dest32[destPos++] = srcByte & mask ? white : black;
  4053. mask >>= 1;
  4054. }
  4055. }
  4056. while (destPos < dest32DataLength) {
  4057. dest32[destPos++] = 0;
  4058. }
  4059. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4060. }
  4061. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  4062. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  4063. j = 0;
  4064. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  4065. for (i = 0; i < fullChunks; i++) {
  4066. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  4067. srcPos += elemsInThisChunk;
  4068. if (hasTransferMaps) {
  4069. for (let k = 0; k < elemsInThisChunk; k += 4) {
  4070. if (transferMapRed) {
  4071. dest[k + 0] = transferMapRed[dest[k + 0]];
  4072. }
  4073. if (transferMapGreen) {
  4074. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4075. }
  4076. if (transferMapBlue) {
  4077. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4078. }
  4079. }
  4080. }
  4081. ctx.putImageData(chunkImgData, 0, j);
  4082. j += FULL_CHUNK_HEIGHT;
  4083. }
  4084. if (i < totalChunks) {
  4085. elemsInThisChunk = width * partialChunkHeight * 4;
  4086. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  4087. if (hasTransferMaps) {
  4088. for (let k = 0; k < elemsInThisChunk; k += 4) {
  4089. if (transferMapRed) {
  4090. dest[k + 0] = transferMapRed[dest[k + 0]];
  4091. }
  4092. if (transferMapGreen) {
  4093. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4094. }
  4095. if (transferMapBlue) {
  4096. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4097. }
  4098. }
  4099. }
  4100. ctx.putImageData(chunkImgData, 0, j);
  4101. }
  4102. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  4103. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  4104. thisChunkHeight = FULL_CHUNK_HEIGHT;
  4105. elemsInThisChunk = width * thisChunkHeight;
  4106. for (i = 0; i < totalChunks; i++) {
  4107. if (i >= fullChunks) {
  4108. thisChunkHeight = partialChunkHeight;
  4109. elemsInThisChunk = width * thisChunkHeight;
  4110. }
  4111. destPos = 0;
  4112. for (j = elemsInThisChunk; j--;) {
  4113. dest[destPos++] = src[srcPos++];
  4114. dest[destPos++] = src[srcPos++];
  4115. dest[destPos++] = src[srcPos++];
  4116. dest[destPos++] = 255;
  4117. }
  4118. if (hasTransferMaps) {
  4119. for (let k = 0; k < destPos; k += 4) {
  4120. if (transferMapRed) {
  4121. dest[k + 0] = transferMapRed[dest[k + 0]];
  4122. }
  4123. if (transferMapGreen) {
  4124. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4125. }
  4126. if (transferMapBlue) {
  4127. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4128. }
  4129. }
  4130. }
  4131. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4132. }
  4133. } else {
  4134. throw new Error(`bad image kind: ${imgData.kind}`);
  4135. }
  4136. }
  4137. function putBinaryImageMask(ctx, imgData) {
  4138. const height = imgData.height,
  4139. width = imgData.width;
  4140. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  4141. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  4142. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  4143. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  4144. let srcPos = 0;
  4145. const src = imgData.data;
  4146. const dest = chunkImgData.data;
  4147. for (let i = 0; i < totalChunks; i++) {
  4148. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  4149. let destPos = 3;
  4150. for (let j = 0; j < thisChunkHeight; j++) {
  4151. let elem,
  4152. mask = 0;
  4153. for (let k = 0; k < width; k++) {
  4154. if (!mask) {
  4155. elem = src[srcPos++];
  4156. mask = 128;
  4157. }
  4158. dest[destPos] = elem & mask ? 0 : 255;
  4159. destPos += 4;
  4160. mask >>= 1;
  4161. }
  4162. }
  4163. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4164. }
  4165. }
  4166. function copyCtxState(sourceCtx, destCtx) {
  4167. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  4168. for (let i = 0, ii = properties.length; i < ii; i++) {
  4169. const property = properties[i];
  4170. if (sourceCtx[property] !== undefined) {
  4171. destCtx[property] = sourceCtx[property];
  4172. }
  4173. }
  4174. if (sourceCtx.setLineDash !== undefined) {
  4175. destCtx.setLineDash(sourceCtx.getLineDash());
  4176. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  4177. }
  4178. }
  4179. function resetCtxToDefault(ctx) {
  4180. ctx.strokeStyle = "#000000";
  4181. ctx.fillStyle = "#000000";
  4182. ctx.fillRule = "nonzero";
  4183. ctx.globalAlpha = 1;
  4184. ctx.lineWidth = 1;
  4185. ctx.lineCap = "butt";
  4186. ctx.lineJoin = "miter";
  4187. ctx.miterLimit = 10;
  4188. ctx.globalCompositeOperation = "source-over";
  4189. ctx.font = "10px sans-serif";
  4190. if (ctx.setLineDash !== undefined) {
  4191. ctx.setLineDash([]);
  4192. ctx.lineDashOffset = 0;
  4193. }
  4194. }
  4195. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  4196. const length = bytes.length;
  4197. for (let i = 3; i < length; i += 4) {
  4198. const alpha = bytes[i];
  4199. if (alpha === 0) {
  4200. bytes[i - 3] = r0;
  4201. bytes[i - 2] = g0;
  4202. bytes[i - 1] = b0;
  4203. } else if (alpha < 255) {
  4204. const alpha_ = 255 - alpha;
  4205. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  4206. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  4207. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  4208. }
  4209. }
  4210. }
  4211. function composeSMaskAlpha(maskData, layerData, transferMap) {
  4212. const length = maskData.length;
  4213. const scale = 1 / 255;
  4214. for (let i = 3; i < length; i += 4) {
  4215. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  4216. layerData[i] = layerData[i] * alpha * scale | 0;
  4217. }
  4218. }
  4219. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  4220. const length = maskData.length;
  4221. for (let i = 3; i < length; i += 4) {
  4222. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  4223. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  4224. }
  4225. }
  4226. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  4227. const hasBackdrop = !!backdrop;
  4228. const r0 = hasBackdrop ? backdrop[0] : 0;
  4229. const g0 = hasBackdrop ? backdrop[1] : 0;
  4230. const b0 = hasBackdrop ? backdrop[2] : 0;
  4231. let composeFn;
  4232. if (subtype === "Luminosity") {
  4233. composeFn = composeSMaskLuminosity;
  4234. } else {
  4235. composeFn = composeSMaskAlpha;
  4236. }
  4237. const PIXELS_TO_PROCESS = 1048576;
  4238. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  4239. for (let row = 0; row < height; row += chunkSize) {
  4240. const chunkHeight = Math.min(chunkSize, height - row);
  4241. const maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  4242. const layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  4243. if (hasBackdrop) {
  4244. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  4245. }
  4246. composeFn(maskData.data, layerData.data, transferMap);
  4247. maskCtx.putImageData(layerData, 0, row);
  4248. }
  4249. }
  4250. function composeSMask(ctx, smask, layerCtx) {
  4251. const mask = smask.canvas;
  4252. const maskCtx = smask.context;
  4253. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  4254. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, smask.backdrop, smask.transferMap);
  4255. ctx.drawImage(mask, 0, 0);
  4256. }
  4257. const LINE_CAP_STYLES = ["butt", "round", "square"];
  4258. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  4259. const NORMAL_CLIP = {};
  4260. const EO_CLIP = {};
  4261. class CanvasGraphics {
  4262. constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig) {
  4263. this.ctx = canvasCtx;
  4264. this.current = new CanvasExtraState();
  4265. this.stateStack = [];
  4266. this.pendingClip = null;
  4267. this.pendingEOFill = false;
  4268. this.res = null;
  4269. this.xobjs = null;
  4270. this.commonObjs = commonObjs;
  4271. this.objs = objs;
  4272. this.canvasFactory = canvasFactory;
  4273. this.imageLayer = imageLayer;
  4274. this.groupStack = [];
  4275. this.processingType3 = null;
  4276. this.baseTransform = null;
  4277. this.baseTransformStack = [];
  4278. this.groupLevel = 0;
  4279. this.smaskStack = [];
  4280. this.smaskCounter = 0;
  4281. this.tempSMask = null;
  4282. this.contentVisible = true;
  4283. this.markedContentStack = [];
  4284. this.optionalContentConfig = optionalContentConfig;
  4285. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  4286. this.cachedPatterns = new Map();
  4287. if (canvasCtx) {
  4288. addContextCurrentTransform(canvasCtx);
  4289. }
  4290. this._cachedGetSinglePixelWidth = null;
  4291. }
  4292. beginDrawing({
  4293. transform,
  4294. viewport,
  4295. transparency = false,
  4296. background = null
  4297. }) {
  4298. const width = this.ctx.canvas.width;
  4299. const height = this.ctx.canvas.height;
  4300. this.ctx.save();
  4301. this.ctx.fillStyle = background || "rgb(255, 255, 255)";
  4302. this.ctx.fillRect(0, 0, width, height);
  4303. this.ctx.restore();
  4304. if (transparency) {
  4305. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
  4306. this.compositeCtx = this.ctx;
  4307. this.transparentCanvas = transparentCanvas.canvas;
  4308. this.ctx = transparentCanvas.context;
  4309. this.ctx.save();
  4310. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  4311. }
  4312. this.ctx.save();
  4313. resetCtxToDefault(this.ctx);
  4314. if (transform) {
  4315. this.ctx.transform.apply(this.ctx, transform);
  4316. }
  4317. this.ctx.transform.apply(this.ctx, viewport.transform);
  4318. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  4319. this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]);
  4320. if (this.imageLayer) {
  4321. this.imageLayer.beginLayout();
  4322. }
  4323. }
  4324. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  4325. const argsArray = operatorList.argsArray;
  4326. const fnArray = operatorList.fnArray;
  4327. let i = executionStartIdx || 0;
  4328. const argsArrayLen = argsArray.length;
  4329. if (argsArrayLen === i) {
  4330. return i;
  4331. }
  4332. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  4333. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  4334. let steps = 0;
  4335. const commonObjs = this.commonObjs;
  4336. const objs = this.objs;
  4337. let fnId;
  4338. while (true) {
  4339. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  4340. stepper.breakIt(i, continueCallback);
  4341. return i;
  4342. }
  4343. fnId = fnArray[i];
  4344. if (fnId !== _util.OPS.dependency) {
  4345. this[fnId].apply(this, argsArray[i]);
  4346. } else {
  4347. for (const depObjId of argsArray[i]) {
  4348. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  4349. if (!objsPool.has(depObjId)) {
  4350. objsPool.get(depObjId, continueCallback);
  4351. return i;
  4352. }
  4353. }
  4354. }
  4355. i++;
  4356. if (i === argsArrayLen) {
  4357. return i;
  4358. }
  4359. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  4360. if (Date.now() > endTime) {
  4361. continueCallback();
  4362. return i;
  4363. }
  4364. steps = 0;
  4365. }
  4366. }
  4367. }
  4368. endDrawing() {
  4369. while (this.stateStack.length || this.current.activeSMask !== null) {
  4370. this.restore();
  4371. }
  4372. this.ctx.restore();
  4373. if (this.transparentCanvas) {
  4374. this.ctx = this.compositeCtx;
  4375. this.ctx.save();
  4376. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  4377. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  4378. this.ctx.restore();
  4379. this.transparentCanvas = null;
  4380. }
  4381. this.cachedCanvases.clear();
  4382. this.cachedPatterns.clear();
  4383. if (this.imageLayer) {
  4384. this.imageLayer.endLayout();
  4385. }
  4386. }
  4387. _scaleImage(img, inverseTransform) {
  4388. const width = img.width;
  4389. const height = img.height;
  4390. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  4391. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  4392. let paintWidth = width,
  4393. paintHeight = height;
  4394. let tmpCanvasId = "prescale1";
  4395. let tmpCanvas, tmpCtx;
  4396. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  4397. let newWidth = paintWidth,
  4398. newHeight = paintHeight;
  4399. if (widthScale > 2 && paintWidth > 1) {
  4400. newWidth = Math.ceil(paintWidth / 2);
  4401. widthScale /= paintWidth / newWidth;
  4402. }
  4403. if (heightScale > 2 && paintHeight > 1) {
  4404. newHeight = Math.ceil(paintHeight / 2);
  4405. heightScale /= paintHeight / newHeight;
  4406. }
  4407. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4408. tmpCtx = tmpCanvas.context;
  4409. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4410. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  4411. img = tmpCanvas.canvas;
  4412. paintWidth = newWidth;
  4413. paintHeight = newHeight;
  4414. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  4415. }
  4416. return {
  4417. img,
  4418. paintWidth,
  4419. paintHeight
  4420. };
  4421. }
  4422. _createMaskCanvas(img) {
  4423. const ctx = this.ctx;
  4424. const width = img.width,
  4425. height = img.height;
  4426. const fillColor = this.current.fillColor;
  4427. const isPatternFill = this.current.patternFill;
  4428. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  4429. const maskCtx = maskCanvas.context;
  4430. putBinaryImageMask(maskCtx, img);
  4431. const objToCanvas = ctx.mozCurrentTransform;
  4432. let maskToCanvas = _util.Util.transform(objToCanvas, [1 / width, 0, 0, -1 / height, 0, 0]);
  4433. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  4434. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  4435. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  4436. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  4437. const drawnWidth = Math.ceil(rect[2] - rect[0]);
  4438. const drawnHeight = Math.ceil(rect[3] - rect[1]);
  4439. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight, true);
  4440. const fillCtx = fillCanvas.context;
  4441. const offsetX = Math.min(cord1[0], cord2[0]);
  4442. const offsetY = Math.min(cord1[1], cord2[1]);
  4443. fillCtx.translate(-offsetX, -offsetY);
  4444. fillCtx.transform.apply(fillCtx, maskToCanvas);
  4445. const scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse);
  4446. fillCtx.drawImage(scaled.img, 0, 0, scaled.img.width, scaled.img.height, 0, 0, width, height);
  4447. fillCtx.globalCompositeOperation = "source-in";
  4448. const inverse = _util.Util.transform(fillCtx.mozCurrentTransformInverse, [1, 0, 0, 1, -offsetX, -offsetY]);
  4449. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, false) : fillColor;
  4450. fillCtx.fillRect(0, 0, width, height);
  4451. return {
  4452. canvas: fillCanvas.canvas,
  4453. offsetX: Math.round(offsetX),
  4454. offsetY: Math.round(offsetY)
  4455. };
  4456. }
  4457. setLineWidth(width) {
  4458. this.current.lineWidth = width;
  4459. this.ctx.lineWidth = width;
  4460. }
  4461. setLineCap(style) {
  4462. this.ctx.lineCap = LINE_CAP_STYLES[style];
  4463. }
  4464. setLineJoin(style) {
  4465. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  4466. }
  4467. setMiterLimit(limit) {
  4468. this.ctx.miterLimit = limit;
  4469. }
  4470. setDash(dashArray, dashPhase) {
  4471. const ctx = this.ctx;
  4472. if (ctx.setLineDash !== undefined) {
  4473. ctx.setLineDash(dashArray);
  4474. ctx.lineDashOffset = dashPhase;
  4475. }
  4476. }
  4477. setRenderingIntent(intent) {}
  4478. setFlatness(flatness) {}
  4479. setGState(states) {
  4480. for (let i = 0, ii = states.length; i < ii; i++) {
  4481. const state = states[i];
  4482. const key = state[0];
  4483. const value = state[1];
  4484. switch (key) {
  4485. case "LW":
  4486. this.setLineWidth(value);
  4487. break;
  4488. case "LC":
  4489. this.setLineCap(value);
  4490. break;
  4491. case "LJ":
  4492. this.setLineJoin(value);
  4493. break;
  4494. case "ML":
  4495. this.setMiterLimit(value);
  4496. break;
  4497. case "D":
  4498. this.setDash(value[0], value[1]);
  4499. break;
  4500. case "RI":
  4501. this.setRenderingIntent(value);
  4502. break;
  4503. case "FL":
  4504. this.setFlatness(value);
  4505. break;
  4506. case "Font":
  4507. this.setFont(value[0], value[1]);
  4508. break;
  4509. case "CA":
  4510. this.current.strokeAlpha = state[1];
  4511. break;
  4512. case "ca":
  4513. this.current.fillAlpha = state[1];
  4514. this.ctx.globalAlpha = state[1];
  4515. break;
  4516. case "BM":
  4517. this.ctx.globalCompositeOperation = value;
  4518. break;
  4519. case "SMask":
  4520. if (this.current.activeSMask) {
  4521. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  4522. this.suspendSMaskGroup();
  4523. } else {
  4524. this.endSMaskGroup();
  4525. }
  4526. }
  4527. this.current.activeSMask = value ? this.tempSMask : null;
  4528. if (this.current.activeSMask) {
  4529. this.beginSMaskGroup();
  4530. }
  4531. this.tempSMask = null;
  4532. break;
  4533. case "TR":
  4534. this.current.transferMaps = value;
  4535. }
  4536. }
  4537. }
  4538. beginSMaskGroup() {
  4539. const activeSMask = this.current.activeSMask;
  4540. const drawnWidth = activeSMask.canvas.width;
  4541. const drawnHeight = activeSMask.canvas.height;
  4542. const cacheId = "smaskGroupAt" + this.groupLevel;
  4543. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  4544. const currentCtx = this.ctx;
  4545. const currentTransform = currentCtx.mozCurrentTransform;
  4546. this.ctx.save();
  4547. const groupCtx = scratchCanvas.context;
  4548. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  4549. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  4550. groupCtx.transform.apply(groupCtx, currentTransform);
  4551. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  4552. copyCtxState(currentCtx, groupCtx);
  4553. this.ctx = groupCtx;
  4554. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  4555. this.groupStack.push(currentCtx);
  4556. this.groupLevel++;
  4557. }
  4558. suspendSMaskGroup() {
  4559. const groupCtx = this.ctx;
  4560. this.groupLevel--;
  4561. this.ctx = this.groupStack.pop();
  4562. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4563. this.ctx.restore();
  4564. this.ctx.save();
  4565. copyCtxState(groupCtx, this.ctx);
  4566. this.current.resumeSMaskCtx = groupCtx;
  4567. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  4568. this.ctx.transform.apply(this.ctx, deltaTransform);
  4569. groupCtx.save();
  4570. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  4571. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  4572. groupCtx.restore();
  4573. }
  4574. resumeSMaskGroup() {
  4575. const groupCtx = this.current.resumeSMaskCtx;
  4576. const currentCtx = this.ctx;
  4577. this.ctx = groupCtx;
  4578. this.groupStack.push(currentCtx);
  4579. this.groupLevel++;
  4580. }
  4581. endSMaskGroup() {
  4582. const groupCtx = this.ctx;
  4583. this.groupLevel--;
  4584. this.ctx = this.groupStack.pop();
  4585. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4586. this.ctx.restore();
  4587. copyCtxState(groupCtx, this.ctx);
  4588. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  4589. this.ctx.transform.apply(this.ctx, deltaTransform);
  4590. }
  4591. save() {
  4592. this.ctx.save();
  4593. const old = this.current;
  4594. this.stateStack.push(old);
  4595. this.current = old.clone();
  4596. this.current.resumeSMaskCtx = null;
  4597. }
  4598. restore() {
  4599. if (this.current.resumeSMaskCtx) {
  4600. this.resumeSMaskGroup();
  4601. }
  4602. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  4603. this.endSMaskGroup();
  4604. }
  4605. if (this.stateStack.length !== 0) {
  4606. this.current = this.stateStack.pop();
  4607. this.ctx.restore();
  4608. this.pendingClip = null;
  4609. this._cachedGetSinglePixelWidth = null;
  4610. } else {
  4611. this.current.activeSMask = null;
  4612. }
  4613. }
  4614. transform(a, b, c, d, e, f) {
  4615. this.ctx.transform(a, b, c, d, e, f);
  4616. this._cachedGetSinglePixelWidth = null;
  4617. }
  4618. constructPath(ops, args) {
  4619. const ctx = this.ctx;
  4620. const current = this.current;
  4621. let x = current.x,
  4622. y = current.y;
  4623. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  4624. switch (ops[i] | 0) {
  4625. case _util.OPS.rectangle:
  4626. x = args[j++];
  4627. y = args[j++];
  4628. const width = args[j++];
  4629. const height = args[j++];
  4630. const xw = x + width;
  4631. const yh = y + height;
  4632. ctx.moveTo(x, y);
  4633. if (width === 0 || height === 0) {
  4634. ctx.lineTo(xw, yh);
  4635. } else {
  4636. ctx.lineTo(xw, y);
  4637. ctx.lineTo(xw, yh);
  4638. ctx.lineTo(x, yh);
  4639. }
  4640. ctx.closePath();
  4641. break;
  4642. case _util.OPS.moveTo:
  4643. x = args[j++];
  4644. y = args[j++];
  4645. ctx.moveTo(x, y);
  4646. break;
  4647. case _util.OPS.lineTo:
  4648. x = args[j++];
  4649. y = args[j++];
  4650. ctx.lineTo(x, y);
  4651. break;
  4652. case _util.OPS.curveTo:
  4653. x = args[j + 4];
  4654. y = args[j + 5];
  4655. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  4656. j += 6;
  4657. break;
  4658. case _util.OPS.curveTo2:
  4659. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  4660. x = args[j + 2];
  4661. y = args[j + 3];
  4662. j += 4;
  4663. break;
  4664. case _util.OPS.curveTo3:
  4665. x = args[j + 2];
  4666. y = args[j + 3];
  4667. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  4668. j += 4;
  4669. break;
  4670. case _util.OPS.closePath:
  4671. ctx.closePath();
  4672. break;
  4673. }
  4674. }
  4675. current.setCurrentPoint(x, y);
  4676. }
  4677. closePath() {
  4678. this.ctx.closePath();
  4679. }
  4680. stroke(consumePath) {
  4681. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  4682. const ctx = this.ctx;
  4683. const strokeColor = this.current.strokeColor;
  4684. ctx.globalAlpha = this.current.strokeAlpha;
  4685. if (this.contentVisible) {
  4686. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  4687. const lineWidth = this.getSinglePixelWidth();
  4688. ctx.save();
  4689. ctx.strokeStyle = strokeColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse);
  4690. ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
  4691. ctx.stroke();
  4692. ctx.restore();
  4693. } else {
  4694. const lineWidth = this.getSinglePixelWidth();
  4695. if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) {
  4696. ctx.save();
  4697. ctx.resetTransform();
  4698. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  4699. ctx.stroke();
  4700. ctx.restore();
  4701. } else {
  4702. ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
  4703. ctx.stroke();
  4704. }
  4705. }
  4706. }
  4707. if (consumePath) {
  4708. this.consumePath();
  4709. }
  4710. ctx.globalAlpha = this.current.fillAlpha;
  4711. }
  4712. closeStroke() {
  4713. this.closePath();
  4714. this.stroke();
  4715. }
  4716. fill(consumePath) {
  4717. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  4718. const ctx = this.ctx;
  4719. const fillColor = this.current.fillColor;
  4720. const isPatternFill = this.current.patternFill;
  4721. let needRestore = false;
  4722. if (isPatternFill) {
  4723. ctx.save();
  4724. ctx.fillStyle = fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse);
  4725. needRestore = true;
  4726. }
  4727. if (this.contentVisible) {
  4728. if (this.pendingEOFill) {
  4729. ctx.fill("evenodd");
  4730. this.pendingEOFill = false;
  4731. } else {
  4732. ctx.fill();
  4733. }
  4734. }
  4735. if (needRestore) {
  4736. ctx.restore();
  4737. }
  4738. if (consumePath) {
  4739. this.consumePath();
  4740. }
  4741. }
  4742. eoFill() {
  4743. this.pendingEOFill = true;
  4744. this.fill();
  4745. }
  4746. fillStroke() {
  4747. this.fill(false);
  4748. this.stroke(false);
  4749. this.consumePath();
  4750. }
  4751. eoFillStroke() {
  4752. this.pendingEOFill = true;
  4753. this.fillStroke();
  4754. }
  4755. closeFillStroke() {
  4756. this.closePath();
  4757. this.fillStroke();
  4758. }
  4759. closeEOFillStroke() {
  4760. this.pendingEOFill = true;
  4761. this.closePath();
  4762. this.fillStroke();
  4763. }
  4764. endPath() {
  4765. this.consumePath();
  4766. }
  4767. clip() {
  4768. this.pendingClip = NORMAL_CLIP;
  4769. }
  4770. eoClip() {
  4771. this.pendingClip = EO_CLIP;
  4772. }
  4773. beginText() {
  4774. this.current.textMatrix = _util.IDENTITY_MATRIX;
  4775. this.current.textMatrixScale = 1;
  4776. this.current.x = this.current.lineX = 0;
  4777. this.current.y = this.current.lineY = 0;
  4778. }
  4779. endText() {
  4780. const paths = this.pendingTextPaths;
  4781. const ctx = this.ctx;
  4782. if (paths === undefined) {
  4783. ctx.beginPath();
  4784. return;
  4785. }
  4786. ctx.save();
  4787. ctx.beginPath();
  4788. for (let i = 0; i < paths.length; i++) {
  4789. const path = paths[i];
  4790. ctx.setTransform.apply(ctx, path.transform);
  4791. ctx.translate(path.x, path.y);
  4792. path.addToPath(ctx, path.fontSize);
  4793. }
  4794. ctx.restore();
  4795. ctx.clip();
  4796. ctx.beginPath();
  4797. delete this.pendingTextPaths;
  4798. }
  4799. setCharSpacing(spacing) {
  4800. this.current.charSpacing = spacing;
  4801. }
  4802. setWordSpacing(spacing) {
  4803. this.current.wordSpacing = spacing;
  4804. }
  4805. setHScale(scale) {
  4806. this.current.textHScale = scale / 100;
  4807. }
  4808. setLeading(leading) {
  4809. this.current.leading = -leading;
  4810. }
  4811. setFont(fontRefName, size) {
  4812. const fontObj = this.commonObjs.get(fontRefName);
  4813. const current = this.current;
  4814. if (!fontObj) {
  4815. throw new Error(`Can't find font for ${fontRefName}`);
  4816. }
  4817. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  4818. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  4819. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  4820. }
  4821. if (size < 0) {
  4822. size = -size;
  4823. current.fontDirection = -1;
  4824. } else {
  4825. current.fontDirection = 1;
  4826. }
  4827. this.current.font = fontObj;
  4828. this.current.fontSize = size;
  4829. if (fontObj.isType3Font) {
  4830. return;
  4831. }
  4832. const name = fontObj.loadedName || "sans-serif";
  4833. let bold = "normal";
  4834. if (fontObj.black) {
  4835. bold = "900";
  4836. } else if (fontObj.bold) {
  4837. bold = "bold";
  4838. }
  4839. const italic = fontObj.italic ? "italic" : "normal";
  4840. const typeface = `"${name}", ${fontObj.fallbackName}`;
  4841. let browserFontSize = size;
  4842. if (size < MIN_FONT_SIZE) {
  4843. browserFontSize = MIN_FONT_SIZE;
  4844. } else if (size > MAX_FONT_SIZE) {
  4845. browserFontSize = MAX_FONT_SIZE;
  4846. }
  4847. this.current.fontSizeScale = size / browserFontSize;
  4848. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  4849. }
  4850. setTextRenderingMode(mode) {
  4851. this.current.textRenderingMode = mode;
  4852. }
  4853. setTextRise(rise) {
  4854. this.current.textRise = rise;
  4855. }
  4856. moveText(x, y) {
  4857. this.current.x = this.current.lineX += x;
  4858. this.current.y = this.current.lineY += y;
  4859. }
  4860. setLeadingMoveText(x, y) {
  4861. this.setLeading(-y);
  4862. this.moveText(x, y);
  4863. }
  4864. setTextMatrix(a, b, c, d, e, f) {
  4865. this.current.textMatrix = [a, b, c, d, e, f];
  4866. this.current.textMatrixScale = Math.hypot(a, b);
  4867. this.current.x = this.current.lineX = 0;
  4868. this.current.y = this.current.lineY = 0;
  4869. }
  4870. nextLine() {
  4871. this.moveText(0, this.current.leading);
  4872. }
  4873. paintChar(character, x, y, patternTransform, resetLineWidthToOne) {
  4874. const ctx = this.ctx;
  4875. const current = this.current;
  4876. const font = current.font;
  4877. const textRenderingMode = current.textRenderingMode;
  4878. const fontSize = current.fontSize / current.fontSizeScale;
  4879. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  4880. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  4881. const patternFill = current.patternFill && !font.missingFile;
  4882. let addToPath;
  4883. if (font.disableFontFace || isAddToPathSet || patternFill) {
  4884. addToPath = font.getPathGenerator(this.commonObjs, character);
  4885. }
  4886. if (font.disableFontFace || patternFill) {
  4887. ctx.save();
  4888. ctx.translate(x, y);
  4889. ctx.beginPath();
  4890. addToPath(ctx, fontSize);
  4891. if (patternTransform) {
  4892. ctx.setTransform.apply(ctx, patternTransform);
  4893. }
  4894. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4895. ctx.fill();
  4896. }
  4897. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4898. if (resetLineWidthToOne) {
  4899. ctx.resetTransform();
  4900. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  4901. }
  4902. ctx.stroke();
  4903. }
  4904. ctx.restore();
  4905. } else {
  4906. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4907. ctx.fillText(character, x, y);
  4908. }
  4909. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4910. if (resetLineWidthToOne) {
  4911. ctx.save();
  4912. ctx.moveTo(x, y);
  4913. ctx.resetTransform();
  4914. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  4915. ctx.strokeText(character, 0, 0);
  4916. ctx.restore();
  4917. } else {
  4918. ctx.strokeText(character, x, y);
  4919. }
  4920. }
  4921. }
  4922. if (isAddToPathSet) {
  4923. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4924. paths.push({
  4925. transform: ctx.mozCurrentTransform,
  4926. x,
  4927. y,
  4928. fontSize,
  4929. addToPath
  4930. });
  4931. }
  4932. }
  4933. get isFontSubpixelAAEnabled() {
  4934. const {
  4935. context: ctx
  4936. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  4937. ctx.scale(1.5, 1);
  4938. ctx.fillText("I", 0, 10);
  4939. const data = ctx.getImageData(0, 0, 10, 10).data;
  4940. let enabled = false;
  4941. for (let i = 3; i < data.length; i += 4) {
  4942. if (data[i] > 0 && data[i] < 255) {
  4943. enabled = true;
  4944. break;
  4945. }
  4946. }
  4947. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  4948. }
  4949. showText(glyphs) {
  4950. const current = this.current;
  4951. const font = current.font;
  4952. if (font.isType3Font) {
  4953. return this.showType3Text(glyphs);
  4954. }
  4955. const fontSize = current.fontSize;
  4956. if (fontSize === 0) {
  4957. return undefined;
  4958. }
  4959. const ctx = this.ctx;
  4960. const fontSizeScale = current.fontSizeScale;
  4961. const charSpacing = current.charSpacing;
  4962. const wordSpacing = current.wordSpacing;
  4963. const fontDirection = current.fontDirection;
  4964. const textHScale = current.textHScale * fontDirection;
  4965. const glyphsLength = glyphs.length;
  4966. const vertical = font.vertical;
  4967. const spacingDir = vertical ? 1 : -1;
  4968. const defaultVMetrics = font.defaultVMetrics;
  4969. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  4970. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  4971. ctx.save();
  4972. let patternTransform;
  4973. if (current.patternFill) {
  4974. ctx.save();
  4975. const pattern = current.fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse);
  4976. patternTransform = ctx.mozCurrentTransform;
  4977. ctx.restore();
  4978. ctx.fillStyle = pattern;
  4979. }
  4980. ctx.transform.apply(ctx, current.textMatrix);
  4981. ctx.translate(current.x, current.y + current.textRise);
  4982. if (fontDirection > 0) {
  4983. ctx.scale(textHScale, -1);
  4984. } else {
  4985. ctx.scale(textHScale, 1);
  4986. }
  4987. let lineWidth = current.lineWidth;
  4988. let resetLineWidthToOne = false;
  4989. const scale = current.textMatrixScale;
  4990. if (scale === 0 || lineWidth === 0) {
  4991. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  4992. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4993. this._cachedGetSinglePixelWidth = null;
  4994. lineWidth = this.getSinglePixelWidth();
  4995. resetLineWidthToOne = lineWidth < 0;
  4996. }
  4997. } else {
  4998. lineWidth /= scale;
  4999. }
  5000. if (fontSizeScale !== 1.0) {
  5001. ctx.scale(fontSizeScale, fontSizeScale);
  5002. lineWidth /= fontSizeScale;
  5003. }
  5004. ctx.lineWidth = lineWidth;
  5005. let x = 0,
  5006. i;
  5007. for (i = 0; i < glyphsLength; ++i) {
  5008. const glyph = glyphs[i];
  5009. if ((0, _util.isNum)(glyph)) {
  5010. x += spacingDir * glyph * fontSize / 1000;
  5011. continue;
  5012. }
  5013. let restoreNeeded = false;
  5014. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  5015. const character = glyph.fontChar;
  5016. const accent = glyph.accent;
  5017. let scaledX, scaledY;
  5018. let width = glyph.width;
  5019. if (vertical) {
  5020. const vmetric = glyph.vmetric || defaultVMetrics;
  5021. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  5022. const vy = vmetric[2] * widthAdvanceScale;
  5023. width = vmetric ? -vmetric[0] : width;
  5024. scaledX = vx / fontSizeScale;
  5025. scaledY = (x + vy) / fontSizeScale;
  5026. } else {
  5027. scaledX = x / fontSizeScale;
  5028. scaledY = 0;
  5029. }
  5030. if (font.remeasure && width > 0) {
  5031. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  5032. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  5033. const characterScaleX = width / measuredWidth;
  5034. restoreNeeded = true;
  5035. ctx.save();
  5036. ctx.scale(characterScaleX, 1);
  5037. scaledX /= characterScaleX;
  5038. } else if (width !== measuredWidth) {
  5039. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  5040. }
  5041. }
  5042. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  5043. if (simpleFillText && !accent) {
  5044. ctx.fillText(character, scaledX, scaledY);
  5045. } else {
  5046. this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne);
  5047. if (accent) {
  5048. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  5049. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  5050. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne);
  5051. }
  5052. }
  5053. }
  5054. let charWidth;
  5055. if (vertical) {
  5056. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  5057. } else {
  5058. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  5059. }
  5060. x += charWidth;
  5061. if (restoreNeeded) {
  5062. ctx.restore();
  5063. }
  5064. }
  5065. if (vertical) {
  5066. current.y -= x;
  5067. } else {
  5068. current.x += x * textHScale;
  5069. }
  5070. ctx.restore();
  5071. return undefined;
  5072. }
  5073. showType3Text(glyphs) {
  5074. const ctx = this.ctx;
  5075. const current = this.current;
  5076. const font = current.font;
  5077. const fontSize = current.fontSize;
  5078. const fontDirection = current.fontDirection;
  5079. const spacingDir = font.vertical ? 1 : -1;
  5080. const charSpacing = current.charSpacing;
  5081. const wordSpacing = current.wordSpacing;
  5082. const textHScale = current.textHScale * fontDirection;
  5083. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  5084. const glyphsLength = glyphs.length;
  5085. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  5086. let i, glyph, width, spacingLength;
  5087. if (isTextInvisible || fontSize === 0) {
  5088. return;
  5089. }
  5090. this._cachedGetSinglePixelWidth = null;
  5091. ctx.save();
  5092. ctx.transform.apply(ctx, current.textMatrix);
  5093. ctx.translate(current.x, current.y);
  5094. ctx.scale(textHScale, fontDirection);
  5095. for (i = 0; i < glyphsLength; ++i) {
  5096. glyph = glyphs[i];
  5097. if ((0, _util.isNum)(glyph)) {
  5098. spacingLength = spacingDir * glyph * fontSize / 1000;
  5099. this.ctx.translate(spacingLength, 0);
  5100. current.x += spacingLength * textHScale;
  5101. continue;
  5102. }
  5103. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  5104. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  5105. if (!operatorList) {
  5106. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  5107. continue;
  5108. }
  5109. if (this.contentVisible) {
  5110. this.processingType3 = glyph;
  5111. this.save();
  5112. ctx.scale(fontSize, fontSize);
  5113. ctx.transform.apply(ctx, fontMatrix);
  5114. this.executeOperatorList(operatorList);
  5115. this.restore();
  5116. }
  5117. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  5118. width = transformed[0] * fontSize + spacing;
  5119. ctx.translate(width, 0);
  5120. current.x += width * textHScale;
  5121. }
  5122. ctx.restore();
  5123. this.processingType3 = null;
  5124. }
  5125. setCharWidth(xWidth, yWidth) {}
  5126. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  5127. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  5128. this.clip();
  5129. this.endPath();
  5130. }
  5131. getColorN_Pattern(IR) {
  5132. let pattern;
  5133. if (IR[0] === "TilingPattern") {
  5134. const color = IR[1];
  5135. const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  5136. const canvasGraphicsFactory = {
  5137. createCanvasGraphics: ctx => {
  5138. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
  5139. }
  5140. };
  5141. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  5142. } else {
  5143. pattern = this._getPattern(IR[1]);
  5144. }
  5145. return pattern;
  5146. }
  5147. setStrokeColorN() {
  5148. this.current.strokeColor = this.getColorN_Pattern(arguments);
  5149. }
  5150. setFillColorN() {
  5151. this.current.fillColor = this.getColorN_Pattern(arguments);
  5152. this.current.patternFill = true;
  5153. }
  5154. setStrokeRGBColor(r, g, b) {
  5155. const color = _util.Util.makeHexColor(r, g, b);
  5156. this.ctx.strokeStyle = color;
  5157. this.current.strokeColor = color;
  5158. }
  5159. setFillRGBColor(r, g, b) {
  5160. const color = _util.Util.makeHexColor(r, g, b);
  5161. this.ctx.fillStyle = color;
  5162. this.current.fillColor = color;
  5163. this.current.patternFill = false;
  5164. }
  5165. _getPattern(objId) {
  5166. if (this.cachedPatterns.has(objId)) {
  5167. return this.cachedPatterns.get(objId);
  5168. }
  5169. const pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  5170. this.cachedPatterns.set(objId, pattern);
  5171. return pattern;
  5172. }
  5173. shadingFill(objId) {
  5174. if (!this.contentVisible) {
  5175. return;
  5176. }
  5177. const ctx = this.ctx;
  5178. this.save();
  5179. const pattern = this._getPattern(objId);
  5180. ctx.fillStyle = pattern.getPattern(ctx, this, ctx.mozCurrentTransformInverse, true);
  5181. const inv = ctx.mozCurrentTransformInverse;
  5182. if (inv) {
  5183. const canvas = ctx.canvas;
  5184. const width = canvas.width;
  5185. const height = canvas.height;
  5186. const bl = _util.Util.applyTransform([0, 0], inv);
  5187. const br = _util.Util.applyTransform([0, height], inv);
  5188. const ul = _util.Util.applyTransform([width, 0], inv);
  5189. const ur = _util.Util.applyTransform([width, height], inv);
  5190. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  5191. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  5192. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  5193. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  5194. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  5195. } else {
  5196. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  5197. }
  5198. this.restore();
  5199. }
  5200. beginInlineImage() {
  5201. (0, _util.unreachable)("Should not call beginInlineImage");
  5202. }
  5203. beginImageData() {
  5204. (0, _util.unreachable)("Should not call beginImageData");
  5205. }
  5206. paintFormXObjectBegin(matrix, bbox) {
  5207. if (!this.contentVisible) {
  5208. return;
  5209. }
  5210. this.save();
  5211. this.baseTransformStack.push(this.baseTransform);
  5212. if (Array.isArray(matrix) && matrix.length === 6) {
  5213. this.transform.apply(this, matrix);
  5214. }
  5215. this.baseTransform = this.ctx.mozCurrentTransform;
  5216. if (bbox) {
  5217. const width = bbox[2] - bbox[0];
  5218. const height = bbox[3] - bbox[1];
  5219. this.ctx.rect(bbox[0], bbox[1], width, height);
  5220. this.clip();
  5221. this.endPath();
  5222. }
  5223. }
  5224. paintFormXObjectEnd() {
  5225. if (!this.contentVisible) {
  5226. return;
  5227. }
  5228. this.restore();
  5229. this.baseTransform = this.baseTransformStack.pop();
  5230. }
  5231. beginGroup(group) {
  5232. if (!this.contentVisible) {
  5233. return;
  5234. }
  5235. this.save();
  5236. const currentCtx = this.ctx;
  5237. if (!group.isolated) {
  5238. (0, _util.info)("TODO: Support non-isolated groups.");
  5239. }
  5240. if (group.knockout) {
  5241. (0, _util.warn)("Knockout groups not supported.");
  5242. }
  5243. const currentTransform = currentCtx.mozCurrentTransform;
  5244. if (group.matrix) {
  5245. currentCtx.transform.apply(currentCtx, group.matrix);
  5246. }
  5247. if (!group.bbox) {
  5248. throw new Error("Bounding box is required.");
  5249. }
  5250. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  5251. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  5252. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  5253. const offsetX = Math.floor(bounds[0]);
  5254. const offsetY = Math.floor(bounds[1]);
  5255. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  5256. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  5257. let scaleX = 1,
  5258. scaleY = 1;
  5259. if (drawnWidth > MAX_GROUP_SIZE) {
  5260. scaleX = drawnWidth / MAX_GROUP_SIZE;
  5261. drawnWidth = MAX_GROUP_SIZE;
  5262. }
  5263. if (drawnHeight > MAX_GROUP_SIZE) {
  5264. scaleY = drawnHeight / MAX_GROUP_SIZE;
  5265. drawnHeight = MAX_GROUP_SIZE;
  5266. }
  5267. let cacheId = "groupAt" + this.groupLevel;
  5268. if (group.smask) {
  5269. cacheId += "_smask_" + this.smaskCounter++ % 2;
  5270. }
  5271. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  5272. const groupCtx = scratchCanvas.context;
  5273. groupCtx.scale(1 / scaleX, 1 / scaleY);
  5274. groupCtx.translate(-offsetX, -offsetY);
  5275. groupCtx.transform.apply(groupCtx, currentTransform);
  5276. if (group.smask) {
  5277. this.smaskStack.push({
  5278. canvas: scratchCanvas.canvas,
  5279. context: groupCtx,
  5280. offsetX,
  5281. offsetY,
  5282. scaleX,
  5283. scaleY,
  5284. subtype: group.smask.subtype,
  5285. backdrop: group.smask.backdrop,
  5286. transferMap: group.smask.transferMap || null,
  5287. startTransformInverse: null
  5288. });
  5289. } else {
  5290. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  5291. currentCtx.translate(offsetX, offsetY);
  5292. currentCtx.scale(scaleX, scaleY);
  5293. }
  5294. copyCtxState(currentCtx, groupCtx);
  5295. this.ctx = groupCtx;
  5296. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  5297. this.groupStack.push(currentCtx);
  5298. this.groupLevel++;
  5299. this.current.activeSMask = null;
  5300. }
  5301. endGroup(group) {
  5302. if (!this.contentVisible) {
  5303. return;
  5304. }
  5305. this.groupLevel--;
  5306. const groupCtx = this.ctx;
  5307. this.ctx = this.groupStack.pop();
  5308. if (this.ctx.imageSmoothingEnabled !== undefined) {
  5309. this.ctx.imageSmoothingEnabled = false;
  5310. } else {
  5311. this.ctx.mozImageSmoothingEnabled = false;
  5312. }
  5313. if (group.smask) {
  5314. this.tempSMask = this.smaskStack.pop();
  5315. } else {
  5316. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  5317. }
  5318. this.restore();
  5319. }
  5320. beginAnnotations() {
  5321. this.save();
  5322. if (this.baseTransform) {
  5323. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  5324. }
  5325. }
  5326. endAnnotations() {
  5327. this.restore();
  5328. }
  5329. beginAnnotation(id, rect, transform, matrix) {
  5330. this.save();
  5331. resetCtxToDefault(this.ctx);
  5332. this.current = new CanvasExtraState();
  5333. if (Array.isArray(rect) && rect.length === 4) {
  5334. const width = rect[2] - rect[0];
  5335. const height = rect[3] - rect[1];
  5336. this.ctx.rect(rect[0], rect[1], width, height);
  5337. this.clip();
  5338. this.endPath();
  5339. }
  5340. this.transform.apply(this, transform);
  5341. this.transform.apply(this, matrix);
  5342. }
  5343. endAnnotation() {
  5344. this.restore();
  5345. }
  5346. paintImageMaskXObject(img) {
  5347. if (!this.contentVisible) {
  5348. return;
  5349. }
  5350. const ctx = this.ctx;
  5351. const width = img.width,
  5352. height = img.height;
  5353. const glyph = this.processingType3;
  5354. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  5355. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  5356. glyph.compiled = compileType3Glyph({
  5357. data: img.data,
  5358. width,
  5359. height
  5360. });
  5361. } else {
  5362. glyph.compiled = null;
  5363. }
  5364. }
  5365. if (glyph?.compiled) {
  5366. glyph.compiled(ctx);
  5367. return;
  5368. }
  5369. const mask = this._createMaskCanvas(img);
  5370. const maskCanvas = mask.canvas;
  5371. ctx.save();
  5372. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5373. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  5374. ctx.restore();
  5375. }
  5376. paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  5377. if (!this.contentVisible) {
  5378. return;
  5379. }
  5380. const ctx = this.ctx;
  5381. ctx.save();
  5382. const currentTransform = ctx.mozCurrentTransform;
  5383. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  5384. const mask = this._createMaskCanvas(imgData);
  5385. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5386. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  5387. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  5388. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  5389. ctx.drawImage(mask.canvas, x, y);
  5390. }
  5391. ctx.restore();
  5392. }
  5393. paintImageMaskXObjectGroup(images) {
  5394. if (!this.contentVisible) {
  5395. return;
  5396. }
  5397. const ctx = this.ctx;
  5398. const fillColor = this.current.fillColor;
  5399. const isPatternFill = this.current.patternFill;
  5400. for (let i = 0, ii = images.length; i < ii; i++) {
  5401. const image = images[i];
  5402. const width = image.width,
  5403. height = image.height;
  5404. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5405. const maskCtx = maskCanvas.context;
  5406. maskCtx.save();
  5407. putBinaryImageMask(maskCtx, image);
  5408. maskCtx.globalCompositeOperation = "source-in";
  5409. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, ctx.mozCurrentTransformInverse, false) : fillColor;
  5410. maskCtx.fillRect(0, 0, width, height);
  5411. maskCtx.restore();
  5412. ctx.save();
  5413. ctx.transform.apply(ctx, image.transform);
  5414. ctx.scale(1, -1);
  5415. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  5416. ctx.restore();
  5417. }
  5418. }
  5419. paintImageXObject(objId) {
  5420. if (!this.contentVisible) {
  5421. return;
  5422. }
  5423. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  5424. if (!imgData) {
  5425. (0, _util.warn)("Dependent image isn't ready yet");
  5426. return;
  5427. }
  5428. this.paintInlineImageXObject(imgData);
  5429. }
  5430. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  5431. if (!this.contentVisible) {
  5432. return;
  5433. }
  5434. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  5435. if (!imgData) {
  5436. (0, _util.warn)("Dependent image isn't ready yet");
  5437. return;
  5438. }
  5439. const width = imgData.width;
  5440. const height = imgData.height;
  5441. const map = [];
  5442. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  5443. map.push({
  5444. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  5445. x: 0,
  5446. y: 0,
  5447. w: width,
  5448. h: height
  5449. });
  5450. }
  5451. this.paintInlineImageXObjectGroup(imgData, map);
  5452. }
  5453. paintInlineImageXObject(imgData) {
  5454. if (!this.contentVisible) {
  5455. return;
  5456. }
  5457. const width = imgData.width;
  5458. const height = imgData.height;
  5459. const ctx = this.ctx;
  5460. this.save();
  5461. ctx.scale(1 / width, -1 / height);
  5462. let imgToPaint;
  5463. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  5464. imgToPaint = imgData;
  5465. } else {
  5466. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  5467. const tmpCtx = tmpCanvas.context;
  5468. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  5469. imgToPaint = tmpCanvas.canvas;
  5470. }
  5471. const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse);
  5472. ctx.drawImage(scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  5473. if (this.imageLayer) {
  5474. const position = this.getCanvasPosition(0, -height);
  5475. this.imageLayer.appendImage({
  5476. imgData,
  5477. left: position[0],
  5478. top: position[1],
  5479. width: width / ctx.mozCurrentTransformInverse[0],
  5480. height: height / ctx.mozCurrentTransformInverse[3]
  5481. });
  5482. }
  5483. this.restore();
  5484. }
  5485. paintInlineImageXObjectGroup(imgData, map) {
  5486. if (!this.contentVisible) {
  5487. return;
  5488. }
  5489. const ctx = this.ctx;
  5490. const w = imgData.width;
  5491. const h = imgData.height;
  5492. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  5493. const tmpCtx = tmpCanvas.context;
  5494. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  5495. for (let i = 0, ii = map.length; i < ii; i++) {
  5496. const entry = map[i];
  5497. ctx.save();
  5498. ctx.transform.apply(ctx, entry.transform);
  5499. ctx.scale(1, -1);
  5500. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  5501. if (this.imageLayer) {
  5502. const position = this.getCanvasPosition(entry.x, entry.y);
  5503. this.imageLayer.appendImage({
  5504. imgData,
  5505. left: position[0],
  5506. top: position[1],
  5507. width: w,
  5508. height: h
  5509. });
  5510. }
  5511. ctx.restore();
  5512. }
  5513. }
  5514. paintSolidColorImageMask() {
  5515. if (!this.contentVisible) {
  5516. return;
  5517. }
  5518. this.ctx.fillRect(0, 0, 1, 1);
  5519. }
  5520. markPoint(tag) {}
  5521. markPointProps(tag, properties) {}
  5522. beginMarkedContent(tag) {
  5523. this.markedContentStack.push({
  5524. visible: true
  5525. });
  5526. }
  5527. beginMarkedContentProps(tag, properties) {
  5528. if (tag === "OC") {
  5529. this.markedContentStack.push({
  5530. visible: this.optionalContentConfig.isVisible(properties)
  5531. });
  5532. } else {
  5533. this.markedContentStack.push({
  5534. visible: true
  5535. });
  5536. }
  5537. this.contentVisible = this.isContentVisible();
  5538. }
  5539. endMarkedContent() {
  5540. this.markedContentStack.pop();
  5541. this.contentVisible = this.isContentVisible();
  5542. }
  5543. beginCompat() {}
  5544. endCompat() {}
  5545. consumePath() {
  5546. const ctx = this.ctx;
  5547. if (this.pendingClip) {
  5548. if (this.pendingClip === EO_CLIP) {
  5549. ctx.clip("evenodd");
  5550. } else {
  5551. ctx.clip();
  5552. }
  5553. this.pendingClip = null;
  5554. }
  5555. ctx.beginPath();
  5556. }
  5557. getSinglePixelWidth() {
  5558. if (this._cachedGetSinglePixelWidth === null) {
  5559. const m = this.ctx.mozCurrentTransform;
  5560. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  5561. const sqNorm1 = m[0] ** 2 + m[2] ** 2;
  5562. const sqNorm2 = m[1] ** 2 + m[3] ** 2;
  5563. const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet;
  5564. if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) {
  5565. this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight);
  5566. } else if (absDet > Number.EPSILON) {
  5567. this._cachedGetSinglePixelWidth = pixelHeight;
  5568. } else {
  5569. this._cachedGetSinglePixelWidth = 1;
  5570. }
  5571. }
  5572. return this._cachedGetSinglePixelWidth;
  5573. }
  5574. getCanvasPosition(x, y) {
  5575. const transform = this.ctx.mozCurrentTransform;
  5576. return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
  5577. }
  5578. isContentVisible() {
  5579. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  5580. if (!this.markedContentStack[i].visible) {
  5581. return false;
  5582. }
  5583. }
  5584. return true;
  5585. }
  5586. }
  5587. for (const op in _util.OPS) {
  5588. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  5589. }
  5590. return CanvasGraphics;
  5591. }();
  5592. exports.CanvasGraphics = CanvasGraphics;
  5593. /***/ }),
  5594. /* 11 */
  5595. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5596. Object.defineProperty(exports, "__esModule", ({
  5597. value: true
  5598. }));
  5599. exports.getShadingPattern = getShadingPattern;
  5600. exports.TilingPattern = void 0;
  5601. var _util = __w_pdfjs_require__(2);
  5602. function applyBoundingBox(ctx, bbox) {
  5603. if (!bbox || typeof Path2D === "undefined") {
  5604. return;
  5605. }
  5606. const width = bbox[2] - bbox[0];
  5607. const height = bbox[3] - bbox[1];
  5608. const region = new Path2D();
  5609. region.rect(bbox[0], bbox[1], width, height);
  5610. ctx.clip(region);
  5611. }
  5612. class BaseShadingPattern {
  5613. constructor() {
  5614. if (this.constructor === BaseShadingPattern) {
  5615. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  5616. }
  5617. }
  5618. getPattern() {
  5619. (0, _util.unreachable)("Abstract method `getPattern` called.");
  5620. }
  5621. }
  5622. class RadialAxialShadingPattern extends BaseShadingPattern {
  5623. constructor(IR) {
  5624. super();
  5625. this._type = IR[1];
  5626. this._bbox = IR[2];
  5627. this._colorStops = IR[3];
  5628. this._p0 = IR[4];
  5629. this._p1 = IR[5];
  5630. this._r0 = IR[6];
  5631. this._r1 = IR[7];
  5632. this._matrix = IR[8];
  5633. this._patternCache = null;
  5634. }
  5635. _createGradient(ctx) {
  5636. let grad;
  5637. if (this._type === "axial") {
  5638. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  5639. } else if (this._type === "radial") {
  5640. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  5641. }
  5642. for (const colorStop of this._colorStops) {
  5643. grad.addColorStop(colorStop[0], colorStop[1]);
  5644. }
  5645. return grad;
  5646. }
  5647. getPattern(ctx, owner, inverse, shadingFill = false) {
  5648. let pattern;
  5649. if (this._patternCache) {
  5650. pattern = this._patternCache;
  5651. } else {
  5652. if (!shadingFill) {
  5653. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", owner.ctx.canvas.width, owner.ctx.canvas.height, true);
  5654. const tmpCtx = tmpCanvas.context;
  5655. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5656. tmpCtx.beginPath();
  5657. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5658. tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
  5659. if (this._matrix) {
  5660. tmpCtx.transform.apply(tmpCtx, this._matrix);
  5661. }
  5662. applyBoundingBox(tmpCtx, this._bbox);
  5663. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  5664. tmpCtx.fill();
  5665. pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
  5666. } else {
  5667. applyBoundingBox(ctx, this._bbox);
  5668. pattern = this._createGradient(ctx);
  5669. }
  5670. this._patternCache = pattern;
  5671. }
  5672. if (!shadingFill) {
  5673. const domMatrix = new DOMMatrix(inverse);
  5674. try {
  5675. pattern.setTransform(domMatrix);
  5676. } catch (ex) {
  5677. (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
  5678. }
  5679. }
  5680. return pattern;
  5681. }
  5682. }
  5683. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5684. const coords = context.coords,
  5685. colors = context.colors;
  5686. const bytes = data.data,
  5687. rowSize = data.width * 4;
  5688. let tmp;
  5689. if (coords[p1 + 1] > coords[p2 + 1]) {
  5690. tmp = p1;
  5691. p1 = p2;
  5692. p2 = tmp;
  5693. tmp = c1;
  5694. c1 = c2;
  5695. c2 = tmp;
  5696. }
  5697. if (coords[p2 + 1] > coords[p3 + 1]) {
  5698. tmp = p2;
  5699. p2 = p3;
  5700. p3 = tmp;
  5701. tmp = c2;
  5702. c2 = c3;
  5703. c3 = tmp;
  5704. }
  5705. if (coords[p1 + 1] > coords[p2 + 1]) {
  5706. tmp = p1;
  5707. p1 = p2;
  5708. p2 = tmp;
  5709. tmp = c1;
  5710. c1 = c2;
  5711. c2 = tmp;
  5712. }
  5713. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5714. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5715. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5716. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5717. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5718. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5719. if (y1 >= y3) {
  5720. return;
  5721. }
  5722. const c1r = colors[c1],
  5723. c1g = colors[c1 + 1],
  5724. c1b = colors[c1 + 2];
  5725. const c2r = colors[c2],
  5726. c2g = colors[c2 + 1],
  5727. c2b = colors[c2 + 2];
  5728. const c3r = colors[c3],
  5729. c3g = colors[c3 + 1],
  5730. c3b = colors[c3 + 2];
  5731. const minY = Math.round(y1),
  5732. maxY = Math.round(y3);
  5733. let xa, car, cag, cab;
  5734. let xb, cbr, cbg, cbb;
  5735. for (let y = minY; y <= maxY; y++) {
  5736. if (y < y2) {
  5737. let k;
  5738. if (y < y1) {
  5739. k = 0;
  5740. } else {
  5741. k = (y1 - y) / (y1 - y2);
  5742. }
  5743. xa = x1 - (x1 - x2) * k;
  5744. car = c1r - (c1r - c2r) * k;
  5745. cag = c1g - (c1g - c2g) * k;
  5746. cab = c1b - (c1b - c2b) * k;
  5747. } else {
  5748. let k;
  5749. if (y > y3) {
  5750. k = 1;
  5751. } else if (y2 === y3) {
  5752. k = 0;
  5753. } else {
  5754. k = (y2 - y) / (y2 - y3);
  5755. }
  5756. xa = x2 - (x2 - x3) * k;
  5757. car = c2r - (c2r - c3r) * k;
  5758. cag = c2g - (c2g - c3g) * k;
  5759. cab = c2b - (c2b - c3b) * k;
  5760. }
  5761. let k;
  5762. if (y < y1) {
  5763. k = 0;
  5764. } else if (y > y3) {
  5765. k = 1;
  5766. } else {
  5767. k = (y1 - y) / (y1 - y3);
  5768. }
  5769. xb = x1 - (x1 - x3) * k;
  5770. cbr = c1r - (c1r - c3r) * k;
  5771. cbg = c1g - (c1g - c3g) * k;
  5772. cbb = c1b - (c1b - c3b) * k;
  5773. const x1_ = Math.round(Math.min(xa, xb));
  5774. const x2_ = Math.round(Math.max(xa, xb));
  5775. let j = rowSize * y + x1_ * 4;
  5776. for (let x = x1_; x <= x2_; x++) {
  5777. k = (xa - x) / (xa - xb);
  5778. if (k < 0) {
  5779. k = 0;
  5780. } else if (k > 1) {
  5781. k = 1;
  5782. }
  5783. bytes[j++] = car - (car - cbr) * k | 0;
  5784. bytes[j++] = cag - (cag - cbg) * k | 0;
  5785. bytes[j++] = cab - (cab - cbb) * k | 0;
  5786. bytes[j++] = 255;
  5787. }
  5788. }
  5789. }
  5790. function drawFigure(data, figure, context) {
  5791. const ps = figure.coords;
  5792. const cs = figure.colors;
  5793. let i, ii;
  5794. switch (figure.type) {
  5795. case "lattice":
  5796. const verticesPerRow = figure.verticesPerRow;
  5797. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  5798. const cols = verticesPerRow - 1;
  5799. for (i = 0; i < rows; i++) {
  5800. let q = i * verticesPerRow;
  5801. for (let j = 0; j < cols; j++, q++) {
  5802. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5803. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5804. }
  5805. }
  5806. break;
  5807. case "triangles":
  5808. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5809. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  5810. }
  5811. break;
  5812. default:
  5813. throw new Error("illegal figure");
  5814. }
  5815. }
  5816. class MeshShadingPattern extends BaseShadingPattern {
  5817. constructor(IR) {
  5818. super();
  5819. this._coords = IR[2];
  5820. this._colors = IR[3];
  5821. this._figures = IR[4];
  5822. this._bounds = IR[5];
  5823. this._matrix = IR[6];
  5824. this._bbox = IR[7];
  5825. this._background = IR[8];
  5826. }
  5827. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  5828. const EXPECTED_SCALE = 1.1;
  5829. const MAX_PATTERN_SIZE = 3000;
  5830. const BORDER_SIZE = 2;
  5831. const offsetX = Math.floor(this._bounds[0]);
  5832. const offsetY = Math.floor(this._bounds[1]);
  5833. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  5834. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  5835. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5836. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5837. const scaleX = boundsWidth / width;
  5838. const scaleY = boundsHeight / height;
  5839. const context = {
  5840. coords: this._coords,
  5841. colors: this._colors,
  5842. offsetX: -offsetX,
  5843. offsetY: -offsetY,
  5844. scaleX: 1 / scaleX,
  5845. scaleY: 1 / scaleY
  5846. };
  5847. const paddedWidth = width + BORDER_SIZE * 2;
  5848. const paddedHeight = height + BORDER_SIZE * 2;
  5849. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  5850. const tmpCtx = tmpCanvas.context;
  5851. const data = tmpCtx.createImageData(width, height);
  5852. if (backgroundColor) {
  5853. const bytes = data.data;
  5854. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  5855. bytes[i] = backgroundColor[0];
  5856. bytes[i + 1] = backgroundColor[1];
  5857. bytes[i + 2] = backgroundColor[2];
  5858. bytes[i + 3] = 255;
  5859. }
  5860. }
  5861. for (const figure of this._figures) {
  5862. drawFigure(data, figure, context);
  5863. }
  5864. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5865. const canvas = tmpCanvas.canvas;
  5866. return {
  5867. canvas,
  5868. offsetX: offsetX - BORDER_SIZE * scaleX,
  5869. offsetY: offsetY - BORDER_SIZE * scaleY,
  5870. scaleX,
  5871. scaleY
  5872. };
  5873. }
  5874. getPattern(ctx, owner, inverse, shadingFill = false) {
  5875. applyBoundingBox(ctx, this._bbox);
  5876. let scale;
  5877. if (shadingFill) {
  5878. scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5879. } else {
  5880. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  5881. if (this._matrix) {
  5882. const matrixScale = _util.Util.singularValueDecompose2dScale(this._matrix);
  5883. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  5884. }
  5885. }
  5886. const temporaryPatternCanvas = this._createMeshCanvas(scale, shadingFill ? null : this._background, owner.cachedCanvases);
  5887. if (!shadingFill) {
  5888. ctx.setTransform.apply(ctx, owner.baseTransform);
  5889. if (this._matrix) {
  5890. ctx.transform.apply(ctx, this._matrix);
  5891. }
  5892. }
  5893. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  5894. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  5895. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  5896. }
  5897. }
  5898. class DummyShadingPattern extends BaseShadingPattern {
  5899. getPattern() {
  5900. return "hotpink";
  5901. }
  5902. }
  5903. function getShadingPattern(IR) {
  5904. switch (IR[0]) {
  5905. case "RadialAxial":
  5906. return new RadialAxialShadingPattern(IR);
  5907. case "Mesh":
  5908. return new MeshShadingPattern(IR);
  5909. case "Dummy":
  5910. return new DummyShadingPattern();
  5911. }
  5912. throw new Error(`Unknown IR type: ${IR[0]}`);
  5913. }
  5914. const PaintType = {
  5915. COLORED: 1,
  5916. UNCOLORED: 2
  5917. };
  5918. class TilingPattern {
  5919. static get MAX_PATTERN_SIZE() {
  5920. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  5921. }
  5922. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5923. this.operatorList = IR[2];
  5924. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5925. this.bbox = IR[4];
  5926. this.xstep = IR[5];
  5927. this.ystep = IR[6];
  5928. this.paintType = IR[7];
  5929. this.tilingType = IR[8];
  5930. this.color = color;
  5931. this.ctx = ctx;
  5932. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5933. this.baseTransform = baseTransform;
  5934. }
  5935. createPatternCanvas(owner) {
  5936. const operatorList = this.operatorList;
  5937. const bbox = this.bbox;
  5938. const xstep = this.xstep;
  5939. const ystep = this.ystep;
  5940. const paintType = this.paintType;
  5941. const tilingType = this.tilingType;
  5942. const color = this.color;
  5943. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  5944. (0, _util.info)("TilingType: " + tilingType);
  5945. const x0 = bbox[0],
  5946. y0 = bbox[1],
  5947. x1 = bbox[2],
  5948. y1 = bbox[3];
  5949. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  5950. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  5951. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  5952. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  5953. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  5954. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  5955. const tmpCtx = tmpCanvas.context;
  5956. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5957. graphics.groupLevel = owner.groupLevel;
  5958. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  5959. let adjustedX0 = x0;
  5960. let adjustedY0 = y0;
  5961. let adjustedX1 = x1;
  5962. let adjustedY1 = y1;
  5963. if (x0 < 0) {
  5964. adjustedX0 = 0;
  5965. adjustedX1 += Math.abs(x0);
  5966. }
  5967. if (y0 < 0) {
  5968. adjustedY0 = 0;
  5969. adjustedY1 += Math.abs(y0);
  5970. }
  5971. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  5972. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  5973. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  5974. graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
  5975. graphics.executeOperatorList(operatorList);
  5976. graphics.endDrawing();
  5977. return {
  5978. canvas: tmpCanvas.canvas,
  5979. scaleX: dimx.scale,
  5980. scaleY: dimy.scale,
  5981. offsetX: adjustedX0,
  5982. offsetY: adjustedY0
  5983. };
  5984. }
  5985. getSizeAndScale(step, realOutputSize, scale) {
  5986. step = Math.abs(step);
  5987. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  5988. let size = Math.ceil(step * scale);
  5989. if (size >= maxSize) {
  5990. size = maxSize;
  5991. } else {
  5992. scale = size / step;
  5993. }
  5994. return {
  5995. scale,
  5996. size
  5997. };
  5998. }
  5999. clipBbox(graphics, x0, y0, x1, y1) {
  6000. const bboxWidth = x1 - x0;
  6001. const bboxHeight = y1 - y0;
  6002. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6003. graphics.clip();
  6004. graphics.endPath();
  6005. }
  6006. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  6007. const context = graphics.ctx,
  6008. current = graphics.current;
  6009. switch (paintType) {
  6010. case PaintType.COLORED:
  6011. const ctx = this.ctx;
  6012. context.fillStyle = ctx.fillStyle;
  6013. context.strokeStyle = ctx.strokeStyle;
  6014. current.fillColor = ctx.fillStyle;
  6015. current.strokeColor = ctx.strokeStyle;
  6016. break;
  6017. case PaintType.UNCOLORED:
  6018. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  6019. context.fillStyle = cssColor;
  6020. context.strokeStyle = cssColor;
  6021. current.fillColor = cssColor;
  6022. current.strokeColor = cssColor;
  6023. break;
  6024. default:
  6025. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  6026. }
  6027. }
  6028. getPattern(ctx, owner, inverse, shadingFill = false) {
  6029. let matrix = inverse;
  6030. if (!shadingFill) {
  6031. matrix = _util.Util.transform(matrix, owner.baseTransform);
  6032. if (this.matrix) {
  6033. matrix = _util.Util.transform(matrix, this.matrix);
  6034. }
  6035. }
  6036. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  6037. let domMatrix = new DOMMatrix(matrix);
  6038. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6039. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  6040. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  6041. try {
  6042. pattern.setTransform(domMatrix);
  6043. } catch (ex) {
  6044. (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
  6045. }
  6046. return pattern;
  6047. }
  6048. }
  6049. exports.TilingPattern = TilingPattern;
  6050. /***/ }),
  6051. /* 12 */
  6052. /***/ ((__unused_webpack_module, exports) => {
  6053. Object.defineProperty(exports, "__esModule", ({
  6054. value: true
  6055. }));
  6056. exports.GlobalWorkerOptions = void 0;
  6057. const GlobalWorkerOptions = Object.create(null);
  6058. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  6059. GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
  6060. GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
  6061. /***/ }),
  6062. /* 13 */
  6063. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6064. Object.defineProperty(exports, "__esModule", ({
  6065. value: true
  6066. }));
  6067. exports.MessageHandler = void 0;
  6068. var _util = __w_pdfjs_require__(2);
  6069. const CallbackKind = {
  6070. UNKNOWN: 0,
  6071. DATA: 1,
  6072. ERROR: 2
  6073. };
  6074. const StreamKind = {
  6075. UNKNOWN: 0,
  6076. CANCEL: 1,
  6077. CANCEL_COMPLETE: 2,
  6078. CLOSE: 3,
  6079. ENQUEUE: 4,
  6080. ERROR: 5,
  6081. PULL: 6,
  6082. PULL_COMPLETE: 7,
  6083. START_COMPLETE: 8
  6084. };
  6085. function wrapReason(reason) {
  6086. if (typeof reason !== "object" || reason === null) {
  6087. return reason;
  6088. }
  6089. switch (reason.name) {
  6090. case "AbortException":
  6091. return new _util.AbortException(reason.message);
  6092. case "MissingPDFException":
  6093. return new _util.MissingPDFException(reason.message);
  6094. case "UnexpectedResponseException":
  6095. return new _util.UnexpectedResponseException(reason.message, reason.status);
  6096. case "UnknownErrorException":
  6097. return new _util.UnknownErrorException(reason.message, reason.details);
  6098. default:
  6099. return new _util.UnknownErrorException(reason.message, reason.toString());
  6100. }
  6101. }
  6102. class MessageHandler {
  6103. constructor(sourceName, targetName, comObj) {
  6104. this.sourceName = sourceName;
  6105. this.targetName = targetName;
  6106. this.comObj = comObj;
  6107. this.callbackId = 1;
  6108. this.streamId = 1;
  6109. this.postMessageTransfers = true;
  6110. this.streamSinks = Object.create(null);
  6111. this.streamControllers = Object.create(null);
  6112. this.callbackCapabilities = Object.create(null);
  6113. this.actionHandler = Object.create(null);
  6114. this._onComObjOnMessage = event => {
  6115. const data = event.data;
  6116. if (data.targetName !== this.sourceName) {
  6117. return;
  6118. }
  6119. if (data.stream) {
  6120. this._processStreamMessage(data);
  6121. return;
  6122. }
  6123. if (data.callback) {
  6124. const callbackId = data.callbackId;
  6125. const capability = this.callbackCapabilities[callbackId];
  6126. if (!capability) {
  6127. throw new Error(`Cannot resolve callback ${callbackId}`);
  6128. }
  6129. delete this.callbackCapabilities[callbackId];
  6130. if (data.callback === CallbackKind.DATA) {
  6131. capability.resolve(data.data);
  6132. } else if (data.callback === CallbackKind.ERROR) {
  6133. capability.reject(wrapReason(data.reason));
  6134. } else {
  6135. throw new Error("Unexpected callback case");
  6136. }
  6137. return;
  6138. }
  6139. const action = this.actionHandler[data.action];
  6140. if (!action) {
  6141. throw new Error(`Unknown action from worker: ${data.action}`);
  6142. }
  6143. if (data.callbackId) {
  6144. const cbSourceName = this.sourceName;
  6145. const cbTargetName = data.sourceName;
  6146. new Promise(function (resolve) {
  6147. resolve(action(data.data));
  6148. }).then(function (result) {
  6149. comObj.postMessage({
  6150. sourceName: cbSourceName,
  6151. targetName: cbTargetName,
  6152. callback: CallbackKind.DATA,
  6153. callbackId: data.callbackId,
  6154. data: result
  6155. });
  6156. }, function (reason) {
  6157. comObj.postMessage({
  6158. sourceName: cbSourceName,
  6159. targetName: cbTargetName,
  6160. callback: CallbackKind.ERROR,
  6161. callbackId: data.callbackId,
  6162. reason: wrapReason(reason)
  6163. });
  6164. });
  6165. return;
  6166. }
  6167. if (data.streamId) {
  6168. this._createStreamSink(data);
  6169. return;
  6170. }
  6171. action(data.data);
  6172. };
  6173. comObj.addEventListener("message", this._onComObjOnMessage);
  6174. }
  6175. on(actionName, handler) {
  6176. const ah = this.actionHandler;
  6177. if (ah[actionName]) {
  6178. throw new Error(`There is already an actionName called "${actionName}"`);
  6179. }
  6180. ah[actionName] = handler;
  6181. }
  6182. send(actionName, data, transfers) {
  6183. this._postMessage({
  6184. sourceName: this.sourceName,
  6185. targetName: this.targetName,
  6186. action: actionName,
  6187. data
  6188. }, transfers);
  6189. }
  6190. sendWithPromise(actionName, data, transfers) {
  6191. const callbackId = this.callbackId++;
  6192. const capability = (0, _util.createPromiseCapability)();
  6193. this.callbackCapabilities[callbackId] = capability;
  6194. try {
  6195. this._postMessage({
  6196. sourceName: this.sourceName,
  6197. targetName: this.targetName,
  6198. action: actionName,
  6199. callbackId,
  6200. data
  6201. }, transfers);
  6202. } catch (ex) {
  6203. capability.reject(ex);
  6204. }
  6205. return capability.promise;
  6206. }
  6207. sendWithStream(actionName, data, queueingStrategy, transfers) {
  6208. const streamId = this.streamId++;
  6209. const sourceName = this.sourceName;
  6210. const targetName = this.targetName;
  6211. const comObj = this.comObj;
  6212. return new ReadableStream({
  6213. start: controller => {
  6214. const startCapability = (0, _util.createPromiseCapability)();
  6215. this.streamControllers[streamId] = {
  6216. controller,
  6217. startCall: startCapability,
  6218. pullCall: null,
  6219. cancelCall: null,
  6220. isClosed: false
  6221. };
  6222. this._postMessage({
  6223. sourceName,
  6224. targetName,
  6225. action: actionName,
  6226. streamId,
  6227. data,
  6228. desiredSize: controller.desiredSize
  6229. }, transfers);
  6230. return startCapability.promise;
  6231. },
  6232. pull: controller => {
  6233. const pullCapability = (0, _util.createPromiseCapability)();
  6234. this.streamControllers[streamId].pullCall = pullCapability;
  6235. comObj.postMessage({
  6236. sourceName,
  6237. targetName,
  6238. stream: StreamKind.PULL,
  6239. streamId,
  6240. desiredSize: controller.desiredSize
  6241. });
  6242. return pullCapability.promise;
  6243. },
  6244. cancel: reason => {
  6245. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  6246. const cancelCapability = (0, _util.createPromiseCapability)();
  6247. this.streamControllers[streamId].cancelCall = cancelCapability;
  6248. this.streamControllers[streamId].isClosed = true;
  6249. comObj.postMessage({
  6250. sourceName,
  6251. targetName,
  6252. stream: StreamKind.CANCEL,
  6253. streamId,
  6254. reason: wrapReason(reason)
  6255. });
  6256. return cancelCapability.promise;
  6257. }
  6258. }, queueingStrategy);
  6259. }
  6260. _createStreamSink(data) {
  6261. const self = this;
  6262. const action = this.actionHandler[data.action];
  6263. const streamId = data.streamId;
  6264. const sourceName = this.sourceName;
  6265. const targetName = data.sourceName;
  6266. const comObj = this.comObj;
  6267. const streamSink = {
  6268. enqueue(chunk, size = 1, transfers) {
  6269. if (this.isCancelled) {
  6270. return;
  6271. }
  6272. const lastDesiredSize = this.desiredSize;
  6273. this.desiredSize -= size;
  6274. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  6275. this.sinkCapability = (0, _util.createPromiseCapability)();
  6276. this.ready = this.sinkCapability.promise;
  6277. }
  6278. self._postMessage({
  6279. sourceName,
  6280. targetName,
  6281. stream: StreamKind.ENQUEUE,
  6282. streamId,
  6283. chunk
  6284. }, transfers);
  6285. },
  6286. close() {
  6287. if (this.isCancelled) {
  6288. return;
  6289. }
  6290. this.isCancelled = true;
  6291. comObj.postMessage({
  6292. sourceName,
  6293. targetName,
  6294. stream: StreamKind.CLOSE,
  6295. streamId
  6296. });
  6297. delete self.streamSinks[streamId];
  6298. },
  6299. error(reason) {
  6300. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  6301. if (this.isCancelled) {
  6302. return;
  6303. }
  6304. this.isCancelled = true;
  6305. comObj.postMessage({
  6306. sourceName,
  6307. targetName,
  6308. stream: StreamKind.ERROR,
  6309. streamId,
  6310. reason: wrapReason(reason)
  6311. });
  6312. },
  6313. sinkCapability: (0, _util.createPromiseCapability)(),
  6314. onPull: null,
  6315. onCancel: null,
  6316. isCancelled: false,
  6317. desiredSize: data.desiredSize,
  6318. ready: null
  6319. };
  6320. streamSink.sinkCapability.resolve();
  6321. streamSink.ready = streamSink.sinkCapability.promise;
  6322. this.streamSinks[streamId] = streamSink;
  6323. new Promise(function (resolve) {
  6324. resolve(action(data.data, streamSink));
  6325. }).then(function () {
  6326. comObj.postMessage({
  6327. sourceName,
  6328. targetName,
  6329. stream: StreamKind.START_COMPLETE,
  6330. streamId,
  6331. success: true
  6332. });
  6333. }, function (reason) {
  6334. comObj.postMessage({
  6335. sourceName,
  6336. targetName,
  6337. stream: StreamKind.START_COMPLETE,
  6338. streamId,
  6339. reason: wrapReason(reason)
  6340. });
  6341. });
  6342. }
  6343. _processStreamMessage(data) {
  6344. const streamId = data.streamId;
  6345. const sourceName = this.sourceName;
  6346. const targetName = data.sourceName;
  6347. const comObj = this.comObj;
  6348. switch (data.stream) {
  6349. case StreamKind.START_COMPLETE:
  6350. if (data.success) {
  6351. this.streamControllers[streamId].startCall.resolve();
  6352. } else {
  6353. this.streamControllers[streamId].startCall.reject(wrapReason(data.reason));
  6354. }
  6355. break;
  6356. case StreamKind.PULL_COMPLETE:
  6357. if (data.success) {
  6358. this.streamControllers[streamId].pullCall.resolve();
  6359. } else {
  6360. this.streamControllers[streamId].pullCall.reject(wrapReason(data.reason));
  6361. }
  6362. break;
  6363. case StreamKind.PULL:
  6364. if (!this.streamSinks[streamId]) {
  6365. comObj.postMessage({
  6366. sourceName,
  6367. targetName,
  6368. stream: StreamKind.PULL_COMPLETE,
  6369. streamId,
  6370. success: true
  6371. });
  6372. break;
  6373. }
  6374. if (this.streamSinks[streamId].desiredSize <= 0 && data.desiredSize > 0) {
  6375. this.streamSinks[streamId].sinkCapability.resolve();
  6376. }
  6377. this.streamSinks[streamId].desiredSize = data.desiredSize;
  6378. const {
  6379. onPull
  6380. } = this.streamSinks[data.streamId];
  6381. new Promise(function (resolve) {
  6382. resolve(onPull && onPull());
  6383. }).then(function () {
  6384. comObj.postMessage({
  6385. sourceName,
  6386. targetName,
  6387. stream: StreamKind.PULL_COMPLETE,
  6388. streamId,
  6389. success: true
  6390. });
  6391. }, function (reason) {
  6392. comObj.postMessage({
  6393. sourceName,
  6394. targetName,
  6395. stream: StreamKind.PULL_COMPLETE,
  6396. streamId,
  6397. reason: wrapReason(reason)
  6398. });
  6399. });
  6400. break;
  6401. case StreamKind.ENQUEUE:
  6402. (0, _util.assert)(this.streamControllers[streamId], "enqueue should have stream controller");
  6403. if (this.streamControllers[streamId].isClosed) {
  6404. break;
  6405. }
  6406. this.streamControllers[streamId].controller.enqueue(data.chunk);
  6407. break;
  6408. case StreamKind.CLOSE:
  6409. (0, _util.assert)(this.streamControllers[streamId], "close should have stream controller");
  6410. if (this.streamControllers[streamId].isClosed) {
  6411. break;
  6412. }
  6413. this.streamControllers[streamId].isClosed = true;
  6414. this.streamControllers[streamId].controller.close();
  6415. this._deleteStreamController(streamId);
  6416. break;
  6417. case StreamKind.ERROR:
  6418. (0, _util.assert)(this.streamControllers[streamId], "error should have stream controller");
  6419. this.streamControllers[streamId].controller.error(wrapReason(data.reason));
  6420. this._deleteStreamController(streamId);
  6421. break;
  6422. case StreamKind.CANCEL_COMPLETE:
  6423. if (data.success) {
  6424. this.streamControllers[streamId].cancelCall.resolve();
  6425. } else {
  6426. this.streamControllers[streamId].cancelCall.reject(wrapReason(data.reason));
  6427. }
  6428. this._deleteStreamController(streamId);
  6429. break;
  6430. case StreamKind.CANCEL:
  6431. if (!this.streamSinks[streamId]) {
  6432. break;
  6433. }
  6434. const {
  6435. onCancel
  6436. } = this.streamSinks[data.streamId];
  6437. new Promise(function (resolve) {
  6438. resolve(onCancel && onCancel(wrapReason(data.reason)));
  6439. }).then(function () {
  6440. comObj.postMessage({
  6441. sourceName,
  6442. targetName,
  6443. stream: StreamKind.CANCEL_COMPLETE,
  6444. streamId,
  6445. success: true
  6446. });
  6447. }, function (reason) {
  6448. comObj.postMessage({
  6449. sourceName,
  6450. targetName,
  6451. stream: StreamKind.CANCEL_COMPLETE,
  6452. streamId,
  6453. reason: wrapReason(reason)
  6454. });
  6455. });
  6456. this.streamSinks[streamId].sinkCapability.reject(wrapReason(data.reason));
  6457. this.streamSinks[streamId].isCancelled = true;
  6458. delete this.streamSinks[streamId];
  6459. break;
  6460. default:
  6461. throw new Error("Unexpected stream case");
  6462. }
  6463. }
  6464. async _deleteStreamController(streamId) {
  6465. await Promise.allSettled([this.streamControllers[streamId].startCall, this.streamControllers[streamId].pullCall, this.streamControllers[streamId].cancelCall].map(function (capability) {
  6466. return capability && capability.promise;
  6467. }));
  6468. delete this.streamControllers[streamId];
  6469. }
  6470. _postMessage(message, transfers) {
  6471. if (transfers && this.postMessageTransfers) {
  6472. this.comObj.postMessage(message, transfers);
  6473. } else {
  6474. this.comObj.postMessage(message);
  6475. }
  6476. }
  6477. destroy() {
  6478. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  6479. }
  6480. }
  6481. exports.MessageHandler = MessageHandler;
  6482. /***/ }),
  6483. /* 14 */
  6484. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6485. Object.defineProperty(exports, "__esModule", ({
  6486. value: true
  6487. }));
  6488. exports.Metadata = void 0;
  6489. var _util = __w_pdfjs_require__(2);
  6490. class Metadata {
  6491. constructor({
  6492. parsedData,
  6493. rawData
  6494. }) {
  6495. this._metadataMap = parsedData;
  6496. this._data = rawData;
  6497. }
  6498. getRaw() {
  6499. return this._data;
  6500. }
  6501. get(name) {
  6502. return this._metadataMap.get(name) ?? null;
  6503. }
  6504. getAll() {
  6505. return (0, _util.objectFromMap)(this._metadataMap);
  6506. }
  6507. has(name) {
  6508. return this._metadataMap.has(name);
  6509. }
  6510. }
  6511. exports.Metadata = Metadata;
  6512. /***/ }),
  6513. /* 15 */
  6514. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6515. Object.defineProperty(exports, "__esModule", ({
  6516. value: true
  6517. }));
  6518. exports.OptionalContentConfig = void 0;
  6519. var _util = __w_pdfjs_require__(2);
  6520. class OptionalContentGroup {
  6521. constructor(name, intent) {
  6522. this.visible = true;
  6523. this.name = name;
  6524. this.intent = intent;
  6525. }
  6526. }
  6527. class OptionalContentConfig {
  6528. constructor(data) {
  6529. this.name = null;
  6530. this.creator = null;
  6531. this._order = null;
  6532. this._groups = new Map();
  6533. if (data === null) {
  6534. return;
  6535. }
  6536. this.name = data.name;
  6537. this.creator = data.creator;
  6538. this._order = data.order;
  6539. for (const group of data.groups) {
  6540. this._groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  6541. }
  6542. if (data.baseState === "OFF") {
  6543. for (const group of this._groups) {
  6544. group.visible = false;
  6545. }
  6546. }
  6547. for (const on of data.on) {
  6548. this._groups.get(on).visible = true;
  6549. }
  6550. for (const off of data.off) {
  6551. this._groups.get(off).visible = false;
  6552. }
  6553. }
  6554. _evaluateVisibilityExpression(array) {
  6555. const length = array.length;
  6556. if (length < 2) {
  6557. return true;
  6558. }
  6559. const operator = array[0];
  6560. for (let i = 1; i < length; i++) {
  6561. const element = array[i];
  6562. let state;
  6563. if (Array.isArray(element)) {
  6564. state = this._evaluateVisibilityExpression(element);
  6565. } else if (this._groups.has(element)) {
  6566. state = this._groups.get(element).visible;
  6567. } else {
  6568. (0, _util.warn)(`Optional content group not found: ${element}`);
  6569. return true;
  6570. }
  6571. switch (operator) {
  6572. case "And":
  6573. if (!state) {
  6574. return false;
  6575. }
  6576. break;
  6577. case "Or":
  6578. if (state) {
  6579. return true;
  6580. }
  6581. break;
  6582. case "Not":
  6583. return !state;
  6584. default:
  6585. return true;
  6586. }
  6587. }
  6588. return operator === "And";
  6589. }
  6590. isVisible(group) {
  6591. if (group.type === "OCG") {
  6592. if (!this._groups.has(group.id)) {
  6593. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  6594. return true;
  6595. }
  6596. return this._groups.get(group.id).visible;
  6597. } else if (group.type === "OCMD") {
  6598. if (group.expression) {
  6599. return this._evaluateVisibilityExpression(group.expression);
  6600. }
  6601. if (!group.policy || group.policy === "AnyOn") {
  6602. for (const id of group.ids) {
  6603. if (!this._groups.has(id)) {
  6604. (0, _util.warn)(`Optional content group not found: ${id}`);
  6605. return true;
  6606. }
  6607. if (this._groups.get(id).visible) {
  6608. return true;
  6609. }
  6610. }
  6611. return false;
  6612. } else if (group.policy === "AllOn") {
  6613. for (const id of group.ids) {
  6614. if (!this._groups.has(id)) {
  6615. (0, _util.warn)(`Optional content group not found: ${id}`);
  6616. return true;
  6617. }
  6618. if (!this._groups.get(id).visible) {
  6619. return false;
  6620. }
  6621. }
  6622. return true;
  6623. } else if (group.policy === "AnyOff") {
  6624. for (const id of group.ids) {
  6625. if (!this._groups.has(id)) {
  6626. (0, _util.warn)(`Optional content group not found: ${id}`);
  6627. return true;
  6628. }
  6629. if (!this._groups.get(id).visible) {
  6630. return true;
  6631. }
  6632. }
  6633. return false;
  6634. } else if (group.policy === "AllOff") {
  6635. for (const id of group.ids) {
  6636. if (!this._groups.has(id)) {
  6637. (0, _util.warn)(`Optional content group not found: ${id}`);
  6638. return true;
  6639. }
  6640. if (this._groups.get(id).visible) {
  6641. return false;
  6642. }
  6643. }
  6644. return true;
  6645. }
  6646. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  6647. return true;
  6648. }
  6649. (0, _util.warn)(`Unknown group type ${group.type}.`);
  6650. return true;
  6651. }
  6652. setVisibility(id, visible = true) {
  6653. if (!this._groups.has(id)) {
  6654. (0, _util.warn)(`Optional content group not found: ${id}`);
  6655. return;
  6656. }
  6657. this._groups.get(id).visible = !!visible;
  6658. }
  6659. getOrder() {
  6660. if (!this._groups.size) {
  6661. return null;
  6662. }
  6663. if (this._order) {
  6664. return this._order.slice();
  6665. }
  6666. return Array.from(this._groups.keys());
  6667. }
  6668. getGroups() {
  6669. return this._groups.size > 0 ? (0, _util.objectFromMap)(this._groups) : null;
  6670. }
  6671. getGroup(id) {
  6672. return this._groups.get(id) || null;
  6673. }
  6674. }
  6675. exports.OptionalContentConfig = OptionalContentConfig;
  6676. /***/ }),
  6677. /* 16 */
  6678. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6679. Object.defineProperty(exports, "__esModule", ({
  6680. value: true
  6681. }));
  6682. exports.PDFDataTransportStream = void 0;
  6683. var _util = __w_pdfjs_require__(2);
  6684. var _display_utils = __w_pdfjs_require__(1);
  6685. class PDFDataTransportStream {
  6686. constructor(params, pdfDataRangeTransport) {
  6687. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  6688. this._queuedChunks = [];
  6689. this._progressiveDone = params.progressiveDone || false;
  6690. this._contentDispositionFilename = params.contentDispositionFilename || null;
  6691. const initialData = params.initialData;
  6692. if (initialData?.length > 0) {
  6693. const buffer = new Uint8Array(initialData).buffer;
  6694. this._queuedChunks.push(buffer);
  6695. }
  6696. this._pdfDataRangeTransport = pdfDataRangeTransport;
  6697. this._isStreamingSupported = !params.disableStream;
  6698. this._isRangeSupported = !params.disableRange;
  6699. this._contentLength = params.length;
  6700. this._fullRequestReader = null;
  6701. this._rangeReaders = [];
  6702. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  6703. this._onReceiveData({
  6704. begin,
  6705. chunk
  6706. });
  6707. });
  6708. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  6709. this._onProgress({
  6710. loaded,
  6711. total
  6712. });
  6713. });
  6714. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  6715. this._onReceiveData({
  6716. chunk
  6717. });
  6718. });
  6719. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  6720. this._onProgressiveDone();
  6721. });
  6722. this._pdfDataRangeTransport.transportReady();
  6723. }
  6724. _onReceiveData(args) {
  6725. const buffer = new Uint8Array(args.chunk).buffer;
  6726. if (args.begin === undefined) {
  6727. if (this._fullRequestReader) {
  6728. this._fullRequestReader._enqueue(buffer);
  6729. } else {
  6730. this._queuedChunks.push(buffer);
  6731. }
  6732. } else {
  6733. const found = this._rangeReaders.some(function (rangeReader) {
  6734. if (rangeReader._begin !== args.begin) {
  6735. return false;
  6736. }
  6737. rangeReader._enqueue(buffer);
  6738. return true;
  6739. });
  6740. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  6741. }
  6742. }
  6743. get _progressiveDataLength() {
  6744. return this._fullRequestReader?._loaded ?? 0;
  6745. }
  6746. _onProgress(evt) {
  6747. if (evt.total === undefined) {
  6748. const firstReader = this._rangeReaders[0];
  6749. if (firstReader?.onProgress) {
  6750. firstReader.onProgress({
  6751. loaded: evt.loaded
  6752. });
  6753. }
  6754. } else {
  6755. const fullReader = this._fullRequestReader;
  6756. if (fullReader?.onProgress) {
  6757. fullReader.onProgress({
  6758. loaded: evt.loaded,
  6759. total: evt.total
  6760. });
  6761. }
  6762. }
  6763. }
  6764. _onProgressiveDone() {
  6765. if (this._fullRequestReader) {
  6766. this._fullRequestReader.progressiveDone();
  6767. }
  6768. this._progressiveDone = true;
  6769. }
  6770. _removeRangeReader(reader) {
  6771. const i = this._rangeReaders.indexOf(reader);
  6772. if (i >= 0) {
  6773. this._rangeReaders.splice(i, 1);
  6774. }
  6775. }
  6776. getFullReader() {
  6777. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  6778. const queuedChunks = this._queuedChunks;
  6779. this._queuedChunks = null;
  6780. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  6781. }
  6782. getRangeReader(begin, end) {
  6783. if (end <= this._progressiveDataLength) {
  6784. return null;
  6785. }
  6786. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  6787. this._pdfDataRangeTransport.requestDataRange(begin, end);
  6788. this._rangeReaders.push(reader);
  6789. return reader;
  6790. }
  6791. cancelAllRequests(reason) {
  6792. if (this._fullRequestReader) {
  6793. this._fullRequestReader.cancel(reason);
  6794. }
  6795. for (const reader of this._rangeReaders.slice(0)) {
  6796. reader.cancel(reason);
  6797. }
  6798. this._pdfDataRangeTransport.abort();
  6799. }
  6800. }
  6801. exports.PDFDataTransportStream = PDFDataTransportStream;
  6802. class PDFDataTransportStreamReader {
  6803. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  6804. this._stream = stream;
  6805. this._done = progressiveDone || false;
  6806. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  6807. this._queuedChunks = queuedChunks || [];
  6808. this._loaded = 0;
  6809. for (const chunk of this._queuedChunks) {
  6810. this._loaded += chunk.byteLength;
  6811. }
  6812. this._requests = [];
  6813. this._headersReady = Promise.resolve();
  6814. stream._fullRequestReader = this;
  6815. this.onProgress = null;
  6816. }
  6817. _enqueue(chunk) {
  6818. if (this._done) {
  6819. return;
  6820. }
  6821. if (this._requests.length > 0) {
  6822. const requestCapability = this._requests.shift();
  6823. requestCapability.resolve({
  6824. value: chunk,
  6825. done: false
  6826. });
  6827. } else {
  6828. this._queuedChunks.push(chunk);
  6829. }
  6830. this._loaded += chunk.byteLength;
  6831. }
  6832. get headersReady() {
  6833. return this._headersReady;
  6834. }
  6835. get filename() {
  6836. return this._filename;
  6837. }
  6838. get isRangeSupported() {
  6839. return this._stream._isRangeSupported;
  6840. }
  6841. get isStreamingSupported() {
  6842. return this._stream._isStreamingSupported;
  6843. }
  6844. get contentLength() {
  6845. return this._stream._contentLength;
  6846. }
  6847. async read() {
  6848. if (this._queuedChunks.length > 0) {
  6849. const chunk = this._queuedChunks.shift();
  6850. return {
  6851. value: chunk,
  6852. done: false
  6853. };
  6854. }
  6855. if (this._done) {
  6856. return {
  6857. value: undefined,
  6858. done: true
  6859. };
  6860. }
  6861. const requestCapability = (0, _util.createPromiseCapability)();
  6862. this._requests.push(requestCapability);
  6863. return requestCapability.promise;
  6864. }
  6865. cancel(reason) {
  6866. this._done = true;
  6867. for (const requestCapability of this._requests) {
  6868. requestCapability.resolve({
  6869. value: undefined,
  6870. done: true
  6871. });
  6872. }
  6873. this._requests.length = 0;
  6874. }
  6875. progressiveDone() {
  6876. if (this._done) {
  6877. return;
  6878. }
  6879. this._done = true;
  6880. }
  6881. }
  6882. class PDFDataTransportStreamRangeReader {
  6883. constructor(stream, begin, end) {
  6884. this._stream = stream;
  6885. this._begin = begin;
  6886. this._end = end;
  6887. this._queuedChunk = null;
  6888. this._requests = [];
  6889. this._done = false;
  6890. this.onProgress = null;
  6891. }
  6892. _enqueue(chunk) {
  6893. if (this._done) {
  6894. return;
  6895. }
  6896. if (this._requests.length === 0) {
  6897. this._queuedChunk = chunk;
  6898. } else {
  6899. const requestsCapability = this._requests.shift();
  6900. requestsCapability.resolve({
  6901. value: chunk,
  6902. done: false
  6903. });
  6904. for (const requestCapability of this._requests) {
  6905. requestCapability.resolve({
  6906. value: undefined,
  6907. done: true
  6908. });
  6909. }
  6910. this._requests.length = 0;
  6911. }
  6912. this._done = true;
  6913. this._stream._removeRangeReader(this);
  6914. }
  6915. get isStreamingSupported() {
  6916. return false;
  6917. }
  6918. async read() {
  6919. if (this._queuedChunk) {
  6920. const chunk = this._queuedChunk;
  6921. this._queuedChunk = null;
  6922. return {
  6923. value: chunk,
  6924. done: false
  6925. };
  6926. }
  6927. if (this._done) {
  6928. return {
  6929. value: undefined,
  6930. done: true
  6931. };
  6932. }
  6933. const requestCapability = (0, _util.createPromiseCapability)();
  6934. this._requests.push(requestCapability);
  6935. return requestCapability.promise;
  6936. }
  6937. cancel(reason) {
  6938. this._done = true;
  6939. for (const requestCapability of this._requests) {
  6940. requestCapability.resolve({
  6941. value: undefined,
  6942. done: true
  6943. });
  6944. }
  6945. this._requests.length = 0;
  6946. this._stream._removeRangeReader(this);
  6947. }
  6948. }
  6949. /***/ }),
  6950. /* 17 */
  6951. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6952. Object.defineProperty(exports, "__esModule", ({
  6953. value: true
  6954. }));
  6955. exports.AnnotationLayer = void 0;
  6956. var _display_utils = __w_pdfjs_require__(1);
  6957. var _util = __w_pdfjs_require__(2);
  6958. var _annotation_storage = __w_pdfjs_require__(9);
  6959. var _scripting_utils = __w_pdfjs_require__(18);
  6960. class AnnotationElementFactory {
  6961. static create(parameters) {
  6962. const subtype = parameters.data.annotationType;
  6963. switch (subtype) {
  6964. case _util.AnnotationType.LINK:
  6965. return new LinkAnnotationElement(parameters);
  6966. case _util.AnnotationType.TEXT:
  6967. return new TextAnnotationElement(parameters);
  6968. case _util.AnnotationType.WIDGET:
  6969. const fieldType = parameters.data.fieldType;
  6970. switch (fieldType) {
  6971. case "Tx":
  6972. return new TextWidgetAnnotationElement(parameters);
  6973. case "Btn":
  6974. if (parameters.data.radioButton) {
  6975. return new RadioButtonWidgetAnnotationElement(parameters);
  6976. } else if (parameters.data.checkBox) {
  6977. return new CheckboxWidgetAnnotationElement(parameters);
  6978. }
  6979. return new PushButtonWidgetAnnotationElement(parameters);
  6980. case "Ch":
  6981. return new ChoiceWidgetAnnotationElement(parameters);
  6982. }
  6983. return new WidgetAnnotationElement(parameters);
  6984. case _util.AnnotationType.POPUP:
  6985. return new PopupAnnotationElement(parameters);
  6986. case _util.AnnotationType.FREETEXT:
  6987. return new FreeTextAnnotationElement(parameters);
  6988. case _util.AnnotationType.LINE:
  6989. return new LineAnnotationElement(parameters);
  6990. case _util.AnnotationType.SQUARE:
  6991. return new SquareAnnotationElement(parameters);
  6992. case _util.AnnotationType.CIRCLE:
  6993. return new CircleAnnotationElement(parameters);
  6994. case _util.AnnotationType.POLYLINE:
  6995. return new PolylineAnnotationElement(parameters);
  6996. case _util.AnnotationType.CARET:
  6997. return new CaretAnnotationElement(parameters);
  6998. case _util.AnnotationType.INK:
  6999. return new InkAnnotationElement(parameters);
  7000. case _util.AnnotationType.POLYGON:
  7001. return new PolygonAnnotationElement(parameters);
  7002. case _util.AnnotationType.HIGHLIGHT:
  7003. return new HighlightAnnotationElement(parameters);
  7004. case _util.AnnotationType.UNDERLINE:
  7005. return new UnderlineAnnotationElement(parameters);
  7006. case _util.AnnotationType.SQUIGGLY:
  7007. return new SquigglyAnnotationElement(parameters);
  7008. case _util.AnnotationType.STRIKEOUT:
  7009. return new StrikeOutAnnotationElement(parameters);
  7010. case _util.AnnotationType.STAMP:
  7011. return new StampAnnotationElement(parameters);
  7012. case _util.AnnotationType.FILEATTACHMENT:
  7013. return new FileAttachmentAnnotationElement(parameters);
  7014. default:
  7015. return new AnnotationElement(parameters);
  7016. }
  7017. }
  7018. }
  7019. class AnnotationElement {
  7020. constructor(parameters, {
  7021. isRenderable = false,
  7022. ignoreBorder = false,
  7023. createQuadrilaterals = false
  7024. } = {}) {
  7025. this.isRenderable = isRenderable;
  7026. this.data = parameters.data;
  7027. this.layer = parameters.layer;
  7028. this.page = parameters.page;
  7029. this.viewport = parameters.viewport;
  7030. this.linkService = parameters.linkService;
  7031. this.downloadManager = parameters.downloadManager;
  7032. this.imageResourcesPath = parameters.imageResourcesPath;
  7033. this.renderInteractiveForms = parameters.renderInteractiveForms;
  7034. this.svgFactory = parameters.svgFactory;
  7035. this.annotationStorage = parameters.annotationStorage;
  7036. this.enableScripting = parameters.enableScripting;
  7037. this.hasJSActions = parameters.hasJSActions;
  7038. this._mouseState = parameters.mouseState;
  7039. if (isRenderable) {
  7040. this.container = this._createContainer(ignoreBorder);
  7041. }
  7042. if (createQuadrilaterals) {
  7043. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  7044. }
  7045. }
  7046. _createContainer(ignoreBorder = false) {
  7047. const data = this.data,
  7048. page = this.page,
  7049. viewport = this.viewport;
  7050. const container = document.createElement("section");
  7051. let width = data.rect[2] - data.rect[0];
  7052. let height = data.rect[3] - data.rect[1];
  7053. container.setAttribute("data-annotation-id", data.id);
  7054. 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]]);
  7055. container.style.transform = `matrix(${viewport.transform.join(",")})`;
  7056. container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
  7057. if (!ignoreBorder && data.borderStyle.width > 0) {
  7058. container.style.borderWidth = `${data.borderStyle.width}px`;
  7059. if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
  7060. width -= 2 * data.borderStyle.width;
  7061. height -= 2 * data.borderStyle.width;
  7062. }
  7063. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  7064. const verticalRadius = data.borderStyle.verticalCornerRadius;
  7065. if (horizontalRadius > 0 || verticalRadius > 0) {
  7066. const radius = `${horizontalRadius}px / ${verticalRadius}px`;
  7067. container.style.borderRadius = radius;
  7068. }
  7069. switch (data.borderStyle.style) {
  7070. case _util.AnnotationBorderStyleType.SOLID:
  7071. container.style.borderStyle = "solid";
  7072. break;
  7073. case _util.AnnotationBorderStyleType.DASHED:
  7074. container.style.borderStyle = "dashed";
  7075. break;
  7076. case _util.AnnotationBorderStyleType.BEVELED:
  7077. (0, _util.warn)("Unimplemented border style: beveled");
  7078. break;
  7079. case _util.AnnotationBorderStyleType.INSET:
  7080. (0, _util.warn)("Unimplemented border style: inset");
  7081. break;
  7082. case _util.AnnotationBorderStyleType.UNDERLINE:
  7083. container.style.borderBottomStyle = "solid";
  7084. break;
  7085. default:
  7086. break;
  7087. }
  7088. if (data.color) {
  7089. container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  7090. } else {
  7091. container.style.borderWidth = 0;
  7092. }
  7093. }
  7094. container.style.left = `${rect[0]}px`;
  7095. container.style.top = `${rect[1]}px`;
  7096. container.style.width = `${width}px`;
  7097. container.style.height = `${height}px`;
  7098. return container;
  7099. }
  7100. _createQuadrilaterals(ignoreBorder = false) {
  7101. if (!this.data.quadPoints) {
  7102. return null;
  7103. }
  7104. const quadrilaterals = [];
  7105. const savedRect = this.data.rect;
  7106. for (const quadPoint of this.data.quadPoints) {
  7107. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  7108. quadrilaterals.push(this._createContainer(ignoreBorder));
  7109. }
  7110. this.data.rect = savedRect;
  7111. return quadrilaterals;
  7112. }
  7113. _createPopup(trigger, data) {
  7114. let container = this.container;
  7115. if (this.quadrilaterals) {
  7116. trigger = trigger || this.quadrilaterals;
  7117. container = this.quadrilaterals[0];
  7118. }
  7119. if (!trigger) {
  7120. trigger = document.createElement("div");
  7121. trigger.style.height = container.style.height;
  7122. trigger.style.width = container.style.width;
  7123. container.appendChild(trigger);
  7124. }
  7125. const popupElement = new PopupElement({
  7126. container,
  7127. trigger,
  7128. color: data.color,
  7129. title: data.title,
  7130. modificationDate: data.modificationDate,
  7131. contents: data.contents,
  7132. hideWrapper: true
  7133. });
  7134. const popup = popupElement.render();
  7135. popup.style.left = container.style.width;
  7136. container.appendChild(popup);
  7137. }
  7138. _renderQuadrilaterals(className) {
  7139. for (const quadrilateral of this.quadrilaterals) {
  7140. quadrilateral.className = className;
  7141. }
  7142. return this.quadrilaterals;
  7143. }
  7144. render() {
  7145. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  7146. }
  7147. }
  7148. class LinkAnnotationElement extends AnnotationElement {
  7149. constructor(parameters) {
  7150. const isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action || parameters.data.isTooltipOnly || parameters.data.actions && (parameters.data.actions.Action || parameters.data.actions["Mouse Up"] || parameters.data.actions["Mouse Down"]));
  7151. super(parameters, {
  7152. isRenderable,
  7153. createQuadrilaterals: true
  7154. });
  7155. }
  7156. render() {
  7157. const {
  7158. data,
  7159. linkService
  7160. } = this;
  7161. const link = document.createElement("a");
  7162. if (data.url) {
  7163. (0, _display_utils.addLinkAttributes)(link, {
  7164. url: data.url,
  7165. target: data.newWindow ? _display_utils.LinkTarget.BLANK : linkService.externalLinkTarget,
  7166. rel: linkService.externalLinkRel,
  7167. enabled: linkService.externalLinkEnabled
  7168. });
  7169. } else if (data.action) {
  7170. this._bindNamedAction(link, data.action);
  7171. } else if (data.dest) {
  7172. this._bindLink(link, data.dest);
  7173. } else if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  7174. this._bindJSAction(link, data);
  7175. } else {
  7176. this._bindLink(link, "");
  7177. }
  7178. if (this.quadrilaterals) {
  7179. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  7180. const linkElement = index === 0 ? link : link.cloneNode();
  7181. quadrilateral.appendChild(linkElement);
  7182. return quadrilateral;
  7183. });
  7184. }
  7185. this.container.className = "linkAnnotation";
  7186. this.container.appendChild(link);
  7187. return this.container;
  7188. }
  7189. _bindLink(link, destination) {
  7190. link.href = this.linkService.getDestinationHash(destination);
  7191. link.onclick = () => {
  7192. if (destination) {
  7193. this.linkService.goToDestination(destination);
  7194. }
  7195. return false;
  7196. };
  7197. if (destination || destination === "") {
  7198. link.className = "internalLink";
  7199. }
  7200. }
  7201. _bindNamedAction(link, action) {
  7202. link.href = this.linkService.getAnchorUrl("");
  7203. link.onclick = () => {
  7204. this.linkService.executeNamedAction(action);
  7205. return false;
  7206. };
  7207. link.className = "internalLink";
  7208. }
  7209. _bindJSAction(link, data) {
  7210. link.href = this.linkService.getAnchorUrl("");
  7211. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  7212. for (const name of Object.keys(data.actions)) {
  7213. const jsName = map.get(name);
  7214. if (!jsName) {
  7215. continue;
  7216. }
  7217. link[jsName] = () => {
  7218. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7219. source: this,
  7220. detail: {
  7221. id: data.id,
  7222. name
  7223. }
  7224. });
  7225. return false;
  7226. };
  7227. }
  7228. link.className = "internalLink";
  7229. }
  7230. }
  7231. class TextAnnotationElement extends AnnotationElement {
  7232. constructor(parameters) {
  7233. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  7234. super(parameters, {
  7235. isRenderable
  7236. });
  7237. }
  7238. render() {
  7239. this.container.className = "textAnnotation";
  7240. const image = document.createElement("img");
  7241. image.style.height = this.container.style.height;
  7242. image.style.width = this.container.style.width;
  7243. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  7244. image.alt = "[{{type}} Annotation]";
  7245. image.dataset.l10nId = "text_annotation_type";
  7246. image.dataset.l10nArgs = JSON.stringify({
  7247. type: this.data.name
  7248. });
  7249. if (!this.data.hasPopup) {
  7250. this._createPopup(image, this.data);
  7251. }
  7252. this.container.appendChild(image);
  7253. return this.container;
  7254. }
  7255. }
  7256. class WidgetAnnotationElement extends AnnotationElement {
  7257. render() {
  7258. if (this.data.alternativeText) {
  7259. this.container.title = this.data.alternativeText;
  7260. }
  7261. return this.container;
  7262. }
  7263. _getKeyModifier(event) {
  7264. return navigator.platform.includes("Win") && event.ctrlKey || navigator.platform.includes("Mac") && event.metaKey;
  7265. }
  7266. _setEventListener(element, baseName, eventName, valueGetter) {
  7267. if (baseName.includes("mouse")) {
  7268. element.addEventListener(baseName, event => {
  7269. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7270. source: this,
  7271. detail: {
  7272. id: this.data.id,
  7273. name: eventName,
  7274. value: valueGetter(event),
  7275. shift: event.shiftKey,
  7276. modifier: this._getKeyModifier(event)
  7277. }
  7278. });
  7279. });
  7280. } else {
  7281. element.addEventListener(baseName, event => {
  7282. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7283. source: this,
  7284. detail: {
  7285. id: this.data.id,
  7286. name: eventName,
  7287. value: event.target.checked
  7288. }
  7289. });
  7290. });
  7291. }
  7292. }
  7293. _setEventListeners(element, names, getter) {
  7294. for (const [baseName, eventName] of names) {
  7295. if (eventName === "Action" || this.data.actions?.[eventName]) {
  7296. this._setEventListener(element, baseName, eventName, getter);
  7297. }
  7298. }
  7299. }
  7300. _dispatchEventFromSandbox(actions, jsEvent) {
  7301. const setColor = (jsName, styleName, event) => {
  7302. const color = event.detail[jsName];
  7303. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  7304. };
  7305. const commonActions = {
  7306. display: event => {
  7307. const hidden = event.detail.display % 2 === 1;
  7308. event.target.style.visibility = hidden ? "hidden" : "visible";
  7309. this.annotationStorage.setValue(this.data.id, {
  7310. hidden,
  7311. print: event.detail.display === 0 || event.detail.display === 3
  7312. });
  7313. },
  7314. print: event => {
  7315. this.annotationStorage.setValue(this.data.id, {
  7316. print: event.detail.print
  7317. });
  7318. },
  7319. hidden: event => {
  7320. event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
  7321. this.annotationStorage.setValue(this.data.id, {
  7322. hidden: event.detail.hidden
  7323. });
  7324. },
  7325. focus: event => {
  7326. setTimeout(() => event.target.focus({
  7327. preventScroll: false
  7328. }), 0);
  7329. },
  7330. userName: event => {
  7331. event.target.title = event.detail.userName;
  7332. },
  7333. readonly: event => {
  7334. if (event.detail.readonly) {
  7335. event.target.setAttribute("readonly", "");
  7336. } else {
  7337. event.target.removeAttribute("readonly");
  7338. }
  7339. },
  7340. required: event => {
  7341. if (event.detail.required) {
  7342. event.target.setAttribute("required", "");
  7343. } else {
  7344. event.target.removeAttribute("required");
  7345. }
  7346. },
  7347. bgColor: event => {
  7348. setColor("bgColor", "backgroundColor", event);
  7349. },
  7350. fillColor: event => {
  7351. setColor("fillColor", "backgroundColor", event);
  7352. },
  7353. fgColor: event => {
  7354. setColor("fgColor", "color", event);
  7355. },
  7356. textColor: event => {
  7357. setColor("textColor", "color", event);
  7358. },
  7359. borderColor: event => {
  7360. setColor("borderColor", "borderColor", event);
  7361. },
  7362. strokeColor: event => {
  7363. setColor("strokeColor", "borderColor", event);
  7364. }
  7365. };
  7366. for (const name of Object.keys(jsEvent.detail)) {
  7367. const action = actions[name] || commonActions[name];
  7368. if (action) {
  7369. action(jsEvent);
  7370. }
  7371. }
  7372. }
  7373. }
  7374. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  7375. constructor(parameters) {
  7376. const isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  7377. super(parameters, {
  7378. isRenderable
  7379. });
  7380. }
  7381. setPropertyOnSiblings(base, key, value, keyInStorage) {
  7382. const storage = this.annotationStorage;
  7383. for (const element of document.getElementsByName(base.name)) {
  7384. if (element !== base) {
  7385. element[key] = value;
  7386. const data = Object.create(null);
  7387. data[keyInStorage] = value;
  7388. storage.setValue(element.getAttribute("id"), data);
  7389. }
  7390. }
  7391. }
  7392. render() {
  7393. const storage = this.annotationStorage;
  7394. const id = this.data.id;
  7395. this.container.className = "textWidgetAnnotation";
  7396. let element = null;
  7397. if (this.renderInteractiveForms) {
  7398. const storedData = storage.getValue(id, {
  7399. value: this.data.fieldValue,
  7400. valueAsString: this.data.fieldValue
  7401. });
  7402. const textContent = storedData.valueAsString || storedData.value || "";
  7403. const elementData = {
  7404. userValue: null,
  7405. formattedValue: null,
  7406. beforeInputSelectionRange: null,
  7407. beforeInputValue: null
  7408. };
  7409. if (this.data.multiLine) {
  7410. element = document.createElement("textarea");
  7411. element.textContent = textContent;
  7412. } else {
  7413. element = document.createElement("input");
  7414. element.type = "text";
  7415. element.setAttribute("value", textContent);
  7416. }
  7417. elementData.userValue = textContent;
  7418. element.setAttribute("id", id);
  7419. element.addEventListener("input", event => {
  7420. storage.setValue(id, {
  7421. value: event.target.value
  7422. });
  7423. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  7424. });
  7425. let blurListener = event => {
  7426. if (elementData.formattedValue) {
  7427. event.target.value = elementData.formattedValue;
  7428. }
  7429. event.target.scrollLeft = 0;
  7430. elementData.beforeInputSelectionRange = null;
  7431. };
  7432. if (this.enableScripting && this.hasJSActions) {
  7433. element.addEventListener("focus", event => {
  7434. if (elementData.userValue) {
  7435. event.target.value = elementData.userValue;
  7436. }
  7437. });
  7438. element.addEventListener("updatefromsandbox", jsEvent => {
  7439. const actions = {
  7440. value(event) {
  7441. elementData.userValue = event.detail.value || "";
  7442. storage.setValue(id, {
  7443. value: elementData.userValue.toString()
  7444. });
  7445. if (!elementData.formattedValue) {
  7446. event.target.value = elementData.userValue;
  7447. }
  7448. },
  7449. valueAsString(event) {
  7450. elementData.formattedValue = event.detail.valueAsString || "";
  7451. if (event.target !== document.activeElement) {
  7452. event.target.value = elementData.formattedValue;
  7453. }
  7454. storage.setValue(id, {
  7455. formattedValue: elementData.formattedValue
  7456. });
  7457. },
  7458. selRange(event) {
  7459. const [selStart, selEnd] = event.detail.selRange;
  7460. if (selStart >= 0 && selEnd < event.target.value.length) {
  7461. event.target.setSelectionRange(selStart, selEnd);
  7462. }
  7463. }
  7464. };
  7465. this._dispatchEventFromSandbox(actions, jsEvent);
  7466. });
  7467. element.addEventListener("keydown", event => {
  7468. elementData.beforeInputValue = event.target.value;
  7469. let commitKey = -1;
  7470. if (event.key === "Escape") {
  7471. commitKey = 0;
  7472. } else if (event.key === "Enter") {
  7473. commitKey = 2;
  7474. } else if (event.key === "Tab") {
  7475. commitKey = 3;
  7476. }
  7477. if (commitKey === -1) {
  7478. return;
  7479. }
  7480. elementData.userValue = event.target.value;
  7481. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7482. source: this,
  7483. detail: {
  7484. id,
  7485. name: "Keystroke",
  7486. value: event.target.value,
  7487. willCommit: true,
  7488. commitKey,
  7489. selStart: event.target.selectionStart,
  7490. selEnd: event.target.selectionEnd
  7491. }
  7492. });
  7493. });
  7494. const _blurListener = blurListener;
  7495. blurListener = null;
  7496. element.addEventListener("blur", event => {
  7497. if (this._mouseState.isDown) {
  7498. elementData.userValue = event.target.value;
  7499. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7500. source: this,
  7501. detail: {
  7502. id,
  7503. name: "Keystroke",
  7504. value: event.target.value,
  7505. willCommit: true,
  7506. commitKey: 1,
  7507. selStart: event.target.selectionStart,
  7508. selEnd: event.target.selectionEnd
  7509. }
  7510. });
  7511. }
  7512. _blurListener(event);
  7513. });
  7514. element.addEventListener("mousedown", event => {
  7515. elementData.beforeInputValue = event.target.value;
  7516. elementData.beforeInputSelectionRange = null;
  7517. });
  7518. element.addEventListener("keyup", event => {
  7519. if (event.target.selectionStart === event.target.selectionEnd) {
  7520. elementData.beforeInputSelectionRange = null;
  7521. }
  7522. });
  7523. element.addEventListener("select", event => {
  7524. elementData.beforeInputSelectionRange = [event.target.selectionStart, event.target.selectionEnd];
  7525. });
  7526. if (this.data.actions?.Keystroke) {
  7527. element.addEventListener("input", event => {
  7528. let selStart = -1;
  7529. let selEnd = -1;
  7530. if (elementData.beforeInputSelectionRange) {
  7531. [selStart, selEnd] = elementData.beforeInputSelectionRange;
  7532. }
  7533. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7534. source: this,
  7535. detail: {
  7536. id,
  7537. name: "Keystroke",
  7538. value: elementData.beforeInputValue,
  7539. change: event.data,
  7540. willCommit: false,
  7541. selStart,
  7542. selEnd
  7543. }
  7544. });
  7545. });
  7546. }
  7547. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  7548. }
  7549. if (blurListener) {
  7550. element.addEventListener("blur", blurListener);
  7551. }
  7552. element.disabled = this.data.readOnly;
  7553. element.name = this.data.fieldName;
  7554. if (this.data.maxLen !== null) {
  7555. element.maxLength = this.data.maxLen;
  7556. }
  7557. if (this.data.comb) {
  7558. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  7559. const combWidth = fieldWidth / this.data.maxLen;
  7560. element.classList.add("comb");
  7561. element.style.letterSpacing = `calc(${combWidth}px - 1ch)`;
  7562. }
  7563. } else {
  7564. element = document.createElement("div");
  7565. element.textContent = this.data.fieldValue;
  7566. element.style.verticalAlign = "middle";
  7567. element.style.display = "table-cell";
  7568. }
  7569. this._setTextStyle(element);
  7570. this.container.appendChild(element);
  7571. return this.container;
  7572. }
  7573. _setTextStyle(element) {
  7574. const TEXT_ALIGNMENT = ["left", "center", "right"];
  7575. const {
  7576. fontSize,
  7577. fontColor
  7578. } = this.data.defaultAppearanceData;
  7579. const style = element.style;
  7580. if (fontSize) {
  7581. style.fontSize = `${fontSize}px`;
  7582. }
  7583. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  7584. if (this.data.textAlignment !== null) {
  7585. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  7586. }
  7587. }
  7588. }
  7589. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  7590. constructor(parameters) {
  7591. super(parameters, {
  7592. isRenderable: parameters.renderInteractiveForms
  7593. });
  7594. }
  7595. render() {
  7596. const storage = this.annotationStorage;
  7597. const data = this.data;
  7598. const id = data.id;
  7599. let value = storage.getValue(id, {
  7600. value: data.fieldValue && (data.exportValue && data.exportValue === data.fieldValue || !data.exportValue && data.fieldValue !== "Off")
  7601. }).value;
  7602. if (typeof value === "string") {
  7603. value = value !== "Off";
  7604. storage.setValue(id, {
  7605. value
  7606. });
  7607. }
  7608. this.container.className = "buttonWidgetAnnotation checkBox";
  7609. const element = document.createElement("input");
  7610. element.disabled = data.readOnly;
  7611. element.type = "checkbox";
  7612. element.name = this.data.fieldName;
  7613. if (value) {
  7614. element.setAttribute("checked", true);
  7615. }
  7616. element.setAttribute("id", id);
  7617. element.addEventListener("change", function (event) {
  7618. const name = event.target.name;
  7619. for (const checkbox of document.getElementsByName(name)) {
  7620. if (checkbox !== event.target) {
  7621. checkbox.checked = false;
  7622. storage.setValue(checkbox.parentNode.getAttribute("data-annotation-id"), {
  7623. value: false
  7624. });
  7625. }
  7626. }
  7627. storage.setValue(id, {
  7628. value: event.target.checked
  7629. });
  7630. });
  7631. if (this.enableScripting && this.hasJSActions) {
  7632. element.addEventListener("updatefromsandbox", jsEvent => {
  7633. const actions = {
  7634. value(event) {
  7635. event.target.checked = event.detail.value !== "Off";
  7636. storage.setValue(id, {
  7637. value: event.target.checked
  7638. });
  7639. }
  7640. };
  7641. this._dispatchEventFromSandbox(actions, jsEvent);
  7642. });
  7643. 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);
  7644. }
  7645. this.container.appendChild(element);
  7646. return this.container;
  7647. }
  7648. }
  7649. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  7650. constructor(parameters) {
  7651. super(parameters, {
  7652. isRenderable: parameters.renderInteractiveForms
  7653. });
  7654. }
  7655. render() {
  7656. this.container.className = "buttonWidgetAnnotation radioButton";
  7657. const storage = this.annotationStorage;
  7658. const data = this.data;
  7659. const id = data.id;
  7660. let value = storage.getValue(id, {
  7661. value: data.fieldValue === data.buttonValue
  7662. }).value;
  7663. if (typeof value === "string") {
  7664. value = value !== data.buttonValue;
  7665. storage.setValue(id, {
  7666. value
  7667. });
  7668. }
  7669. const element = document.createElement("input");
  7670. element.disabled = data.readOnly;
  7671. element.type = "radio";
  7672. element.name = data.fieldName;
  7673. if (value) {
  7674. element.setAttribute("checked", true);
  7675. }
  7676. element.setAttribute("id", id);
  7677. element.addEventListener("change", function (event) {
  7678. const {
  7679. target
  7680. } = event;
  7681. for (const radio of document.getElementsByName(target.name)) {
  7682. if (radio !== target) {
  7683. storage.setValue(radio.getAttribute("id"), {
  7684. value: false
  7685. });
  7686. }
  7687. }
  7688. storage.setValue(id, {
  7689. value: target.checked
  7690. });
  7691. });
  7692. if (this.enableScripting && this.hasJSActions) {
  7693. const pdfButtonValue = data.buttonValue;
  7694. element.addEventListener("updatefromsandbox", jsEvent => {
  7695. const actions = {
  7696. value(event) {
  7697. const checked = pdfButtonValue === event.detail.value;
  7698. for (const radio of document.getElementsByName(event.target.name)) {
  7699. const radioId = radio.getAttribute("id");
  7700. radio.checked = radioId === id && checked;
  7701. storage.setValue(radioId, {
  7702. value: radio.checked
  7703. });
  7704. }
  7705. }
  7706. };
  7707. this._dispatchEventFromSandbox(actions, jsEvent);
  7708. });
  7709. 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);
  7710. }
  7711. this.container.appendChild(element);
  7712. return this.container;
  7713. }
  7714. }
  7715. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  7716. render() {
  7717. const container = super.render();
  7718. container.className = "buttonWidgetAnnotation pushButton";
  7719. if (this.data.alternativeText) {
  7720. container.title = this.data.alternativeText;
  7721. }
  7722. return container;
  7723. }
  7724. }
  7725. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  7726. constructor(parameters) {
  7727. super(parameters, {
  7728. isRenderable: parameters.renderInteractiveForms
  7729. });
  7730. }
  7731. render() {
  7732. this.container.className = "choiceWidgetAnnotation";
  7733. const storage = this.annotationStorage;
  7734. const id = this.data.id;
  7735. storage.getValue(id, {
  7736. value: this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : undefined
  7737. });
  7738. const selectElement = document.createElement("select");
  7739. selectElement.disabled = this.data.readOnly;
  7740. selectElement.name = this.data.fieldName;
  7741. selectElement.setAttribute("id", id);
  7742. if (!this.data.combo) {
  7743. selectElement.size = this.data.options.length;
  7744. if (this.data.multiSelect) {
  7745. selectElement.multiple = true;
  7746. }
  7747. }
  7748. for (const option of this.data.options) {
  7749. const optionElement = document.createElement("option");
  7750. optionElement.textContent = option.displayValue;
  7751. optionElement.value = option.exportValue;
  7752. if (this.data.fieldValue.includes(option.exportValue)) {
  7753. optionElement.setAttribute("selected", true);
  7754. }
  7755. selectElement.appendChild(optionElement);
  7756. }
  7757. const getValue = (event, isExport) => {
  7758. const name = isExport ? "value" : "textContent";
  7759. const options = event.target.options;
  7760. if (!event.target.multiple) {
  7761. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  7762. }
  7763. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  7764. };
  7765. const getItems = event => {
  7766. const options = event.target.options;
  7767. return Array.prototype.map.call(options, option => {
  7768. return {
  7769. displayValue: option.textContent,
  7770. exportValue: option.value
  7771. };
  7772. });
  7773. };
  7774. if (this.enableScripting && this.hasJSActions) {
  7775. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  7776. const actions = {
  7777. value(event) {
  7778. const options = selectElement.options;
  7779. const value = event.detail.value;
  7780. const values = new Set(Array.isArray(value) ? value : [value]);
  7781. Array.prototype.forEach.call(options, option => {
  7782. option.selected = values.has(option.value);
  7783. });
  7784. storage.setValue(id, {
  7785. value: getValue(event, true)
  7786. });
  7787. },
  7788. multipleSelection(event) {
  7789. selectElement.multiple = true;
  7790. },
  7791. remove(event) {
  7792. const options = selectElement.options;
  7793. const index = event.detail.remove;
  7794. options[index].selected = false;
  7795. selectElement.remove(index);
  7796. if (options.length > 0) {
  7797. const i = Array.prototype.findIndex.call(options, option => option.selected);
  7798. if (i === -1) {
  7799. options[0].selected = true;
  7800. }
  7801. }
  7802. storage.setValue(id, {
  7803. value: getValue(event, true),
  7804. items: getItems(event)
  7805. });
  7806. },
  7807. clear(event) {
  7808. while (selectElement.length !== 0) {
  7809. selectElement.remove(0);
  7810. }
  7811. storage.setValue(id, {
  7812. value: null,
  7813. items: []
  7814. });
  7815. },
  7816. insert(event) {
  7817. const {
  7818. index,
  7819. displayValue,
  7820. exportValue
  7821. } = event.detail.insert;
  7822. const optionElement = document.createElement("option");
  7823. optionElement.textContent = displayValue;
  7824. optionElement.value = exportValue;
  7825. selectElement.insertBefore(optionElement, selectElement.children[index]);
  7826. storage.setValue(id, {
  7827. value: getValue(event, true),
  7828. items: getItems(event)
  7829. });
  7830. },
  7831. items(event) {
  7832. const {
  7833. items
  7834. } = event.detail;
  7835. while (selectElement.length !== 0) {
  7836. selectElement.remove(0);
  7837. }
  7838. for (const item of items) {
  7839. const {
  7840. displayValue,
  7841. exportValue
  7842. } = item;
  7843. const optionElement = document.createElement("option");
  7844. optionElement.textContent = displayValue;
  7845. optionElement.value = exportValue;
  7846. selectElement.appendChild(optionElement);
  7847. }
  7848. if (selectElement.options.length > 0) {
  7849. selectElement.options[0].selected = true;
  7850. }
  7851. storage.setValue(id, {
  7852. value: getValue(event, true),
  7853. items: getItems(event)
  7854. });
  7855. },
  7856. indices(event) {
  7857. const indices = new Set(event.detail.indices);
  7858. const options = event.target.options;
  7859. Array.prototype.forEach.call(options, (option, i) => {
  7860. option.selected = indices.has(i);
  7861. });
  7862. storage.setValue(id, {
  7863. value: getValue(event, true)
  7864. });
  7865. },
  7866. editable(event) {
  7867. event.target.disabled = !event.detail.editable;
  7868. }
  7869. };
  7870. this._dispatchEventFromSandbox(actions, jsEvent);
  7871. });
  7872. selectElement.addEventListener("input", event => {
  7873. const exportValue = getValue(event, true);
  7874. const value = getValue(event, false);
  7875. storage.setValue(id, {
  7876. value: exportValue
  7877. });
  7878. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7879. source: this,
  7880. detail: {
  7881. id,
  7882. name: "Keystroke",
  7883. value,
  7884. changeEx: exportValue,
  7885. willCommit: true,
  7886. commitKey: 1,
  7887. keyDown: false
  7888. }
  7889. });
  7890. });
  7891. 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);
  7892. } else {
  7893. selectElement.addEventListener("input", function (event) {
  7894. storage.setValue(id, {
  7895. value: getValue(event)
  7896. });
  7897. });
  7898. }
  7899. this.container.appendChild(selectElement);
  7900. return this.container;
  7901. }
  7902. }
  7903. class PopupAnnotationElement extends AnnotationElement {
  7904. constructor(parameters) {
  7905. const isRenderable = !!(parameters.data.title || parameters.data.contents);
  7906. super(parameters, {
  7907. isRenderable
  7908. });
  7909. }
  7910. render() {
  7911. const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"];
  7912. this.container.className = "popupAnnotation";
  7913. if (IGNORE_TYPES.includes(this.data.parentType)) {
  7914. return this.container;
  7915. }
  7916. const selector = `[data-annotation-id="${this.data.parentId}"]`;
  7917. const parentElements = this.layer.querySelectorAll(selector);
  7918. if (parentElements.length === 0) {
  7919. return this.container;
  7920. }
  7921. const popup = new PopupElement({
  7922. container: this.container,
  7923. trigger: Array.from(parentElements),
  7924. color: this.data.color,
  7925. title: this.data.title,
  7926. modificationDate: this.data.modificationDate,
  7927. contents: this.data.contents
  7928. });
  7929. const page = this.page;
  7930. 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]]);
  7931. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  7932. const popupTop = rect[1];
  7933. this.container.style.transformOrigin = `${-popupLeft}px ${-popupTop}px`;
  7934. this.container.style.left = `${popupLeft}px`;
  7935. this.container.style.top = `${popupTop}px`;
  7936. this.container.appendChild(popup.render());
  7937. return this.container;
  7938. }
  7939. }
  7940. class PopupElement {
  7941. constructor(parameters) {
  7942. this.container = parameters.container;
  7943. this.trigger = parameters.trigger;
  7944. this.color = parameters.color;
  7945. this.title = parameters.title;
  7946. this.modificationDate = parameters.modificationDate;
  7947. this.contents = parameters.contents;
  7948. this.hideWrapper = parameters.hideWrapper || false;
  7949. this.pinned = false;
  7950. }
  7951. render() {
  7952. const BACKGROUND_ENLIGHT = 0.7;
  7953. const wrapper = document.createElement("div");
  7954. wrapper.className = "popupWrapper";
  7955. this.hideElement = this.hideWrapper ? wrapper : this.container;
  7956. this.hideElement.hidden = true;
  7957. const popup = document.createElement("div");
  7958. popup.className = "popup";
  7959. const color = this.color;
  7960. if (color) {
  7961. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  7962. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  7963. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  7964. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  7965. }
  7966. const title = document.createElement("h1");
  7967. title.textContent = this.title;
  7968. popup.appendChild(title);
  7969. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  7970. if (dateObject) {
  7971. const modificationDate = document.createElement("span");
  7972. modificationDate.textContent = "{{date}}, {{time}}";
  7973. modificationDate.dataset.l10nId = "annotation_date_string";
  7974. modificationDate.dataset.l10nArgs = JSON.stringify({
  7975. date: dateObject.toLocaleDateString(),
  7976. time: dateObject.toLocaleTimeString()
  7977. });
  7978. popup.appendChild(modificationDate);
  7979. }
  7980. const contents = this._formatContents(this.contents);
  7981. popup.appendChild(contents);
  7982. if (!Array.isArray(this.trigger)) {
  7983. this.trigger = [this.trigger];
  7984. }
  7985. for (const element of this.trigger) {
  7986. element.addEventListener("click", this._toggle.bind(this));
  7987. element.addEventListener("mouseover", this._show.bind(this, false));
  7988. element.addEventListener("mouseout", this._hide.bind(this, false));
  7989. }
  7990. popup.addEventListener("click", this._hide.bind(this, true));
  7991. wrapper.appendChild(popup);
  7992. return wrapper;
  7993. }
  7994. _formatContents(contents) {
  7995. const p = document.createElement("p");
  7996. const lines = contents.split(/(?:\r\n?|\n)/);
  7997. for (let i = 0, ii = lines.length; i < ii; ++i) {
  7998. const line = lines[i];
  7999. p.appendChild(document.createTextNode(line));
  8000. if (i < ii - 1) {
  8001. p.appendChild(document.createElement("br"));
  8002. }
  8003. }
  8004. return p;
  8005. }
  8006. _toggle() {
  8007. if (this.pinned) {
  8008. this._hide(true);
  8009. } else {
  8010. this._show(true);
  8011. }
  8012. }
  8013. _show(pin = false) {
  8014. if (pin) {
  8015. this.pinned = true;
  8016. }
  8017. if (this.hideElement.hidden) {
  8018. this.hideElement.hidden = false;
  8019. this.container.style.zIndex += 1;
  8020. }
  8021. }
  8022. _hide(unpin = true) {
  8023. if (unpin) {
  8024. this.pinned = false;
  8025. }
  8026. if (!this.hideElement.hidden && !this.pinned) {
  8027. this.hideElement.hidden = true;
  8028. this.container.style.zIndex -= 1;
  8029. }
  8030. }
  8031. }
  8032. class FreeTextAnnotationElement extends AnnotationElement {
  8033. constructor(parameters) {
  8034. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8035. super(parameters, {
  8036. isRenderable,
  8037. ignoreBorder: true
  8038. });
  8039. }
  8040. render() {
  8041. this.container.className = "freeTextAnnotation";
  8042. if (!this.data.hasPopup) {
  8043. this._createPopup(null, this.data);
  8044. }
  8045. return this.container;
  8046. }
  8047. }
  8048. class LineAnnotationElement extends AnnotationElement {
  8049. constructor(parameters) {
  8050. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8051. super(parameters, {
  8052. isRenderable,
  8053. ignoreBorder: true
  8054. });
  8055. }
  8056. render() {
  8057. this.container.className = "lineAnnotation";
  8058. const data = this.data;
  8059. const width = data.rect[2] - data.rect[0];
  8060. const height = data.rect[3] - data.rect[1];
  8061. const svg = this.svgFactory.create(width, height);
  8062. const line = this.svgFactory.createElement("svg:line");
  8063. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  8064. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  8065. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  8066. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  8067. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  8068. line.setAttribute("stroke", "transparent");
  8069. svg.appendChild(line);
  8070. this.container.append(svg);
  8071. this._createPopup(line, data);
  8072. return this.container;
  8073. }
  8074. }
  8075. class SquareAnnotationElement extends AnnotationElement {
  8076. constructor(parameters) {
  8077. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8078. super(parameters, {
  8079. isRenderable,
  8080. ignoreBorder: true
  8081. });
  8082. }
  8083. render() {
  8084. this.container.className = "squareAnnotation";
  8085. const data = this.data;
  8086. const width = data.rect[2] - data.rect[0];
  8087. const height = data.rect[3] - data.rect[1];
  8088. const svg = this.svgFactory.create(width, height);
  8089. const borderWidth = data.borderStyle.width;
  8090. const square = this.svgFactory.createElement("svg:rect");
  8091. square.setAttribute("x", borderWidth / 2);
  8092. square.setAttribute("y", borderWidth / 2);
  8093. square.setAttribute("width", width - borderWidth);
  8094. square.setAttribute("height", height - borderWidth);
  8095. square.setAttribute("stroke-width", borderWidth || 1);
  8096. square.setAttribute("stroke", "transparent");
  8097. square.setAttribute("fill", "none");
  8098. svg.appendChild(square);
  8099. this.container.append(svg);
  8100. this._createPopup(square, data);
  8101. return this.container;
  8102. }
  8103. }
  8104. class CircleAnnotationElement extends AnnotationElement {
  8105. constructor(parameters) {
  8106. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8107. super(parameters, {
  8108. isRenderable,
  8109. ignoreBorder: true
  8110. });
  8111. }
  8112. render() {
  8113. this.container.className = "circleAnnotation";
  8114. const data = this.data;
  8115. const width = data.rect[2] - data.rect[0];
  8116. const height = data.rect[3] - data.rect[1];
  8117. const svg = this.svgFactory.create(width, height);
  8118. const borderWidth = data.borderStyle.width;
  8119. const circle = this.svgFactory.createElement("svg:ellipse");
  8120. circle.setAttribute("cx", width / 2);
  8121. circle.setAttribute("cy", height / 2);
  8122. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  8123. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  8124. circle.setAttribute("stroke-width", borderWidth || 1);
  8125. circle.setAttribute("stroke", "transparent");
  8126. circle.setAttribute("fill", "none");
  8127. svg.appendChild(circle);
  8128. this.container.append(svg);
  8129. this._createPopup(circle, data);
  8130. return this.container;
  8131. }
  8132. }
  8133. class PolylineAnnotationElement extends AnnotationElement {
  8134. constructor(parameters) {
  8135. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8136. super(parameters, {
  8137. isRenderable,
  8138. ignoreBorder: true
  8139. });
  8140. this.containerClassName = "polylineAnnotation";
  8141. this.svgElementName = "svg:polyline";
  8142. }
  8143. render() {
  8144. this.container.className = this.containerClassName;
  8145. const data = this.data;
  8146. const width = data.rect[2] - data.rect[0];
  8147. const height = data.rect[3] - data.rect[1];
  8148. const svg = this.svgFactory.create(width, height);
  8149. let points = [];
  8150. for (const coordinate of data.vertices) {
  8151. const x = coordinate.x - data.rect[0];
  8152. const y = data.rect[3] - coordinate.y;
  8153. points.push(x + "," + y);
  8154. }
  8155. points = points.join(" ");
  8156. const polyline = this.svgFactory.createElement(this.svgElementName);
  8157. polyline.setAttribute("points", points);
  8158. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  8159. polyline.setAttribute("stroke", "transparent");
  8160. polyline.setAttribute("fill", "none");
  8161. svg.appendChild(polyline);
  8162. this.container.append(svg);
  8163. this._createPopup(polyline, data);
  8164. return this.container;
  8165. }
  8166. }
  8167. class PolygonAnnotationElement extends PolylineAnnotationElement {
  8168. constructor(parameters) {
  8169. super(parameters);
  8170. this.containerClassName = "polygonAnnotation";
  8171. this.svgElementName = "svg:polygon";
  8172. }
  8173. }
  8174. class CaretAnnotationElement extends AnnotationElement {
  8175. constructor(parameters) {
  8176. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8177. super(parameters, {
  8178. isRenderable,
  8179. ignoreBorder: true
  8180. });
  8181. }
  8182. render() {
  8183. this.container.className = "caretAnnotation";
  8184. if (!this.data.hasPopup) {
  8185. this._createPopup(null, this.data);
  8186. }
  8187. return this.container;
  8188. }
  8189. }
  8190. class InkAnnotationElement extends AnnotationElement {
  8191. constructor(parameters) {
  8192. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8193. super(parameters, {
  8194. isRenderable,
  8195. ignoreBorder: true
  8196. });
  8197. this.containerClassName = "inkAnnotation";
  8198. this.svgElementName = "svg:polyline";
  8199. }
  8200. render() {
  8201. this.container.className = this.containerClassName;
  8202. const data = this.data;
  8203. const width = data.rect[2] - data.rect[0];
  8204. const height = data.rect[3] - data.rect[1];
  8205. const svg = this.svgFactory.create(width, height);
  8206. for (const inkList of data.inkLists) {
  8207. let points = [];
  8208. for (const coordinate of inkList) {
  8209. const x = coordinate.x - data.rect[0];
  8210. const y = data.rect[3] - coordinate.y;
  8211. points.push(`${x},${y}`);
  8212. }
  8213. points = points.join(" ");
  8214. const polyline = this.svgFactory.createElement(this.svgElementName);
  8215. polyline.setAttribute("points", points);
  8216. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  8217. polyline.setAttribute("stroke", "transparent");
  8218. polyline.setAttribute("fill", "none");
  8219. this._createPopup(polyline, data);
  8220. svg.appendChild(polyline);
  8221. }
  8222. this.container.append(svg);
  8223. return this.container;
  8224. }
  8225. }
  8226. class HighlightAnnotationElement extends AnnotationElement {
  8227. constructor(parameters) {
  8228. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8229. super(parameters, {
  8230. isRenderable,
  8231. ignoreBorder: true,
  8232. createQuadrilaterals: true
  8233. });
  8234. }
  8235. render() {
  8236. if (!this.data.hasPopup) {
  8237. this._createPopup(null, this.data);
  8238. }
  8239. if (this.quadrilaterals) {
  8240. return this._renderQuadrilaterals("highlightAnnotation");
  8241. }
  8242. this.container.className = "highlightAnnotation";
  8243. return this.container;
  8244. }
  8245. }
  8246. class UnderlineAnnotationElement extends AnnotationElement {
  8247. constructor(parameters) {
  8248. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8249. super(parameters, {
  8250. isRenderable,
  8251. ignoreBorder: true,
  8252. createQuadrilaterals: true
  8253. });
  8254. }
  8255. render() {
  8256. if (!this.data.hasPopup) {
  8257. this._createPopup(null, this.data);
  8258. }
  8259. if (this.quadrilaterals) {
  8260. return this._renderQuadrilaterals("underlineAnnotation");
  8261. }
  8262. this.container.className = "underlineAnnotation";
  8263. return this.container;
  8264. }
  8265. }
  8266. class SquigglyAnnotationElement extends AnnotationElement {
  8267. constructor(parameters) {
  8268. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8269. super(parameters, {
  8270. isRenderable,
  8271. ignoreBorder: true,
  8272. createQuadrilaterals: true
  8273. });
  8274. }
  8275. render() {
  8276. if (!this.data.hasPopup) {
  8277. this._createPopup(null, this.data);
  8278. }
  8279. if (this.quadrilaterals) {
  8280. return this._renderQuadrilaterals("squigglyAnnotation");
  8281. }
  8282. this.container.className = "squigglyAnnotation";
  8283. return this.container;
  8284. }
  8285. }
  8286. class StrikeOutAnnotationElement extends AnnotationElement {
  8287. constructor(parameters) {
  8288. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8289. super(parameters, {
  8290. isRenderable,
  8291. ignoreBorder: true,
  8292. createQuadrilaterals: true
  8293. });
  8294. }
  8295. render() {
  8296. if (!this.data.hasPopup) {
  8297. this._createPopup(null, this.data);
  8298. }
  8299. if (this.quadrilaterals) {
  8300. return this._renderQuadrilaterals("strikeoutAnnotation");
  8301. }
  8302. this.container.className = "strikeoutAnnotation";
  8303. return this.container;
  8304. }
  8305. }
  8306. class StampAnnotationElement extends AnnotationElement {
  8307. constructor(parameters) {
  8308. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8309. super(parameters, {
  8310. isRenderable,
  8311. ignoreBorder: true
  8312. });
  8313. }
  8314. render() {
  8315. this.container.className = "stampAnnotation";
  8316. if (!this.data.hasPopup) {
  8317. this._createPopup(null, this.data);
  8318. }
  8319. return this.container;
  8320. }
  8321. }
  8322. class FileAttachmentAnnotationElement extends AnnotationElement {
  8323. constructor(parameters) {
  8324. super(parameters, {
  8325. isRenderable: true
  8326. });
  8327. const {
  8328. filename,
  8329. content
  8330. } = this.data.file;
  8331. this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
  8332. this.content = content;
  8333. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  8334. source: this,
  8335. id: (0, _util.stringToPDFString)(filename),
  8336. filename,
  8337. content
  8338. });
  8339. }
  8340. render() {
  8341. this.container.className = "fileAttachmentAnnotation";
  8342. const trigger = document.createElement("div");
  8343. trigger.style.height = this.container.style.height;
  8344. trigger.style.width = this.container.style.width;
  8345. trigger.addEventListener("dblclick", this._download.bind(this));
  8346. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  8347. this._createPopup(trigger, this.data);
  8348. }
  8349. this.container.appendChild(trigger);
  8350. return this.container;
  8351. }
  8352. _download() {
  8353. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  8354. }
  8355. }
  8356. class AnnotationLayer {
  8357. static render(parameters) {
  8358. const sortedAnnotations = [],
  8359. popupAnnotations = [];
  8360. for (const data of parameters.annotations) {
  8361. if (!data) {
  8362. continue;
  8363. }
  8364. if (data.annotationType === _util.AnnotationType.POPUP) {
  8365. popupAnnotations.push(data);
  8366. continue;
  8367. }
  8368. sortedAnnotations.push(data);
  8369. }
  8370. if (popupAnnotations.length) {
  8371. sortedAnnotations.push(...popupAnnotations);
  8372. }
  8373. for (const data of sortedAnnotations) {
  8374. const element = AnnotationElementFactory.create({
  8375. data,
  8376. layer: parameters.div,
  8377. page: parameters.page,
  8378. viewport: parameters.viewport,
  8379. linkService: parameters.linkService,
  8380. downloadManager: parameters.downloadManager,
  8381. imageResourcesPath: parameters.imageResourcesPath || "",
  8382. renderInteractiveForms: parameters.renderInteractiveForms !== false,
  8383. svgFactory: new _display_utils.DOMSVGFactory(),
  8384. annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
  8385. enableScripting: parameters.enableScripting,
  8386. hasJSActions: parameters.hasJSActions,
  8387. mouseState: parameters.mouseState || {
  8388. isDown: false
  8389. }
  8390. });
  8391. if (element.isRenderable) {
  8392. const rendered = element.render();
  8393. if (data.hidden) {
  8394. rendered.style.visibility = "hidden";
  8395. }
  8396. if (Array.isArray(rendered)) {
  8397. for (const renderedElement of rendered) {
  8398. parameters.div.appendChild(renderedElement);
  8399. }
  8400. } else {
  8401. if (element instanceof PopupAnnotationElement) {
  8402. parameters.div.prepend(rendered);
  8403. } else {
  8404. parameters.div.appendChild(rendered);
  8405. }
  8406. }
  8407. }
  8408. }
  8409. }
  8410. static update(parameters) {
  8411. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  8412. for (const data of parameters.annotations) {
  8413. const elements = parameters.div.querySelectorAll(`[data-annotation-id="${data.id}"]`);
  8414. if (elements) {
  8415. for (const element of elements) {
  8416. element.style.transform = transform;
  8417. }
  8418. }
  8419. }
  8420. parameters.div.hidden = false;
  8421. }
  8422. }
  8423. exports.AnnotationLayer = AnnotationLayer;
  8424. /***/ }),
  8425. /* 18 */
  8426. /***/ ((__unused_webpack_module, exports) => {
  8427. Object.defineProperty(exports, "__esModule", ({
  8428. value: true
  8429. }));
  8430. exports.ColorConverters = void 0;
  8431. function makeColorComp(n) {
  8432. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  8433. }
  8434. class ColorConverters {
  8435. static CMYK_G([c, y, m, k]) {
  8436. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  8437. }
  8438. static G_CMYK([g]) {
  8439. return ["CMYK", 0, 0, 0, 1 - g];
  8440. }
  8441. static G_RGB([g]) {
  8442. return ["RGB", g, g, g];
  8443. }
  8444. static G_HTML([g]) {
  8445. const G = makeColorComp(g);
  8446. return `#${G}${G}${G}`;
  8447. }
  8448. static RGB_G([r, g, b]) {
  8449. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  8450. }
  8451. static RGB_HTML([r, g, b]) {
  8452. const R = makeColorComp(r);
  8453. const G = makeColorComp(g);
  8454. const B = makeColorComp(b);
  8455. return `#${R}${G}${B}`;
  8456. }
  8457. static T_HTML() {
  8458. return "#00000000";
  8459. }
  8460. static CMYK_RGB([c, y, m, k]) {
  8461. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  8462. }
  8463. static CMYK_HTML(components) {
  8464. return this.RGB_HTML(this.CMYK_RGB(components));
  8465. }
  8466. static RGB_CMYK([r, g, b]) {
  8467. const c = 1 - r;
  8468. const m = 1 - g;
  8469. const y = 1 - b;
  8470. const k = Math.min(c, m, y);
  8471. return ["CMYK", c, m, y, k];
  8472. }
  8473. }
  8474. exports.ColorConverters = ColorConverters;
  8475. /***/ }),
  8476. /* 19 */
  8477. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8478. Object.defineProperty(exports, "__esModule", ({
  8479. value: true
  8480. }));
  8481. exports.renderTextLayer = renderTextLayer;
  8482. var _util = __w_pdfjs_require__(2);
  8483. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  8484. const DEFAULT_FONT_SIZE = 30;
  8485. const DEFAULT_FONT_ASCENT = 0.8;
  8486. const ascentCache = new Map();
  8487. const AllWhitespaceRegexp = /^\s+$/g;
  8488. function getAscent(fontFamily, ctx) {
  8489. const cachedAscent = ascentCache.get(fontFamily);
  8490. if (cachedAscent) {
  8491. return cachedAscent;
  8492. }
  8493. ctx.save();
  8494. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  8495. const metrics = ctx.measureText("");
  8496. let ascent = metrics.fontBoundingBoxAscent;
  8497. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  8498. if (ascent) {
  8499. ctx.restore();
  8500. const ratio = ascent / (ascent + descent);
  8501. ascentCache.set(fontFamily, ratio);
  8502. return ratio;
  8503. }
  8504. ctx.strokeStyle = "red";
  8505. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8506. ctx.strokeText("g", 0, 0);
  8507. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8508. descent = 0;
  8509. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  8510. if (pixels[i] > 0) {
  8511. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  8512. break;
  8513. }
  8514. }
  8515. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8516. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  8517. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8518. ascent = 0;
  8519. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  8520. if (pixels[i] > 0) {
  8521. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  8522. break;
  8523. }
  8524. }
  8525. ctx.restore();
  8526. if (ascent) {
  8527. const ratio = ascent / (ascent + descent);
  8528. ascentCache.set(fontFamily, ratio);
  8529. return ratio;
  8530. }
  8531. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  8532. return DEFAULT_FONT_ASCENT;
  8533. }
  8534. function appendText(task, geom, styles, ctx) {
  8535. const textDiv = document.createElement("span");
  8536. const textDivProperties = {
  8537. angle: 0,
  8538. canvasWidth: 0,
  8539. hasText: geom.str !== "",
  8540. hasEOL: geom.hasEOL,
  8541. originalTransform: null,
  8542. paddingBottom: 0,
  8543. paddingLeft: 0,
  8544. paddingRight: 0,
  8545. paddingTop: 0,
  8546. scale: 1
  8547. };
  8548. task._textDivs.push(textDiv);
  8549. const tx = _util.Util.transform(task._viewport.transform, geom.transform);
  8550. let angle = Math.atan2(tx[1], tx[0]);
  8551. const style = styles[geom.fontName];
  8552. if (style.vertical) {
  8553. angle += Math.PI / 2;
  8554. }
  8555. const fontHeight = Math.hypot(tx[2], tx[3]);
  8556. const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
  8557. let left, top;
  8558. if (angle === 0) {
  8559. left = tx[4];
  8560. top = tx[5] - fontAscent;
  8561. } else {
  8562. left = tx[4] + fontAscent * Math.sin(angle);
  8563. top = tx[5] - fontAscent * Math.cos(angle);
  8564. }
  8565. textDiv.style.left = `${left}px`;
  8566. textDiv.style.top = `${top}px`;
  8567. textDiv.style.fontSize = `${fontHeight}px`;
  8568. textDiv.style.fontFamily = style.fontFamily;
  8569. textDiv.setAttribute("role", "presentation");
  8570. textDiv.textContent = geom.str;
  8571. textDiv.dir = geom.dir;
  8572. if (task._fontInspectorEnabled) {
  8573. textDiv.dataset.fontName = geom.fontName;
  8574. }
  8575. if (angle !== 0) {
  8576. textDivProperties.angle = angle * (180 / Math.PI);
  8577. }
  8578. let shouldScaleText = false;
  8579. if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) {
  8580. shouldScaleText = true;
  8581. } else if (geom.transform[0] !== geom.transform[3]) {
  8582. const absScaleX = Math.abs(geom.transform[0]),
  8583. absScaleY = Math.abs(geom.transform[3]);
  8584. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  8585. shouldScaleText = true;
  8586. }
  8587. }
  8588. if (shouldScaleText) {
  8589. if (style.vertical) {
  8590. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  8591. } else {
  8592. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  8593. }
  8594. }
  8595. task._textDivProperties.set(textDiv, textDivProperties);
  8596. if (task._textContentStream) {
  8597. task._layoutText(textDiv);
  8598. }
  8599. if (task._enhanceTextSelection && textDivProperties.hasText) {
  8600. let angleCos = 1,
  8601. angleSin = 0;
  8602. if (angle !== 0) {
  8603. angleCos = Math.cos(angle);
  8604. angleSin = Math.sin(angle);
  8605. }
  8606. const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  8607. const divHeight = fontHeight;
  8608. let m, b;
  8609. if (angle !== 0) {
  8610. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  8611. b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  8612. } else {
  8613. b = [left, top, left + divWidth, top + divHeight];
  8614. }
  8615. task._bounds.push({
  8616. left: b[0],
  8617. top: b[1],
  8618. right: b[2],
  8619. bottom: b[3],
  8620. div: textDiv,
  8621. size: [divWidth, divHeight],
  8622. m
  8623. });
  8624. }
  8625. }
  8626. function render(task) {
  8627. if (task._canceled) {
  8628. return;
  8629. }
  8630. const textDivs = task._textDivs;
  8631. const capability = task._capability;
  8632. const textDivsLength = textDivs.length;
  8633. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  8634. task._renderingDone = true;
  8635. capability.resolve();
  8636. return;
  8637. }
  8638. if (!task._textContentStream) {
  8639. for (let i = 0; i < textDivsLength; i++) {
  8640. task._layoutText(textDivs[i]);
  8641. }
  8642. }
  8643. task._renderingDone = true;
  8644. capability.resolve();
  8645. }
  8646. function findPositiveMin(ts, offset, count) {
  8647. let result = 0;
  8648. for (let i = 0; i < count; i++) {
  8649. const t = ts[offset++];
  8650. if (t > 0) {
  8651. result = result ? Math.min(t, result) : t;
  8652. }
  8653. }
  8654. return result;
  8655. }
  8656. function expand(task) {
  8657. const bounds = task._bounds;
  8658. const viewport = task._viewport;
  8659. const expanded = expandBounds(viewport.width, viewport.height, bounds);
  8660. for (let i = 0; i < expanded.length; i++) {
  8661. const div = bounds[i].div;
  8662. const divProperties = task._textDivProperties.get(div);
  8663. if (divProperties.angle === 0) {
  8664. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  8665. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  8666. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  8667. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  8668. task._textDivProperties.set(div, divProperties);
  8669. continue;
  8670. }
  8671. const e = expanded[i],
  8672. b = bounds[i];
  8673. const m = b.m,
  8674. c = m[0],
  8675. s = m[1];
  8676. const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  8677. const ts = new Float64Array(64);
  8678. for (let j = 0, jj = points.length; j < jj; j++) {
  8679. const t = _util.Util.applyTransform(points[j], m);
  8680. ts[j + 0] = c && (e.left - t[0]) / c;
  8681. ts[j + 4] = s && (e.top - t[1]) / s;
  8682. ts[j + 8] = c && (e.right - t[0]) / c;
  8683. ts[j + 12] = s && (e.bottom - t[1]) / s;
  8684. ts[j + 16] = s && (e.left - t[0]) / -s;
  8685. ts[j + 20] = c && (e.top - t[1]) / c;
  8686. ts[j + 24] = s && (e.right - t[0]) / -s;
  8687. ts[j + 28] = c && (e.bottom - t[1]) / c;
  8688. ts[j + 32] = c && (e.left - t[0]) / -c;
  8689. ts[j + 36] = s && (e.top - t[1]) / -s;
  8690. ts[j + 40] = c && (e.right - t[0]) / -c;
  8691. ts[j + 44] = s && (e.bottom - t[1]) / -s;
  8692. ts[j + 48] = s && (e.left - t[0]) / s;
  8693. ts[j + 52] = c && (e.top - t[1]) / -c;
  8694. ts[j + 56] = s && (e.right - t[0]) / s;
  8695. ts[j + 60] = c && (e.bottom - t[1]) / -c;
  8696. }
  8697. const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  8698. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  8699. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  8700. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  8701. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  8702. task._textDivProperties.set(div, divProperties);
  8703. }
  8704. }
  8705. function expandBounds(width, height, boxes) {
  8706. const bounds = boxes.map(function (box, i) {
  8707. return {
  8708. x1: box.left,
  8709. y1: box.top,
  8710. x2: box.right,
  8711. y2: box.bottom,
  8712. index: i,
  8713. x1New: undefined,
  8714. x2New: undefined
  8715. };
  8716. });
  8717. expandBoundsLTR(width, bounds);
  8718. const expanded = new Array(boxes.length);
  8719. for (const b of bounds) {
  8720. const i = b.index;
  8721. expanded[i] = {
  8722. left: b.x1New,
  8723. top: 0,
  8724. right: b.x2New,
  8725. bottom: 0
  8726. };
  8727. }
  8728. boxes.map(function (box, i) {
  8729. const e = expanded[i],
  8730. b = bounds[i];
  8731. b.x1 = box.top;
  8732. b.y1 = width - e.right;
  8733. b.x2 = box.bottom;
  8734. b.y2 = width - e.left;
  8735. b.index = i;
  8736. b.x1New = undefined;
  8737. b.x2New = undefined;
  8738. });
  8739. expandBoundsLTR(height, bounds);
  8740. for (const b of bounds) {
  8741. const i = b.index;
  8742. expanded[i].top = b.x1New;
  8743. expanded[i].bottom = b.x2New;
  8744. }
  8745. return expanded;
  8746. }
  8747. function expandBoundsLTR(width, bounds) {
  8748. bounds.sort(function (a, b) {
  8749. return a.x1 - b.x1 || a.index - b.index;
  8750. });
  8751. const fakeBoundary = {
  8752. x1: -Infinity,
  8753. y1: -Infinity,
  8754. x2: 0,
  8755. y2: Infinity,
  8756. index: -1,
  8757. x1New: 0,
  8758. x2New: 0
  8759. };
  8760. const horizon = [{
  8761. start: -Infinity,
  8762. end: Infinity,
  8763. boundary: fakeBoundary
  8764. }];
  8765. for (const boundary of bounds) {
  8766. let i = 0;
  8767. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  8768. i++;
  8769. }
  8770. let j = horizon.length - 1;
  8771. while (j >= 0 && horizon[j].start >= boundary.y2) {
  8772. j--;
  8773. }
  8774. let horizonPart, affectedBoundary;
  8775. let q,
  8776. k,
  8777. maxXNew = -Infinity;
  8778. for (q = i; q <= j; q++) {
  8779. horizonPart = horizon[q];
  8780. affectedBoundary = horizonPart.boundary;
  8781. let xNew;
  8782. if (affectedBoundary.x2 > boundary.x1) {
  8783. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  8784. } else if (affectedBoundary.x2New === undefined) {
  8785. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  8786. } else {
  8787. xNew = affectedBoundary.x2New;
  8788. }
  8789. if (xNew > maxXNew) {
  8790. maxXNew = xNew;
  8791. }
  8792. }
  8793. boundary.x1New = maxXNew;
  8794. for (q = i; q <= j; q++) {
  8795. horizonPart = horizon[q];
  8796. affectedBoundary = horizonPart.boundary;
  8797. if (affectedBoundary.x2New === undefined) {
  8798. if (affectedBoundary.x2 > boundary.x1) {
  8799. if (affectedBoundary.index > boundary.index) {
  8800. affectedBoundary.x2New = affectedBoundary.x2;
  8801. }
  8802. } else {
  8803. affectedBoundary.x2New = maxXNew;
  8804. }
  8805. } else if (affectedBoundary.x2New > maxXNew) {
  8806. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  8807. }
  8808. }
  8809. const changedHorizon = [];
  8810. let lastBoundary = null;
  8811. for (q = i; q <= j; q++) {
  8812. horizonPart = horizon[q];
  8813. affectedBoundary = horizonPart.boundary;
  8814. const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  8815. if (lastBoundary === useBoundary) {
  8816. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  8817. } else {
  8818. changedHorizon.push({
  8819. start: horizonPart.start,
  8820. end: horizonPart.end,
  8821. boundary: useBoundary
  8822. });
  8823. lastBoundary = useBoundary;
  8824. }
  8825. }
  8826. if (horizon[i].start < boundary.y1) {
  8827. changedHorizon[0].start = boundary.y1;
  8828. changedHorizon.unshift({
  8829. start: horizon[i].start,
  8830. end: boundary.y1,
  8831. boundary: horizon[i].boundary
  8832. });
  8833. }
  8834. if (boundary.y2 < horizon[j].end) {
  8835. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  8836. changedHorizon.push({
  8837. start: boundary.y2,
  8838. end: horizon[j].end,
  8839. boundary: horizon[j].boundary
  8840. });
  8841. }
  8842. for (q = i; q <= j; q++) {
  8843. horizonPart = horizon[q];
  8844. affectedBoundary = horizonPart.boundary;
  8845. if (affectedBoundary.x2New !== undefined) {
  8846. continue;
  8847. }
  8848. let used = false;
  8849. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  8850. used = horizon[k].boundary === affectedBoundary;
  8851. }
  8852. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  8853. used = horizon[k].boundary === affectedBoundary;
  8854. }
  8855. for (k = 0; !used && k < changedHorizon.length; k++) {
  8856. used = changedHorizon[k].boundary === affectedBoundary;
  8857. }
  8858. if (!used) {
  8859. affectedBoundary.x2New = maxXNew;
  8860. }
  8861. }
  8862. Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
  8863. }
  8864. for (const horizonPart of horizon) {
  8865. const affectedBoundary = horizonPart.boundary;
  8866. if (affectedBoundary.x2New === undefined) {
  8867. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  8868. }
  8869. }
  8870. }
  8871. class TextLayerRenderTask {
  8872. constructor({
  8873. textContent,
  8874. textContentStream,
  8875. container,
  8876. viewport,
  8877. textDivs,
  8878. textContentItemsStr,
  8879. enhanceTextSelection
  8880. }) {
  8881. this._textContent = textContent;
  8882. this._textContentStream = textContentStream;
  8883. this._container = container;
  8884. this._document = container.ownerDocument;
  8885. this._viewport = viewport;
  8886. this._textDivs = textDivs || [];
  8887. this._textContentItemsStr = textContentItemsStr || [];
  8888. this._enhanceTextSelection = !!enhanceTextSelection;
  8889. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  8890. this._reader = null;
  8891. this._layoutTextLastFontSize = null;
  8892. this._layoutTextLastFontFamily = null;
  8893. this._layoutTextCtx = null;
  8894. this._textDivProperties = new WeakMap();
  8895. this._renderingDone = false;
  8896. this._canceled = false;
  8897. this._capability = (0, _util.createPromiseCapability)();
  8898. this._renderTimer = null;
  8899. this._bounds = [];
  8900. this._capability.promise.finally(() => {
  8901. if (this._layoutTextCtx) {
  8902. this._layoutTextCtx.canvas.width = 0;
  8903. this._layoutTextCtx.canvas.height = 0;
  8904. this._layoutTextCtx = null;
  8905. }
  8906. }).catch(() => {});
  8907. }
  8908. get promise() {
  8909. return this._capability.promise;
  8910. }
  8911. cancel() {
  8912. this._canceled = true;
  8913. if (this._reader) {
  8914. this._reader.cancel(new _util.AbortException("TextLayer task cancelled."));
  8915. this._reader = null;
  8916. }
  8917. if (this._renderTimer !== null) {
  8918. clearTimeout(this._renderTimer);
  8919. this._renderTimer = null;
  8920. }
  8921. this._capability.reject(new Error("TextLayer task cancelled."));
  8922. }
  8923. _processItems(items, styleCache) {
  8924. for (let i = 0, len = items.length; i < len; i++) {
  8925. if (items[i].str === undefined) {
  8926. if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") {
  8927. const parent = this._container;
  8928. this._container = document.createElement("span");
  8929. this._container.classList.add("markedContent");
  8930. if (items[i].id !== null) {
  8931. this._container.setAttribute("id", `${items[i].id}`);
  8932. }
  8933. parent.appendChild(this._container);
  8934. } else if (items[i].type === "endMarkedContent") {
  8935. this._container = this._container.parentNode;
  8936. }
  8937. continue;
  8938. }
  8939. this._textContentItemsStr.push(items[i].str);
  8940. appendText(this, items[i], styleCache, this._layoutTextCtx);
  8941. }
  8942. }
  8943. _layoutText(textDiv) {
  8944. const textDivProperties = this._textDivProperties.get(textDiv);
  8945. let transform = "";
  8946. if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
  8947. const {
  8948. fontSize,
  8949. fontFamily
  8950. } = textDiv.style;
  8951. if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
  8952. this._layoutTextCtx.font = `${fontSize} ${fontFamily}`;
  8953. this._layoutTextLastFontSize = fontSize;
  8954. this._layoutTextLastFontFamily = fontFamily;
  8955. }
  8956. const {
  8957. width
  8958. } = this._layoutTextCtx.measureText(textDiv.textContent);
  8959. if (width > 0) {
  8960. textDivProperties.scale = textDivProperties.canvasWidth / width;
  8961. transform = `scaleX(${textDivProperties.scale})`;
  8962. }
  8963. }
  8964. if (textDivProperties.angle !== 0) {
  8965. transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
  8966. }
  8967. if (transform.length > 0) {
  8968. if (this._enhanceTextSelection) {
  8969. textDivProperties.originalTransform = transform;
  8970. }
  8971. textDiv.style.transform = transform;
  8972. }
  8973. if (textDivProperties.hasText) {
  8974. this._container.appendChild(textDiv);
  8975. }
  8976. if (textDivProperties.hasEOL) {
  8977. const br = document.createElement("br");
  8978. br.setAttribute("role", "presentation");
  8979. this._container.appendChild(br);
  8980. }
  8981. }
  8982. _render(timeout = 0) {
  8983. const capability = (0, _util.createPromiseCapability)();
  8984. let styleCache = Object.create(null);
  8985. const canvas = this._document.createElement("canvas");
  8986. canvas.height = canvas.width = DEFAULT_FONT_SIZE;
  8987. canvas.mozOpaque = true;
  8988. this._layoutTextCtx = canvas.getContext("2d", {
  8989. alpha: false
  8990. });
  8991. if (this._textContent) {
  8992. const textItems = this._textContent.items;
  8993. const textStyles = this._textContent.styles;
  8994. this._processItems(textItems, textStyles);
  8995. capability.resolve();
  8996. } else if (this._textContentStream) {
  8997. const pump = () => {
  8998. this._reader.read().then(({
  8999. value,
  9000. done
  9001. }) => {
  9002. if (done) {
  9003. capability.resolve();
  9004. return;
  9005. }
  9006. Object.assign(styleCache, value.styles);
  9007. this._processItems(value.items, styleCache);
  9008. pump();
  9009. }, capability.reject);
  9010. };
  9011. this._reader = this._textContentStream.getReader();
  9012. pump();
  9013. } else {
  9014. throw new Error('Neither "textContent" nor "textContentStream"' + " parameters specified.");
  9015. }
  9016. capability.promise.then(() => {
  9017. styleCache = null;
  9018. if (!timeout) {
  9019. render(this);
  9020. } else {
  9021. this._renderTimer = setTimeout(() => {
  9022. render(this);
  9023. this._renderTimer = null;
  9024. }, timeout);
  9025. }
  9026. }, this._capability.reject);
  9027. }
  9028. expandTextDivs(expandDivs = false) {
  9029. if (!this._enhanceTextSelection || !this._renderingDone) {
  9030. return;
  9031. }
  9032. if (this._bounds !== null) {
  9033. expand(this);
  9034. this._bounds = null;
  9035. }
  9036. const transformBuf = [],
  9037. paddingBuf = [];
  9038. for (let i = 0, ii = this._textDivs.length; i < ii; i++) {
  9039. const div = this._textDivs[i];
  9040. const divProps = this._textDivProperties.get(div);
  9041. if (!divProps.hasText) {
  9042. continue;
  9043. }
  9044. if (expandDivs) {
  9045. transformBuf.length = 0;
  9046. paddingBuf.length = 0;
  9047. if (divProps.originalTransform) {
  9048. transformBuf.push(divProps.originalTransform);
  9049. }
  9050. if (divProps.paddingTop > 0) {
  9051. paddingBuf.push(`${divProps.paddingTop}px`);
  9052. transformBuf.push(`translateY(${-divProps.paddingTop}px)`);
  9053. } else {
  9054. paddingBuf.push(0);
  9055. }
  9056. if (divProps.paddingRight > 0) {
  9057. paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`);
  9058. } else {
  9059. paddingBuf.push(0);
  9060. }
  9061. if (divProps.paddingBottom > 0) {
  9062. paddingBuf.push(`${divProps.paddingBottom}px`);
  9063. } else {
  9064. paddingBuf.push(0);
  9065. }
  9066. if (divProps.paddingLeft > 0) {
  9067. paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`);
  9068. transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`);
  9069. } else {
  9070. paddingBuf.push(0);
  9071. }
  9072. div.style.padding = paddingBuf.join(" ");
  9073. if (transformBuf.length) {
  9074. div.style.transform = transformBuf.join(" ");
  9075. }
  9076. } else {
  9077. div.style.padding = null;
  9078. div.style.transform = divProps.originalTransform;
  9079. }
  9080. }
  9081. }
  9082. }
  9083. function renderTextLayer(renderParameters) {
  9084. const task = new TextLayerRenderTask({
  9085. textContent: renderParameters.textContent,
  9086. textContentStream: renderParameters.textContentStream,
  9087. container: renderParameters.container,
  9088. viewport: renderParameters.viewport,
  9089. textDivs: renderParameters.textDivs,
  9090. textContentItemsStr: renderParameters.textContentItemsStr,
  9091. enhanceTextSelection: renderParameters.enhanceTextSelection
  9092. });
  9093. task._render(renderParameters.timeout);
  9094. return task;
  9095. }
  9096. /***/ }),
  9097. /* 20 */
  9098. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9099. Object.defineProperty(exports, "__esModule", ({
  9100. value: true
  9101. }));
  9102. exports.SVGGraphics = void 0;
  9103. var _util = __w_pdfjs_require__(2);
  9104. var _display_utils = __w_pdfjs_require__(1);
  9105. var _is_node = __w_pdfjs_require__(4);
  9106. let SVGGraphics = class {
  9107. constructor() {
  9108. (0, _util.unreachable)("Not implemented: SVGGraphics");
  9109. }
  9110. };
  9111. exports.SVGGraphics = SVGGraphics;
  9112. {
  9113. const SVG_DEFAULTS = {
  9114. fontStyle: "normal",
  9115. fontWeight: "normal",
  9116. fillColor: "#000000"
  9117. };
  9118. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  9119. const XLINK_NS = "http://www.w3.org/1999/xlink";
  9120. const LINE_CAP_STYLES = ["butt", "round", "square"];
  9121. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  9122. const convertImgDataToPng = function () {
  9123. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  9124. const CHUNK_WRAPPER_SIZE = 12;
  9125. const crcTable = new Int32Array(256);
  9126. for (let i = 0; i < 256; i++) {
  9127. let c = i;
  9128. for (let h = 0; h < 8; h++) {
  9129. if (c & 1) {
  9130. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  9131. } else {
  9132. c = c >> 1 & 0x7fffffff;
  9133. }
  9134. }
  9135. crcTable[i] = c;
  9136. }
  9137. function crc32(data, start, end) {
  9138. let crc = -1;
  9139. for (let i = start; i < end; i++) {
  9140. const a = (crc ^ data[i]) & 0xff;
  9141. const b = crcTable[a];
  9142. crc = crc >>> 8 ^ b;
  9143. }
  9144. return crc ^ -1;
  9145. }
  9146. function writePngChunk(type, body, data, offset) {
  9147. let p = offset;
  9148. const len = body.length;
  9149. data[p] = len >> 24 & 0xff;
  9150. data[p + 1] = len >> 16 & 0xff;
  9151. data[p + 2] = len >> 8 & 0xff;
  9152. data[p + 3] = len & 0xff;
  9153. p += 4;
  9154. data[p] = type.charCodeAt(0) & 0xff;
  9155. data[p + 1] = type.charCodeAt(1) & 0xff;
  9156. data[p + 2] = type.charCodeAt(2) & 0xff;
  9157. data[p + 3] = type.charCodeAt(3) & 0xff;
  9158. p += 4;
  9159. data.set(body, p);
  9160. p += body.length;
  9161. const crc = crc32(data, offset + 4, p);
  9162. data[p] = crc >> 24 & 0xff;
  9163. data[p + 1] = crc >> 16 & 0xff;
  9164. data[p + 2] = crc >> 8 & 0xff;
  9165. data[p + 3] = crc & 0xff;
  9166. }
  9167. function adler32(data, start, end) {
  9168. let a = 1;
  9169. let b = 0;
  9170. for (let i = start; i < end; ++i) {
  9171. a = (a + (data[i] & 0xff)) % 65521;
  9172. b = (b + a) % 65521;
  9173. }
  9174. return b << 16 | a;
  9175. }
  9176. function deflateSync(literals) {
  9177. if (!_is_node.isNodeJS) {
  9178. return deflateSyncUncompressed(literals);
  9179. }
  9180. try {
  9181. let input;
  9182. if (parseInt(process.versions.node) >= 8) {
  9183. input = literals;
  9184. } else {
  9185. input = Buffer.from(literals);
  9186. }
  9187. const output = require("zlib").deflateSync(input, {
  9188. level: 9
  9189. });
  9190. return output instanceof Uint8Array ? output : new Uint8Array(output);
  9191. } catch (e) {
  9192. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  9193. }
  9194. return deflateSyncUncompressed(literals);
  9195. }
  9196. function deflateSyncUncompressed(literals) {
  9197. let len = literals.length;
  9198. const maxBlockLength = 0xffff;
  9199. const deflateBlocks = Math.ceil(len / maxBlockLength);
  9200. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  9201. let pi = 0;
  9202. idat[pi++] = 0x78;
  9203. idat[pi++] = 0x9c;
  9204. let pos = 0;
  9205. while (len > maxBlockLength) {
  9206. idat[pi++] = 0x00;
  9207. idat[pi++] = 0xff;
  9208. idat[pi++] = 0xff;
  9209. idat[pi++] = 0x00;
  9210. idat[pi++] = 0x00;
  9211. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  9212. pi += maxBlockLength;
  9213. pos += maxBlockLength;
  9214. len -= maxBlockLength;
  9215. }
  9216. idat[pi++] = 0x01;
  9217. idat[pi++] = len & 0xff;
  9218. idat[pi++] = len >> 8 & 0xff;
  9219. idat[pi++] = ~len & 0xffff & 0xff;
  9220. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  9221. idat.set(literals.subarray(pos), pi);
  9222. pi += literals.length - pos;
  9223. const adler = adler32(literals, 0, literals.length);
  9224. idat[pi++] = adler >> 24 & 0xff;
  9225. idat[pi++] = adler >> 16 & 0xff;
  9226. idat[pi++] = adler >> 8 & 0xff;
  9227. idat[pi++] = adler & 0xff;
  9228. return idat;
  9229. }
  9230. function encode(imgData, kind, forceDataSchema, isMask) {
  9231. const width = imgData.width;
  9232. const height = imgData.height;
  9233. let bitDepth, colorType, lineSize;
  9234. const bytes = imgData.data;
  9235. switch (kind) {
  9236. case _util.ImageKind.GRAYSCALE_1BPP:
  9237. colorType = 0;
  9238. bitDepth = 1;
  9239. lineSize = width + 7 >> 3;
  9240. break;
  9241. case _util.ImageKind.RGB_24BPP:
  9242. colorType = 2;
  9243. bitDepth = 8;
  9244. lineSize = width * 3;
  9245. break;
  9246. case _util.ImageKind.RGBA_32BPP:
  9247. colorType = 6;
  9248. bitDepth = 8;
  9249. lineSize = width * 4;
  9250. break;
  9251. default:
  9252. throw new Error("invalid format");
  9253. }
  9254. const literals = new Uint8Array((1 + lineSize) * height);
  9255. let offsetLiterals = 0,
  9256. offsetBytes = 0;
  9257. for (let y = 0; y < height; ++y) {
  9258. literals[offsetLiterals++] = 0;
  9259. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  9260. offsetBytes += lineSize;
  9261. offsetLiterals += lineSize;
  9262. }
  9263. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  9264. offsetLiterals = 0;
  9265. for (let y = 0; y < height; y++) {
  9266. offsetLiterals++;
  9267. for (let i = 0; i < lineSize; i++) {
  9268. literals[offsetLiterals++] ^= 0xff;
  9269. }
  9270. }
  9271. }
  9272. 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]);
  9273. const idat = deflateSync(literals);
  9274. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  9275. const data = new Uint8Array(pngLength);
  9276. let offset = 0;
  9277. data.set(PNG_HEADER, offset);
  9278. offset += PNG_HEADER.length;
  9279. writePngChunk("IHDR", ihdr, data, offset);
  9280. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  9281. writePngChunk("IDATA", idat, data, offset);
  9282. offset += CHUNK_WRAPPER_SIZE + idat.length;
  9283. writePngChunk("IEND", new Uint8Array(0), data, offset);
  9284. return (0, _util.createObjectURL)(data, "image/png", forceDataSchema);
  9285. }
  9286. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  9287. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  9288. return encode(imgData, kind, forceDataSchema, isMask);
  9289. };
  9290. }();
  9291. class SVGExtraState {
  9292. constructor() {
  9293. this.fontSizeScale = 1;
  9294. this.fontWeight = SVG_DEFAULTS.fontWeight;
  9295. this.fontSize = 0;
  9296. this.textMatrix = _util.IDENTITY_MATRIX;
  9297. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  9298. this.leading = 0;
  9299. this.textRenderingMode = _util.TextRenderingMode.FILL;
  9300. this.textMatrixScale = 1;
  9301. this.x = 0;
  9302. this.y = 0;
  9303. this.lineX = 0;
  9304. this.lineY = 0;
  9305. this.charSpacing = 0;
  9306. this.wordSpacing = 0;
  9307. this.textHScale = 1;
  9308. this.textRise = 0;
  9309. this.fillColor = SVG_DEFAULTS.fillColor;
  9310. this.strokeColor = "#000000";
  9311. this.fillAlpha = 1;
  9312. this.strokeAlpha = 1;
  9313. this.lineWidth = 1;
  9314. this.lineJoin = "";
  9315. this.lineCap = "";
  9316. this.miterLimit = 0;
  9317. this.dashArray = [];
  9318. this.dashPhase = 0;
  9319. this.dependencies = [];
  9320. this.activeClipUrl = null;
  9321. this.clipGroup = null;
  9322. this.maskId = "";
  9323. }
  9324. clone() {
  9325. return Object.create(this);
  9326. }
  9327. setCurrentPoint(x, y) {
  9328. this.x = x;
  9329. this.y = y;
  9330. }
  9331. }
  9332. function opListToTree(opList) {
  9333. let opTree = [];
  9334. const tmp = [];
  9335. for (const opListElement of opList) {
  9336. if (opListElement.fn === "save") {
  9337. opTree.push({
  9338. fnId: 92,
  9339. fn: "group",
  9340. items: []
  9341. });
  9342. tmp.push(opTree);
  9343. opTree = opTree[opTree.length - 1].items;
  9344. continue;
  9345. }
  9346. if (opListElement.fn === "restore") {
  9347. opTree = tmp.pop();
  9348. } else {
  9349. opTree.push(opListElement);
  9350. }
  9351. }
  9352. return opTree;
  9353. }
  9354. function pf(value) {
  9355. if (Number.isInteger(value)) {
  9356. return value.toString();
  9357. }
  9358. const s = value.toFixed(10);
  9359. let i = s.length - 1;
  9360. if (s[i] !== "0") {
  9361. return s;
  9362. }
  9363. do {
  9364. i--;
  9365. } while (s[i] === "0");
  9366. return s.substring(0, s[i] === "." ? i : i + 1);
  9367. }
  9368. function pm(m) {
  9369. if (m[4] === 0 && m[5] === 0) {
  9370. if (m[1] === 0 && m[2] === 0) {
  9371. if (m[0] === 1 && m[3] === 1) {
  9372. return "";
  9373. }
  9374. return `scale(${pf(m[0])} ${pf(m[3])})`;
  9375. }
  9376. if (m[0] === m[3] && m[1] === -m[2]) {
  9377. const a = Math.acos(m[0]) * 180 / Math.PI;
  9378. return `rotate(${pf(a)})`;
  9379. }
  9380. } else {
  9381. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  9382. return `translate(${pf(m[4])} ${pf(m[5])})`;
  9383. }
  9384. }
  9385. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  9386. }
  9387. let clipCount = 0;
  9388. let maskCount = 0;
  9389. let shadingCount = 0;
  9390. exports.SVGGraphics = SVGGraphics = class {
  9391. constructor(commonObjs, objs, forceDataSchema = false) {
  9392. this.svgFactory = new _display_utils.DOMSVGFactory();
  9393. this.current = new SVGExtraState();
  9394. this.transformMatrix = _util.IDENTITY_MATRIX;
  9395. this.transformStack = [];
  9396. this.extraStack = [];
  9397. this.commonObjs = commonObjs;
  9398. this.objs = objs;
  9399. this.pendingClip = null;
  9400. this.pendingEOFill = false;
  9401. this.embedFonts = false;
  9402. this.embeddedFonts = Object.create(null);
  9403. this.cssStyle = null;
  9404. this.forceDataSchema = !!forceDataSchema;
  9405. this._operatorIdMapping = [];
  9406. for (const op in _util.OPS) {
  9407. this._operatorIdMapping[_util.OPS[op]] = op;
  9408. }
  9409. }
  9410. save() {
  9411. this.transformStack.push(this.transformMatrix);
  9412. const old = this.current;
  9413. this.extraStack.push(old);
  9414. this.current = old.clone();
  9415. }
  9416. restore() {
  9417. this.transformMatrix = this.transformStack.pop();
  9418. this.current = this.extraStack.pop();
  9419. this.pendingClip = null;
  9420. this.tgrp = null;
  9421. }
  9422. group(items) {
  9423. this.save();
  9424. this.executeOpTree(items);
  9425. this.restore();
  9426. }
  9427. loadDependencies(operatorList) {
  9428. const fnArray = operatorList.fnArray;
  9429. const argsArray = operatorList.argsArray;
  9430. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  9431. if (fnArray[i] !== _util.OPS.dependency) {
  9432. continue;
  9433. }
  9434. for (const obj of argsArray[i]) {
  9435. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  9436. const promise = new Promise(resolve => {
  9437. objsPool.get(obj, resolve);
  9438. });
  9439. this.current.dependencies.push(promise);
  9440. }
  9441. }
  9442. return Promise.all(this.current.dependencies);
  9443. }
  9444. transform(a, b, c, d, e, f) {
  9445. const transformMatrix = [a, b, c, d, e, f];
  9446. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  9447. this.tgrp = null;
  9448. }
  9449. getSVG(operatorList, viewport) {
  9450. this.viewport = viewport;
  9451. const svgElement = this._initialize(viewport);
  9452. return this.loadDependencies(operatorList).then(() => {
  9453. this.transformMatrix = _util.IDENTITY_MATRIX;
  9454. this.executeOpTree(this.convertOpList(operatorList));
  9455. return svgElement;
  9456. });
  9457. }
  9458. convertOpList(operatorList) {
  9459. const operatorIdMapping = this._operatorIdMapping;
  9460. const argsArray = operatorList.argsArray;
  9461. const fnArray = operatorList.fnArray;
  9462. const opList = [];
  9463. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  9464. const fnId = fnArray[i];
  9465. opList.push({
  9466. fnId,
  9467. fn: operatorIdMapping[fnId],
  9468. args: argsArray[i]
  9469. });
  9470. }
  9471. return opListToTree(opList);
  9472. }
  9473. executeOpTree(opTree) {
  9474. for (const opTreeElement of opTree) {
  9475. const fn = opTreeElement.fn;
  9476. const fnId = opTreeElement.fnId;
  9477. const args = opTreeElement.args;
  9478. switch (fnId | 0) {
  9479. case _util.OPS.beginText:
  9480. this.beginText();
  9481. break;
  9482. case _util.OPS.dependency:
  9483. break;
  9484. case _util.OPS.setLeading:
  9485. this.setLeading(args);
  9486. break;
  9487. case _util.OPS.setLeadingMoveText:
  9488. this.setLeadingMoveText(args[0], args[1]);
  9489. break;
  9490. case _util.OPS.setFont:
  9491. this.setFont(args);
  9492. break;
  9493. case _util.OPS.showText:
  9494. this.showText(args[0]);
  9495. break;
  9496. case _util.OPS.showSpacedText:
  9497. this.showText(args[0]);
  9498. break;
  9499. case _util.OPS.endText:
  9500. this.endText();
  9501. break;
  9502. case _util.OPS.moveText:
  9503. this.moveText(args[0], args[1]);
  9504. break;
  9505. case _util.OPS.setCharSpacing:
  9506. this.setCharSpacing(args[0]);
  9507. break;
  9508. case _util.OPS.setWordSpacing:
  9509. this.setWordSpacing(args[0]);
  9510. break;
  9511. case _util.OPS.setHScale:
  9512. this.setHScale(args[0]);
  9513. break;
  9514. case _util.OPS.setTextMatrix:
  9515. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  9516. break;
  9517. case _util.OPS.setTextRise:
  9518. this.setTextRise(args[0]);
  9519. break;
  9520. case _util.OPS.setTextRenderingMode:
  9521. this.setTextRenderingMode(args[0]);
  9522. break;
  9523. case _util.OPS.setLineWidth:
  9524. this.setLineWidth(args[0]);
  9525. break;
  9526. case _util.OPS.setLineJoin:
  9527. this.setLineJoin(args[0]);
  9528. break;
  9529. case _util.OPS.setLineCap:
  9530. this.setLineCap(args[0]);
  9531. break;
  9532. case _util.OPS.setMiterLimit:
  9533. this.setMiterLimit(args[0]);
  9534. break;
  9535. case _util.OPS.setFillRGBColor:
  9536. this.setFillRGBColor(args[0], args[1], args[2]);
  9537. break;
  9538. case _util.OPS.setStrokeRGBColor:
  9539. this.setStrokeRGBColor(args[0], args[1], args[2]);
  9540. break;
  9541. case _util.OPS.setStrokeColorN:
  9542. this.setStrokeColorN(args);
  9543. break;
  9544. case _util.OPS.setFillColorN:
  9545. this.setFillColorN(args);
  9546. break;
  9547. case _util.OPS.shadingFill:
  9548. this.shadingFill(args[0]);
  9549. break;
  9550. case _util.OPS.setDash:
  9551. this.setDash(args[0], args[1]);
  9552. break;
  9553. case _util.OPS.setRenderingIntent:
  9554. this.setRenderingIntent(args[0]);
  9555. break;
  9556. case _util.OPS.setFlatness:
  9557. this.setFlatness(args[0]);
  9558. break;
  9559. case _util.OPS.setGState:
  9560. this.setGState(args[0]);
  9561. break;
  9562. case _util.OPS.fill:
  9563. this.fill();
  9564. break;
  9565. case _util.OPS.eoFill:
  9566. this.eoFill();
  9567. break;
  9568. case _util.OPS.stroke:
  9569. this.stroke();
  9570. break;
  9571. case _util.OPS.fillStroke:
  9572. this.fillStroke();
  9573. break;
  9574. case _util.OPS.eoFillStroke:
  9575. this.eoFillStroke();
  9576. break;
  9577. case _util.OPS.clip:
  9578. this.clip("nonzero");
  9579. break;
  9580. case _util.OPS.eoClip:
  9581. this.clip("evenodd");
  9582. break;
  9583. case _util.OPS.paintSolidColorImageMask:
  9584. this.paintSolidColorImageMask();
  9585. break;
  9586. case _util.OPS.paintImageXObject:
  9587. this.paintImageXObject(args[0]);
  9588. break;
  9589. case _util.OPS.paintInlineImageXObject:
  9590. this.paintInlineImageXObject(args[0]);
  9591. break;
  9592. case _util.OPS.paintImageMaskXObject:
  9593. this.paintImageMaskXObject(args[0]);
  9594. break;
  9595. case _util.OPS.paintFormXObjectBegin:
  9596. this.paintFormXObjectBegin(args[0], args[1]);
  9597. break;
  9598. case _util.OPS.paintFormXObjectEnd:
  9599. this.paintFormXObjectEnd();
  9600. break;
  9601. case _util.OPS.closePath:
  9602. this.closePath();
  9603. break;
  9604. case _util.OPS.closeStroke:
  9605. this.closeStroke();
  9606. break;
  9607. case _util.OPS.closeFillStroke:
  9608. this.closeFillStroke();
  9609. break;
  9610. case _util.OPS.closeEOFillStroke:
  9611. this.closeEOFillStroke();
  9612. break;
  9613. case _util.OPS.nextLine:
  9614. this.nextLine();
  9615. break;
  9616. case _util.OPS.transform:
  9617. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  9618. break;
  9619. case _util.OPS.constructPath:
  9620. this.constructPath(args[0], args[1]);
  9621. break;
  9622. case _util.OPS.endPath:
  9623. this.endPath();
  9624. break;
  9625. case 92:
  9626. this.group(opTreeElement.items);
  9627. break;
  9628. default:
  9629. (0, _util.warn)(`Unimplemented operator ${fn}`);
  9630. break;
  9631. }
  9632. }
  9633. }
  9634. setWordSpacing(wordSpacing) {
  9635. this.current.wordSpacing = wordSpacing;
  9636. }
  9637. setCharSpacing(charSpacing) {
  9638. this.current.charSpacing = charSpacing;
  9639. }
  9640. nextLine() {
  9641. this.moveText(0, this.current.leading);
  9642. }
  9643. setTextMatrix(a, b, c, d, e, f) {
  9644. const current = this.current;
  9645. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  9646. current.textMatrixScale = Math.hypot(a, b);
  9647. current.x = current.lineX = 0;
  9648. current.y = current.lineY = 0;
  9649. current.xcoords = [];
  9650. current.ycoords = [];
  9651. current.tspan = this.svgFactory.createElement("svg:tspan");
  9652. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  9653. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  9654. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9655. current.txtElement = this.svgFactory.createElement("svg:text");
  9656. current.txtElement.appendChild(current.tspan);
  9657. }
  9658. beginText() {
  9659. const current = this.current;
  9660. current.x = current.lineX = 0;
  9661. current.y = current.lineY = 0;
  9662. current.textMatrix = _util.IDENTITY_MATRIX;
  9663. current.lineMatrix = _util.IDENTITY_MATRIX;
  9664. current.textMatrixScale = 1;
  9665. current.tspan = this.svgFactory.createElement("svg:tspan");
  9666. current.txtElement = this.svgFactory.createElement("svg:text");
  9667. current.txtgrp = this.svgFactory.createElement("svg:g");
  9668. current.xcoords = [];
  9669. current.ycoords = [];
  9670. }
  9671. moveText(x, y) {
  9672. const current = this.current;
  9673. current.x = current.lineX += x;
  9674. current.y = current.lineY += y;
  9675. current.xcoords = [];
  9676. current.ycoords = [];
  9677. current.tspan = this.svgFactory.createElement("svg:tspan");
  9678. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  9679. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  9680. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9681. }
  9682. showText(glyphs) {
  9683. const current = this.current;
  9684. const font = current.font;
  9685. const fontSize = current.fontSize;
  9686. if (fontSize === 0) {
  9687. return;
  9688. }
  9689. const fontSizeScale = current.fontSizeScale;
  9690. const charSpacing = current.charSpacing;
  9691. const wordSpacing = current.wordSpacing;
  9692. const fontDirection = current.fontDirection;
  9693. const textHScale = current.textHScale * fontDirection;
  9694. const vertical = font.vertical;
  9695. const spacingDir = vertical ? 1 : -1;
  9696. const defaultVMetrics = font.defaultVMetrics;
  9697. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  9698. let x = 0;
  9699. for (const glyph of glyphs) {
  9700. if (glyph === null) {
  9701. x += fontDirection * wordSpacing;
  9702. continue;
  9703. } else if ((0, _util.isNum)(glyph)) {
  9704. x += spacingDir * glyph * fontSize / 1000;
  9705. continue;
  9706. }
  9707. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  9708. const character = glyph.fontChar;
  9709. let scaledX, scaledY;
  9710. let width = glyph.width;
  9711. if (vertical) {
  9712. let vx;
  9713. const vmetric = glyph.vmetric || defaultVMetrics;
  9714. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  9715. vx = -vx * widthAdvanceScale;
  9716. const vy = vmetric[2] * widthAdvanceScale;
  9717. width = vmetric ? -vmetric[0] : width;
  9718. scaledX = vx / fontSizeScale;
  9719. scaledY = (x + vy) / fontSizeScale;
  9720. } else {
  9721. scaledX = x / fontSizeScale;
  9722. scaledY = 0;
  9723. }
  9724. if (glyph.isInFont || font.missingFile) {
  9725. current.xcoords.push(current.x + scaledX);
  9726. if (vertical) {
  9727. current.ycoords.push(-current.y + scaledY);
  9728. }
  9729. current.tspan.textContent += character;
  9730. } else {}
  9731. let charWidth;
  9732. if (vertical) {
  9733. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  9734. } else {
  9735. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  9736. }
  9737. x += charWidth;
  9738. }
  9739. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  9740. if (vertical) {
  9741. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  9742. } else {
  9743. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9744. }
  9745. if (vertical) {
  9746. current.y -= x;
  9747. } else {
  9748. current.x += x * textHScale;
  9749. }
  9750. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  9751. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  9752. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  9753. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  9754. }
  9755. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  9756. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  9757. }
  9758. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  9759. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  9760. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  9761. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  9762. }
  9763. if (current.fillAlpha < 1) {
  9764. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  9765. }
  9766. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  9767. current.tspan.setAttributeNS(null, "fill", "transparent");
  9768. } else {
  9769. current.tspan.setAttributeNS(null, "fill", "none");
  9770. }
  9771. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  9772. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  9773. this._setStrokeAttributes(current.tspan, lineWidthScale);
  9774. }
  9775. let textMatrix = current.textMatrix;
  9776. if (current.textRise !== 0) {
  9777. textMatrix = textMatrix.slice();
  9778. textMatrix[5] += current.textRise;
  9779. }
  9780. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  9781. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  9782. current.txtElement.appendChild(current.tspan);
  9783. current.txtgrp.appendChild(current.txtElement);
  9784. this._ensureTransformGroup().appendChild(current.txtElement);
  9785. }
  9786. setLeadingMoveText(x, y) {
  9787. this.setLeading(-y);
  9788. this.moveText(x, y);
  9789. }
  9790. addFontStyle(fontObj) {
  9791. if (!fontObj.data) {
  9792. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  9793. }
  9794. if (!this.cssStyle) {
  9795. this.cssStyle = this.svgFactory.createElement("svg:style");
  9796. this.cssStyle.setAttributeNS(null, "type", "text/css");
  9797. this.defs.appendChild(this.cssStyle);
  9798. }
  9799. const url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  9800. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  9801. }
  9802. setFont(details) {
  9803. const current = this.current;
  9804. const fontObj = this.commonObjs.get(details[0]);
  9805. let size = details[1];
  9806. current.font = fontObj;
  9807. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  9808. this.addFontStyle(fontObj);
  9809. this.embeddedFonts[fontObj.loadedName] = fontObj;
  9810. }
  9811. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  9812. let bold = "normal";
  9813. if (fontObj.black) {
  9814. bold = "900";
  9815. } else if (fontObj.bold) {
  9816. bold = "bold";
  9817. }
  9818. const italic = fontObj.italic ? "italic" : "normal";
  9819. if (size < 0) {
  9820. size = -size;
  9821. current.fontDirection = -1;
  9822. } else {
  9823. current.fontDirection = 1;
  9824. }
  9825. current.fontSize = size;
  9826. current.fontFamily = fontObj.loadedName;
  9827. current.fontWeight = bold;
  9828. current.fontStyle = italic;
  9829. current.tspan = this.svgFactory.createElement("svg:tspan");
  9830. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9831. current.xcoords = [];
  9832. current.ycoords = [];
  9833. }
  9834. endText() {
  9835. const current = this.current;
  9836. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  9837. current.element = current.txtElement;
  9838. this.clip("nonzero");
  9839. this.endPath();
  9840. }
  9841. }
  9842. setLineWidth(width) {
  9843. if (width > 0) {
  9844. this.current.lineWidth = width;
  9845. }
  9846. }
  9847. setLineCap(style) {
  9848. this.current.lineCap = LINE_CAP_STYLES[style];
  9849. }
  9850. setLineJoin(style) {
  9851. this.current.lineJoin = LINE_JOIN_STYLES[style];
  9852. }
  9853. setMiterLimit(limit) {
  9854. this.current.miterLimit = limit;
  9855. }
  9856. setStrokeAlpha(strokeAlpha) {
  9857. this.current.strokeAlpha = strokeAlpha;
  9858. }
  9859. setStrokeRGBColor(r, g, b) {
  9860. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  9861. }
  9862. setFillAlpha(fillAlpha) {
  9863. this.current.fillAlpha = fillAlpha;
  9864. }
  9865. setFillRGBColor(r, g, b) {
  9866. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  9867. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  9868. this.current.xcoords = [];
  9869. this.current.ycoords = [];
  9870. }
  9871. setStrokeColorN(args) {
  9872. this.current.strokeColor = this._makeColorN_Pattern(args);
  9873. }
  9874. setFillColorN(args) {
  9875. this.current.fillColor = this._makeColorN_Pattern(args);
  9876. }
  9877. shadingFill(args) {
  9878. const width = this.viewport.width;
  9879. const height = this.viewport.height;
  9880. const inv = _util.Util.inverseTransform(this.transformMatrix);
  9881. const bl = _util.Util.applyTransform([0, 0], inv);
  9882. const br = _util.Util.applyTransform([0, height], inv);
  9883. const ul = _util.Util.applyTransform([width, 0], inv);
  9884. const ur = _util.Util.applyTransform([width, height], inv);
  9885. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  9886. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  9887. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  9888. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  9889. const rect = this.svgFactory.createElement("svg:rect");
  9890. rect.setAttributeNS(null, "x", x0);
  9891. rect.setAttributeNS(null, "y", y0);
  9892. rect.setAttributeNS(null, "width", x1 - x0);
  9893. rect.setAttributeNS(null, "height", y1 - y0);
  9894. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  9895. if (this.current.fillAlpha < 1) {
  9896. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  9897. }
  9898. this._ensureTransformGroup().appendChild(rect);
  9899. }
  9900. _makeColorN_Pattern(args) {
  9901. if (args[0] === "TilingPattern") {
  9902. return this._makeTilingPattern(args);
  9903. }
  9904. return this._makeShadingPattern(args);
  9905. }
  9906. _makeTilingPattern(args) {
  9907. const color = args[1];
  9908. const operatorList = args[2];
  9909. const matrix = args[3] || _util.IDENTITY_MATRIX;
  9910. const [x0, y0, x1, y1] = args[4];
  9911. const xstep = args[5];
  9912. const ystep = args[6];
  9913. const paintType = args[7];
  9914. const tilingId = `shading${shadingCount++}`;
  9915. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  9916. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  9917. const txstep = xstep * xscale;
  9918. const tystep = ystep * yscale;
  9919. const tiling = this.svgFactory.createElement("svg:pattern");
  9920. tiling.setAttributeNS(null, "id", tilingId);
  9921. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  9922. tiling.setAttributeNS(null, "width", txstep);
  9923. tiling.setAttributeNS(null, "height", tystep);
  9924. tiling.setAttributeNS(null, "x", `${tx0}`);
  9925. tiling.setAttributeNS(null, "y", `${ty0}`);
  9926. const svg = this.svg;
  9927. const transformMatrix = this.transformMatrix;
  9928. const fillColor = this.current.fillColor;
  9929. const strokeColor = this.current.strokeColor;
  9930. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  9931. this.svg = bbox;
  9932. this.transformMatrix = matrix;
  9933. if (paintType === 2) {
  9934. const cssColor = _util.Util.makeHexColor(...color);
  9935. this.current.fillColor = cssColor;
  9936. this.current.strokeColor = cssColor;
  9937. }
  9938. this.executeOpTree(this.convertOpList(operatorList));
  9939. this.svg = svg;
  9940. this.transformMatrix = transformMatrix;
  9941. this.current.fillColor = fillColor;
  9942. this.current.strokeColor = strokeColor;
  9943. tiling.appendChild(bbox.childNodes[0]);
  9944. this.defs.appendChild(tiling);
  9945. return `url(#${tilingId})`;
  9946. }
  9947. _makeShadingPattern(args) {
  9948. switch (args[0]) {
  9949. case "RadialAxial":
  9950. const shadingId = `shading${shadingCount++}`;
  9951. const colorStops = args[3];
  9952. let gradient;
  9953. switch (args[1]) {
  9954. case "axial":
  9955. const point0 = args[4];
  9956. const point1 = args[5];
  9957. gradient = this.svgFactory.createElement("svg:linearGradient");
  9958. gradient.setAttributeNS(null, "id", shadingId);
  9959. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  9960. gradient.setAttributeNS(null, "x1", point0[0]);
  9961. gradient.setAttributeNS(null, "y1", point0[1]);
  9962. gradient.setAttributeNS(null, "x2", point1[0]);
  9963. gradient.setAttributeNS(null, "y2", point1[1]);
  9964. break;
  9965. case "radial":
  9966. const focalPoint = args[4];
  9967. const circlePoint = args[5];
  9968. const focalRadius = args[6];
  9969. const circleRadius = args[7];
  9970. gradient = this.svgFactory.createElement("svg:radialGradient");
  9971. gradient.setAttributeNS(null, "id", shadingId);
  9972. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  9973. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  9974. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  9975. gradient.setAttributeNS(null, "r", circleRadius);
  9976. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  9977. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  9978. gradient.setAttributeNS(null, "fr", focalRadius);
  9979. break;
  9980. default:
  9981. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  9982. }
  9983. for (const colorStop of colorStops) {
  9984. const stop = this.svgFactory.createElement("svg:stop");
  9985. stop.setAttributeNS(null, "offset", colorStop[0]);
  9986. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  9987. gradient.appendChild(stop);
  9988. }
  9989. this.defs.appendChild(gradient);
  9990. return `url(#${shadingId})`;
  9991. case "Mesh":
  9992. (0, _util.warn)("Unimplemented pattern Mesh");
  9993. return null;
  9994. case "Dummy":
  9995. return "hotpink";
  9996. default:
  9997. throw new Error(`Unknown IR type: ${args[0]}`);
  9998. }
  9999. }
  10000. setDash(dashArray, dashPhase) {
  10001. this.current.dashArray = dashArray;
  10002. this.current.dashPhase = dashPhase;
  10003. }
  10004. constructPath(ops, args) {
  10005. const current = this.current;
  10006. let x = current.x,
  10007. y = current.y;
  10008. let d = [];
  10009. let j = 0;
  10010. for (const op of ops) {
  10011. switch (op | 0) {
  10012. case _util.OPS.rectangle:
  10013. x = args[j++];
  10014. y = args[j++];
  10015. const width = args[j++];
  10016. const height = args[j++];
  10017. const xw = x + width;
  10018. const yh = y + height;
  10019. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  10020. break;
  10021. case _util.OPS.moveTo:
  10022. x = args[j++];
  10023. y = args[j++];
  10024. d.push("M", pf(x), pf(y));
  10025. break;
  10026. case _util.OPS.lineTo:
  10027. x = args[j++];
  10028. y = args[j++];
  10029. d.push("L", pf(x), pf(y));
  10030. break;
  10031. case _util.OPS.curveTo:
  10032. x = args[j + 4];
  10033. y = args[j + 5];
  10034. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  10035. j += 6;
  10036. break;
  10037. case _util.OPS.curveTo2:
  10038. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  10039. x = args[j + 2];
  10040. y = args[j + 3];
  10041. j += 4;
  10042. break;
  10043. case _util.OPS.curveTo3:
  10044. x = args[j + 2];
  10045. y = args[j + 3];
  10046. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  10047. j += 4;
  10048. break;
  10049. case _util.OPS.closePath:
  10050. d.push("Z");
  10051. break;
  10052. }
  10053. }
  10054. d = d.join(" ");
  10055. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  10056. d = current.path.getAttributeNS(null, "d") + d;
  10057. } else {
  10058. current.path = this.svgFactory.createElement("svg:path");
  10059. this._ensureTransformGroup().appendChild(current.path);
  10060. }
  10061. current.path.setAttributeNS(null, "d", d);
  10062. current.path.setAttributeNS(null, "fill", "none");
  10063. current.element = current.path;
  10064. current.setCurrentPoint(x, y);
  10065. }
  10066. endPath() {
  10067. const current = this.current;
  10068. current.path = null;
  10069. if (!this.pendingClip) {
  10070. return;
  10071. }
  10072. if (!current.element) {
  10073. this.pendingClip = null;
  10074. return;
  10075. }
  10076. const clipId = `clippath${clipCount++}`;
  10077. const clipPath = this.svgFactory.createElement("svg:clipPath");
  10078. clipPath.setAttributeNS(null, "id", clipId);
  10079. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  10080. const clipElement = current.element.cloneNode(true);
  10081. if (this.pendingClip === "evenodd") {
  10082. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  10083. } else {
  10084. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  10085. }
  10086. this.pendingClip = null;
  10087. clipPath.appendChild(clipElement);
  10088. this.defs.appendChild(clipPath);
  10089. if (current.activeClipUrl) {
  10090. current.clipGroup = null;
  10091. for (const prev of this.extraStack) {
  10092. prev.clipGroup = null;
  10093. }
  10094. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  10095. }
  10096. current.activeClipUrl = `url(#${clipId})`;
  10097. this.tgrp = null;
  10098. }
  10099. clip(type) {
  10100. this.pendingClip = type;
  10101. }
  10102. closePath() {
  10103. const current = this.current;
  10104. if (current.path) {
  10105. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  10106. current.path.setAttributeNS(null, "d", d);
  10107. }
  10108. }
  10109. setLeading(leading) {
  10110. this.current.leading = -leading;
  10111. }
  10112. setTextRise(textRise) {
  10113. this.current.textRise = textRise;
  10114. }
  10115. setTextRenderingMode(textRenderingMode) {
  10116. this.current.textRenderingMode = textRenderingMode;
  10117. }
  10118. setHScale(scale) {
  10119. this.current.textHScale = scale / 100;
  10120. }
  10121. setRenderingIntent(intent) {}
  10122. setFlatness(flatness) {}
  10123. setGState(states) {
  10124. for (const [key, value] of states) {
  10125. switch (key) {
  10126. case "LW":
  10127. this.setLineWidth(value);
  10128. break;
  10129. case "LC":
  10130. this.setLineCap(value);
  10131. break;
  10132. case "LJ":
  10133. this.setLineJoin(value);
  10134. break;
  10135. case "ML":
  10136. this.setMiterLimit(value);
  10137. break;
  10138. case "D":
  10139. this.setDash(value[0], value[1]);
  10140. break;
  10141. case "RI":
  10142. this.setRenderingIntent(value);
  10143. break;
  10144. case "FL":
  10145. this.setFlatness(value);
  10146. break;
  10147. case "Font":
  10148. this.setFont(value);
  10149. break;
  10150. case "CA":
  10151. this.setStrokeAlpha(value);
  10152. break;
  10153. case "ca":
  10154. this.setFillAlpha(value);
  10155. break;
  10156. default:
  10157. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  10158. break;
  10159. }
  10160. }
  10161. }
  10162. fill() {
  10163. const current = this.current;
  10164. if (current.element) {
  10165. current.element.setAttributeNS(null, "fill", current.fillColor);
  10166. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  10167. this.endPath();
  10168. }
  10169. }
  10170. stroke() {
  10171. const current = this.current;
  10172. if (current.element) {
  10173. this._setStrokeAttributes(current.element);
  10174. current.element.setAttributeNS(null, "fill", "none");
  10175. this.endPath();
  10176. }
  10177. }
  10178. _setStrokeAttributes(element, lineWidthScale = 1) {
  10179. const current = this.current;
  10180. let dashArray = current.dashArray;
  10181. if (lineWidthScale !== 1 && dashArray.length > 0) {
  10182. dashArray = dashArray.map(function (value) {
  10183. return lineWidthScale * value;
  10184. });
  10185. }
  10186. element.setAttributeNS(null, "stroke", current.strokeColor);
  10187. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  10188. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  10189. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  10190. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  10191. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  10192. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  10193. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  10194. }
  10195. eoFill() {
  10196. if (this.current.element) {
  10197. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  10198. }
  10199. this.fill();
  10200. }
  10201. fillStroke() {
  10202. this.stroke();
  10203. this.fill();
  10204. }
  10205. eoFillStroke() {
  10206. if (this.current.element) {
  10207. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  10208. }
  10209. this.fillStroke();
  10210. }
  10211. closeStroke() {
  10212. this.closePath();
  10213. this.stroke();
  10214. }
  10215. closeFillStroke() {
  10216. this.closePath();
  10217. this.fillStroke();
  10218. }
  10219. closeEOFillStroke() {
  10220. this.closePath();
  10221. this.eoFillStroke();
  10222. }
  10223. paintSolidColorImageMask() {
  10224. const rect = this.svgFactory.createElement("svg:rect");
  10225. rect.setAttributeNS(null, "x", "0");
  10226. rect.setAttributeNS(null, "y", "0");
  10227. rect.setAttributeNS(null, "width", "1px");
  10228. rect.setAttributeNS(null, "height", "1px");
  10229. rect.setAttributeNS(null, "fill", this.current.fillColor);
  10230. this._ensureTransformGroup().appendChild(rect);
  10231. }
  10232. paintImageXObject(objId) {
  10233. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  10234. if (!imgData) {
  10235. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  10236. return;
  10237. }
  10238. this.paintInlineImageXObject(imgData);
  10239. }
  10240. paintInlineImageXObject(imgData, mask) {
  10241. const width = imgData.width;
  10242. const height = imgData.height;
  10243. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  10244. const cliprect = this.svgFactory.createElement("svg:rect");
  10245. cliprect.setAttributeNS(null, "x", "0");
  10246. cliprect.setAttributeNS(null, "y", "0");
  10247. cliprect.setAttributeNS(null, "width", pf(width));
  10248. cliprect.setAttributeNS(null, "height", pf(height));
  10249. this.current.element = cliprect;
  10250. this.clip("nonzero");
  10251. const imgEl = this.svgFactory.createElement("svg:image");
  10252. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  10253. imgEl.setAttributeNS(null, "x", "0");
  10254. imgEl.setAttributeNS(null, "y", pf(-height));
  10255. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  10256. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  10257. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  10258. if (mask) {
  10259. mask.appendChild(imgEl);
  10260. } else {
  10261. this._ensureTransformGroup().appendChild(imgEl);
  10262. }
  10263. }
  10264. paintImageMaskXObject(imgData) {
  10265. const current = this.current;
  10266. const width = imgData.width;
  10267. const height = imgData.height;
  10268. const fillColor = current.fillColor;
  10269. current.maskId = `mask${maskCount++}`;
  10270. const mask = this.svgFactory.createElement("svg:mask");
  10271. mask.setAttributeNS(null, "id", current.maskId);
  10272. const rect = this.svgFactory.createElement("svg:rect");
  10273. rect.setAttributeNS(null, "x", "0");
  10274. rect.setAttributeNS(null, "y", "0");
  10275. rect.setAttributeNS(null, "width", pf(width));
  10276. rect.setAttributeNS(null, "height", pf(height));
  10277. rect.setAttributeNS(null, "fill", fillColor);
  10278. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  10279. this.defs.appendChild(mask);
  10280. this._ensureTransformGroup().appendChild(rect);
  10281. this.paintInlineImageXObject(imgData, mask);
  10282. }
  10283. paintFormXObjectBegin(matrix, bbox) {
  10284. if (Array.isArray(matrix) && matrix.length === 6) {
  10285. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  10286. }
  10287. if (bbox) {
  10288. const width = bbox[2] - bbox[0];
  10289. const height = bbox[3] - bbox[1];
  10290. const cliprect = this.svgFactory.createElement("svg:rect");
  10291. cliprect.setAttributeNS(null, "x", bbox[0]);
  10292. cliprect.setAttributeNS(null, "y", bbox[1]);
  10293. cliprect.setAttributeNS(null, "width", pf(width));
  10294. cliprect.setAttributeNS(null, "height", pf(height));
  10295. this.current.element = cliprect;
  10296. this.clip("nonzero");
  10297. this.endPath();
  10298. }
  10299. }
  10300. paintFormXObjectEnd() {}
  10301. _initialize(viewport) {
  10302. const svg = this.svgFactory.create(viewport.width, viewport.height);
  10303. const definitions = this.svgFactory.createElement("svg:defs");
  10304. svg.appendChild(definitions);
  10305. this.defs = definitions;
  10306. const rootGroup = this.svgFactory.createElement("svg:g");
  10307. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  10308. svg.appendChild(rootGroup);
  10309. this.svg = rootGroup;
  10310. return svg;
  10311. }
  10312. _ensureClipGroup() {
  10313. if (!this.current.clipGroup) {
  10314. const clipGroup = this.svgFactory.createElement("svg:g");
  10315. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  10316. this.svg.appendChild(clipGroup);
  10317. this.current.clipGroup = clipGroup;
  10318. }
  10319. return this.current.clipGroup;
  10320. }
  10321. _ensureTransformGroup() {
  10322. if (!this.tgrp) {
  10323. this.tgrp = this.svgFactory.createElement("svg:g");
  10324. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  10325. if (this.current.activeClipUrl) {
  10326. this._ensureClipGroup().appendChild(this.tgrp);
  10327. } else {
  10328. this.svg.appendChild(this.tgrp);
  10329. }
  10330. }
  10331. return this.tgrp;
  10332. }
  10333. };
  10334. }
  10335. /***/ }),
  10336. /* 21 */
  10337. /***/ ((__unused_webpack_module, exports) => {
  10338. Object.defineProperty(exports, "__esModule", ({
  10339. value: true
  10340. }));
  10341. exports.XfaLayer = void 0;
  10342. class XfaLayer {
  10343. static setupStorage(html, id, element, storage, intent) {
  10344. const storedData = storage.getValue(id, {
  10345. value: null
  10346. });
  10347. switch (element.name) {
  10348. case "textarea":
  10349. if (storedData.value !== null) {
  10350. html.textContent = storedData.value;
  10351. }
  10352. if (intent === "print") {
  10353. break;
  10354. }
  10355. html.addEventListener("input", event => {
  10356. storage.setValue(id, {
  10357. value: event.target.value
  10358. });
  10359. });
  10360. break;
  10361. case "input":
  10362. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  10363. if (storedData.value === element.attributes.xfaOn) {
  10364. html.setAttribute("checked", true);
  10365. }
  10366. if (intent === "print") {
  10367. break;
  10368. }
  10369. html.addEventListener("change", event => {
  10370. storage.setValue(id, {
  10371. value: event.target.getAttribute("xfaOn")
  10372. });
  10373. });
  10374. } else {
  10375. if (storedData.value !== null) {
  10376. html.setAttribute("value", storedData.value);
  10377. }
  10378. if (intent === "print") {
  10379. break;
  10380. }
  10381. html.addEventListener("input", event => {
  10382. storage.setValue(id, {
  10383. value: event.target.value
  10384. });
  10385. });
  10386. }
  10387. break;
  10388. case "select":
  10389. if (storedData.value !== null) {
  10390. for (const option of element.children) {
  10391. if (option.attributes.value === storedData.value) {
  10392. option.attributes.selected = true;
  10393. }
  10394. }
  10395. }
  10396. html.addEventListener("input", event => {
  10397. const options = event.target.options;
  10398. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  10399. storage.setValue(id, {
  10400. value
  10401. });
  10402. });
  10403. break;
  10404. }
  10405. }
  10406. static setAttributes(html, element, storage, intent) {
  10407. const {
  10408. attributes
  10409. } = element;
  10410. if (attributes.type === "radio") {
  10411. attributes.name = `${attributes.name}-${intent}`;
  10412. }
  10413. for (const [key, value] of Object.entries(attributes)) {
  10414. if (value === null || value === undefined || key === "dataId") {
  10415. continue;
  10416. }
  10417. if (key !== "style") {
  10418. if (key === "textContent") {
  10419. html.textContent = value;
  10420. } else if (key === "class") {
  10421. html.setAttribute(key, value.join(" "));
  10422. } else {
  10423. html.setAttribute(key, value);
  10424. }
  10425. } else {
  10426. Object.assign(html.style, value);
  10427. }
  10428. }
  10429. if (storage && attributes.dataId) {
  10430. this.setupStorage(html, attributes.dataId, element, storage);
  10431. }
  10432. }
  10433. static render(parameters) {
  10434. const storage = parameters.annotationStorage;
  10435. const root = parameters.xfa;
  10436. const intent = parameters.intent || "display";
  10437. const rootHtml = document.createElement(root.name);
  10438. if (root.attributes) {
  10439. this.setAttributes(rootHtml, root);
  10440. }
  10441. const stack = [[root, -1, rootHtml]];
  10442. const rootDiv = parameters.div;
  10443. rootDiv.appendChild(rootHtml);
  10444. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  10445. rootDiv.style.transform = transform;
  10446. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  10447. while (stack.length > 0) {
  10448. const [parent, i, html] = stack[stack.length - 1];
  10449. if (i + 1 === parent.children.length) {
  10450. stack.pop();
  10451. continue;
  10452. }
  10453. const child = parent.children[++stack[stack.length - 1][1]];
  10454. if (child === null) {
  10455. continue;
  10456. }
  10457. const {
  10458. name
  10459. } = child;
  10460. if (name === "#text") {
  10461. html.appendChild(document.createTextNode(child.value));
  10462. continue;
  10463. }
  10464. let childHtml;
  10465. if (child?.attributes?.xmlns) {
  10466. childHtml = document.createElementNS(child.attributes.xmlns, name);
  10467. } else {
  10468. childHtml = document.createElement(name);
  10469. }
  10470. html.appendChild(childHtml);
  10471. if (child.attributes) {
  10472. this.setAttributes(childHtml, child, storage, intent);
  10473. }
  10474. if (child.children && child.children.length > 0) {
  10475. stack.push([child, -1, childHtml]);
  10476. } else if (child.value) {
  10477. childHtml.appendChild(document.createTextNode(child.value));
  10478. }
  10479. }
  10480. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  10481. el.setAttribute("readOnly", true);
  10482. }
  10483. }
  10484. static update(parameters) {
  10485. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  10486. parameters.div.style.transform = transform;
  10487. parameters.div.hidden = false;
  10488. }
  10489. }
  10490. exports.XfaLayer = XfaLayer;
  10491. /***/ }),
  10492. /* 22 */
  10493. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10494. Object.defineProperty(exports, "__esModule", ({
  10495. value: true
  10496. }));
  10497. exports.PDFNodeStream = void 0;
  10498. var _util = __w_pdfjs_require__(2);
  10499. var _network_utils = __w_pdfjs_require__(23);
  10500. ;
  10501. const fs = require("fs");
  10502. const http = require("http");
  10503. const https = require("https");
  10504. const url = require("url");
  10505. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  10506. function parseUrl(sourceUrl) {
  10507. const parsedUrl = url.parse(sourceUrl);
  10508. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  10509. return parsedUrl;
  10510. }
  10511. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  10512. return url.parse(`file:///${sourceUrl}`);
  10513. }
  10514. if (!parsedUrl.host) {
  10515. parsedUrl.protocol = "file:";
  10516. }
  10517. return parsedUrl;
  10518. }
  10519. class PDFNodeStream {
  10520. constructor(source) {
  10521. this.source = source;
  10522. this.url = parseUrl(source.url);
  10523. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  10524. this.isFsUrl = this.url.protocol === "file:";
  10525. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  10526. this._fullRequestReader = null;
  10527. this._rangeRequestReaders = [];
  10528. }
  10529. get _progressiveDataLength() {
  10530. return this._fullRequestReader?._loaded ?? 0;
  10531. }
  10532. getFullReader() {
  10533. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  10534. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  10535. return this._fullRequestReader;
  10536. }
  10537. getRangeReader(start, end) {
  10538. if (end <= this._progressiveDataLength) {
  10539. return null;
  10540. }
  10541. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  10542. this._rangeRequestReaders.push(rangeReader);
  10543. return rangeReader;
  10544. }
  10545. cancelAllRequests(reason) {
  10546. if (this._fullRequestReader) {
  10547. this._fullRequestReader.cancel(reason);
  10548. }
  10549. for (const reader of this._rangeRequestReaders.slice(0)) {
  10550. reader.cancel(reason);
  10551. }
  10552. }
  10553. }
  10554. exports.PDFNodeStream = PDFNodeStream;
  10555. class BaseFullReader {
  10556. constructor(stream) {
  10557. this._url = stream.url;
  10558. this._done = false;
  10559. this._storedError = null;
  10560. this.onProgress = null;
  10561. const source = stream.source;
  10562. this._contentLength = source.length;
  10563. this._loaded = 0;
  10564. this._filename = null;
  10565. this._disableRange = source.disableRange || false;
  10566. this._rangeChunkSize = source.rangeChunkSize;
  10567. if (!this._rangeChunkSize && !this._disableRange) {
  10568. this._disableRange = true;
  10569. }
  10570. this._isStreamingSupported = !source.disableStream;
  10571. this._isRangeSupported = !source.disableRange;
  10572. this._readableStream = null;
  10573. this._readCapability = (0, _util.createPromiseCapability)();
  10574. this._headersCapability = (0, _util.createPromiseCapability)();
  10575. }
  10576. get headersReady() {
  10577. return this._headersCapability.promise;
  10578. }
  10579. get filename() {
  10580. return this._filename;
  10581. }
  10582. get contentLength() {
  10583. return this._contentLength;
  10584. }
  10585. get isRangeSupported() {
  10586. return this._isRangeSupported;
  10587. }
  10588. get isStreamingSupported() {
  10589. return this._isStreamingSupported;
  10590. }
  10591. async read() {
  10592. await this._readCapability.promise;
  10593. if (this._done) {
  10594. return {
  10595. value: undefined,
  10596. done: true
  10597. };
  10598. }
  10599. if (this._storedError) {
  10600. throw this._storedError;
  10601. }
  10602. const chunk = this._readableStream.read();
  10603. if (chunk === null) {
  10604. this._readCapability = (0, _util.createPromiseCapability)();
  10605. return this.read();
  10606. }
  10607. this._loaded += chunk.length;
  10608. if (this.onProgress) {
  10609. this.onProgress({
  10610. loaded: this._loaded,
  10611. total: this._contentLength
  10612. });
  10613. }
  10614. const buffer = new Uint8Array(chunk).buffer;
  10615. return {
  10616. value: buffer,
  10617. done: false
  10618. };
  10619. }
  10620. cancel(reason) {
  10621. if (!this._readableStream) {
  10622. this._error(reason);
  10623. return;
  10624. }
  10625. this._readableStream.destroy(reason);
  10626. }
  10627. _error(reason) {
  10628. this._storedError = reason;
  10629. this._readCapability.resolve();
  10630. }
  10631. _setReadableStream(readableStream) {
  10632. this._readableStream = readableStream;
  10633. readableStream.on("readable", () => {
  10634. this._readCapability.resolve();
  10635. });
  10636. readableStream.on("end", () => {
  10637. readableStream.destroy();
  10638. this._done = true;
  10639. this._readCapability.resolve();
  10640. });
  10641. readableStream.on("error", reason => {
  10642. this._error(reason);
  10643. });
  10644. if (!this._isStreamingSupported && this._isRangeSupported) {
  10645. this._error(new _util.AbortException("streaming is disabled"));
  10646. }
  10647. if (this._storedError) {
  10648. this._readableStream.destroy(this._storedError);
  10649. }
  10650. }
  10651. }
  10652. class BaseRangeReader {
  10653. constructor(stream) {
  10654. this._url = stream.url;
  10655. this._done = false;
  10656. this._storedError = null;
  10657. this.onProgress = null;
  10658. this._loaded = 0;
  10659. this._readableStream = null;
  10660. this._readCapability = (0, _util.createPromiseCapability)();
  10661. const source = stream.source;
  10662. this._isStreamingSupported = !source.disableStream;
  10663. }
  10664. get isStreamingSupported() {
  10665. return this._isStreamingSupported;
  10666. }
  10667. async read() {
  10668. await this._readCapability.promise;
  10669. if (this._done) {
  10670. return {
  10671. value: undefined,
  10672. done: true
  10673. };
  10674. }
  10675. if (this._storedError) {
  10676. throw this._storedError;
  10677. }
  10678. const chunk = this._readableStream.read();
  10679. if (chunk === null) {
  10680. this._readCapability = (0, _util.createPromiseCapability)();
  10681. return this.read();
  10682. }
  10683. this._loaded += chunk.length;
  10684. if (this.onProgress) {
  10685. this.onProgress({
  10686. loaded: this._loaded
  10687. });
  10688. }
  10689. const buffer = new Uint8Array(chunk).buffer;
  10690. return {
  10691. value: buffer,
  10692. done: false
  10693. };
  10694. }
  10695. cancel(reason) {
  10696. if (!this._readableStream) {
  10697. this._error(reason);
  10698. return;
  10699. }
  10700. this._readableStream.destroy(reason);
  10701. }
  10702. _error(reason) {
  10703. this._storedError = reason;
  10704. this._readCapability.resolve();
  10705. }
  10706. _setReadableStream(readableStream) {
  10707. this._readableStream = readableStream;
  10708. readableStream.on("readable", () => {
  10709. this._readCapability.resolve();
  10710. });
  10711. readableStream.on("end", () => {
  10712. readableStream.destroy();
  10713. this._done = true;
  10714. this._readCapability.resolve();
  10715. });
  10716. readableStream.on("error", reason => {
  10717. this._error(reason);
  10718. });
  10719. if (this._storedError) {
  10720. this._readableStream.destroy(this._storedError);
  10721. }
  10722. }
  10723. }
  10724. function createRequestOptions(parsedUrl, headers) {
  10725. return {
  10726. protocol: parsedUrl.protocol,
  10727. auth: parsedUrl.auth,
  10728. host: parsedUrl.hostname,
  10729. port: parsedUrl.port,
  10730. path: parsedUrl.path,
  10731. method: "GET",
  10732. headers
  10733. };
  10734. }
  10735. class PDFNodeStreamFullReader extends BaseFullReader {
  10736. constructor(stream) {
  10737. super(stream);
  10738. const handleResponse = response => {
  10739. if (response.statusCode === 404) {
  10740. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  10741. this._storedError = error;
  10742. this._headersCapability.reject(error);
  10743. return;
  10744. }
  10745. this._headersCapability.resolve();
  10746. this._setReadableStream(response);
  10747. const getResponseHeader = name => {
  10748. return this._readableStream.headers[name.toLowerCase()];
  10749. };
  10750. const {
  10751. allowRangeRequests,
  10752. suggestedLength
  10753. } = (0, _network_utils.validateRangeRequestCapabilities)({
  10754. getResponseHeader,
  10755. isHttp: stream.isHttp,
  10756. rangeChunkSize: this._rangeChunkSize,
  10757. disableRange: this._disableRange
  10758. });
  10759. this._isRangeSupported = allowRangeRequests;
  10760. this._contentLength = suggestedLength || this._contentLength;
  10761. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  10762. };
  10763. this._request = null;
  10764. if (this._url.protocol === "http:") {
  10765. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  10766. } else {
  10767. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  10768. }
  10769. this._request.on("error", reason => {
  10770. this._storedError = reason;
  10771. this._headersCapability.reject(reason);
  10772. });
  10773. this._request.end();
  10774. }
  10775. }
  10776. class PDFNodeStreamRangeReader extends BaseRangeReader {
  10777. constructor(stream, start, end) {
  10778. super(stream);
  10779. this._httpHeaders = {};
  10780. for (const property in stream.httpHeaders) {
  10781. const value = stream.httpHeaders[property];
  10782. if (typeof value === "undefined") {
  10783. continue;
  10784. }
  10785. this._httpHeaders[property] = value;
  10786. }
  10787. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  10788. const handleResponse = response => {
  10789. if (response.statusCode === 404) {
  10790. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  10791. this._storedError = error;
  10792. return;
  10793. }
  10794. this._setReadableStream(response);
  10795. };
  10796. this._request = null;
  10797. if (this._url.protocol === "http:") {
  10798. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  10799. } else {
  10800. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  10801. }
  10802. this._request.on("error", reason => {
  10803. this._storedError = reason;
  10804. });
  10805. this._request.end();
  10806. }
  10807. }
  10808. class PDFNodeStreamFsFullReader extends BaseFullReader {
  10809. constructor(stream) {
  10810. super(stream);
  10811. let path = decodeURIComponent(this._url.path);
  10812. if (fileUriRegex.test(this._url.href)) {
  10813. path = path.replace(/^\//, "");
  10814. }
  10815. fs.lstat(path, (error, stat) => {
  10816. if (error) {
  10817. if (error.code === "ENOENT") {
  10818. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  10819. }
  10820. this._storedError = error;
  10821. this._headersCapability.reject(error);
  10822. return;
  10823. }
  10824. this._contentLength = stat.size;
  10825. this._setReadableStream(fs.createReadStream(path));
  10826. this._headersCapability.resolve();
  10827. });
  10828. }
  10829. }
  10830. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  10831. constructor(stream, start, end) {
  10832. super(stream);
  10833. let path = decodeURIComponent(this._url.path);
  10834. if (fileUriRegex.test(this._url.href)) {
  10835. path = path.replace(/^\//, "");
  10836. }
  10837. this._setReadableStream(fs.createReadStream(path, {
  10838. start,
  10839. end: end - 1
  10840. }));
  10841. }
  10842. }
  10843. /***/ }),
  10844. /* 23 */
  10845. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10846. Object.defineProperty(exports, "__esModule", ({
  10847. value: true
  10848. }));
  10849. exports.createResponseStatusError = createResponseStatusError;
  10850. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  10851. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  10852. exports.validateResponseStatus = validateResponseStatus;
  10853. var _util = __w_pdfjs_require__(2);
  10854. var _content_disposition = __w_pdfjs_require__(24);
  10855. var _display_utils = __w_pdfjs_require__(1);
  10856. function validateRangeRequestCapabilities({
  10857. getResponseHeader,
  10858. isHttp,
  10859. rangeChunkSize,
  10860. disableRange
  10861. }) {
  10862. (0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero");
  10863. const returnValues = {
  10864. allowRangeRequests: false,
  10865. suggestedLength: undefined
  10866. };
  10867. const length = parseInt(getResponseHeader("Content-Length"), 10);
  10868. if (!Number.isInteger(length)) {
  10869. return returnValues;
  10870. }
  10871. returnValues.suggestedLength = length;
  10872. if (length <= 2 * rangeChunkSize) {
  10873. return returnValues;
  10874. }
  10875. if (disableRange || !isHttp) {
  10876. return returnValues;
  10877. }
  10878. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  10879. return returnValues;
  10880. }
  10881. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  10882. if (contentEncoding !== "identity") {
  10883. return returnValues;
  10884. }
  10885. returnValues.allowRangeRequests = true;
  10886. return returnValues;
  10887. }
  10888. function extractFilenameFromHeader(getResponseHeader) {
  10889. const contentDisposition = getResponseHeader("Content-Disposition");
  10890. if (contentDisposition) {
  10891. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  10892. if (filename.includes("%")) {
  10893. try {
  10894. filename = decodeURIComponent(filename);
  10895. } catch (ex) {}
  10896. }
  10897. if ((0, _display_utils.isPdfFile)(filename)) {
  10898. return filename;
  10899. }
  10900. }
  10901. return null;
  10902. }
  10903. function createResponseStatusError(status, url) {
  10904. if (status === 404 || status === 0 && url.startsWith("file:")) {
  10905. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  10906. }
  10907. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  10908. }
  10909. function validateResponseStatus(status) {
  10910. return status === 200 || status === 206;
  10911. }
  10912. /***/ }),
  10913. /* 24 */
  10914. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10915. Object.defineProperty(exports, "__esModule", ({
  10916. value: true
  10917. }));
  10918. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  10919. var _util = __w_pdfjs_require__(2);
  10920. function getFilenameFromContentDispositionHeader(contentDisposition) {
  10921. let needsEncodingFixup = true;
  10922. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  10923. if (tmp) {
  10924. tmp = tmp[1];
  10925. let filename = rfc2616unquote(tmp);
  10926. filename = unescape(filename);
  10927. filename = rfc5987decode(filename);
  10928. filename = rfc2047decode(filename);
  10929. return fixupEncoding(filename);
  10930. }
  10931. tmp = rfc2231getparam(contentDisposition);
  10932. if (tmp) {
  10933. const filename = rfc2047decode(tmp);
  10934. return fixupEncoding(filename);
  10935. }
  10936. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  10937. if (tmp) {
  10938. tmp = tmp[1];
  10939. let filename = rfc2616unquote(tmp);
  10940. filename = rfc2047decode(filename);
  10941. return fixupEncoding(filename);
  10942. }
  10943. function toParamRegExp(attributePattern, flags) {
  10944. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  10945. }
  10946. function textdecode(encoding, value) {
  10947. if (encoding) {
  10948. if (!/^[\x00-\xFF]+$/.test(value)) {
  10949. return value;
  10950. }
  10951. try {
  10952. const decoder = new TextDecoder(encoding, {
  10953. fatal: true
  10954. });
  10955. const buffer = (0, _util.stringToBytes)(value);
  10956. value = decoder.decode(buffer);
  10957. needsEncodingFixup = false;
  10958. } catch (e) {
  10959. if (/^utf-?8$/i.test(encoding)) {
  10960. try {
  10961. value = decodeURIComponent(escape(value));
  10962. needsEncodingFixup = false;
  10963. } catch (err) {}
  10964. }
  10965. }
  10966. }
  10967. return value;
  10968. }
  10969. function fixupEncoding(value) {
  10970. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  10971. value = textdecode("utf-8", value);
  10972. if (needsEncodingFixup) {
  10973. value = textdecode("iso-8859-1", value);
  10974. }
  10975. }
  10976. return value;
  10977. }
  10978. function rfc2231getparam(contentDispositionStr) {
  10979. const matches = [];
  10980. let match;
  10981. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  10982. while ((match = iter.exec(contentDispositionStr)) !== null) {
  10983. let [, n, quot, part] = match;
  10984. n = parseInt(n, 10);
  10985. if (n in matches) {
  10986. if (n === 0) {
  10987. break;
  10988. }
  10989. continue;
  10990. }
  10991. matches[n] = [quot, part];
  10992. }
  10993. const parts = [];
  10994. for (let n = 0; n < matches.length; ++n) {
  10995. if (!(n in matches)) {
  10996. break;
  10997. }
  10998. let [quot, part] = matches[n];
  10999. part = rfc2616unquote(part);
  11000. if (quot) {
  11001. part = unescape(part);
  11002. if (n === 0) {
  11003. part = rfc5987decode(part);
  11004. }
  11005. }
  11006. parts.push(part);
  11007. }
  11008. return parts.join("");
  11009. }
  11010. function rfc2616unquote(value) {
  11011. if (value.startsWith('"')) {
  11012. const parts = value.slice(1).split('\\"');
  11013. for (let i = 0; i < parts.length; ++i) {
  11014. const quotindex = parts[i].indexOf('"');
  11015. if (quotindex !== -1) {
  11016. parts[i] = parts[i].slice(0, quotindex);
  11017. parts.length = i + 1;
  11018. }
  11019. parts[i] = parts[i].replace(/\\(.)/g, "$1");
  11020. }
  11021. value = parts.join('"');
  11022. }
  11023. return value;
  11024. }
  11025. function rfc5987decode(extvalue) {
  11026. const encodingend = extvalue.indexOf("'");
  11027. if (encodingend === -1) {
  11028. return extvalue;
  11029. }
  11030. const encoding = extvalue.slice(0, encodingend);
  11031. const langvalue = extvalue.slice(encodingend + 1);
  11032. const value = langvalue.replace(/^[^']*'/, "");
  11033. return textdecode(encoding, value);
  11034. }
  11035. function rfc2047decode(value) {
  11036. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  11037. return value;
  11038. }
  11039. return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  11040. if (encoding === "q" || encoding === "Q") {
  11041. text = text.replace(/_/g, " ");
  11042. text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  11043. return String.fromCharCode(parseInt(hex, 16));
  11044. });
  11045. return textdecode(charset, text);
  11046. }
  11047. try {
  11048. text = atob(text);
  11049. } catch (e) {}
  11050. return textdecode(charset, text);
  11051. });
  11052. }
  11053. return "";
  11054. }
  11055. /***/ }),
  11056. /* 25 */
  11057. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11058. Object.defineProperty(exports, "__esModule", ({
  11059. value: true
  11060. }));
  11061. exports.PDFNetworkStream = void 0;
  11062. var _util = __w_pdfjs_require__(2);
  11063. var _network_utils = __w_pdfjs_require__(23);
  11064. ;
  11065. const OK_RESPONSE = 200;
  11066. const PARTIAL_CONTENT_RESPONSE = 206;
  11067. function getArrayBuffer(xhr) {
  11068. const data = xhr.response;
  11069. if (typeof data !== "string") {
  11070. return data;
  11071. }
  11072. const array = (0, _util.stringToBytes)(data);
  11073. return array.buffer;
  11074. }
  11075. class NetworkManager {
  11076. constructor(url, args) {
  11077. this.url = url;
  11078. args = args || {};
  11079. this.isHttp = /^https?:/i.test(url);
  11080. this.httpHeaders = this.isHttp && args.httpHeaders || {};
  11081. this.withCredentials = args.withCredentials || false;
  11082. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  11083. return new XMLHttpRequest();
  11084. };
  11085. this.currXhrId = 0;
  11086. this.pendingRequests = Object.create(null);
  11087. }
  11088. requestRange(begin, end, listeners) {
  11089. const args = {
  11090. begin,
  11091. end
  11092. };
  11093. for (const prop in listeners) {
  11094. args[prop] = listeners[prop];
  11095. }
  11096. return this.request(args);
  11097. }
  11098. requestFull(listeners) {
  11099. return this.request(listeners);
  11100. }
  11101. request(args) {
  11102. const xhr = this.getXhr();
  11103. const xhrId = this.currXhrId++;
  11104. const pendingRequest = this.pendingRequests[xhrId] = {
  11105. xhr
  11106. };
  11107. xhr.open("GET", this.url);
  11108. xhr.withCredentials = this.withCredentials;
  11109. for (const property in this.httpHeaders) {
  11110. const value = this.httpHeaders[property];
  11111. if (typeof value === "undefined") {
  11112. continue;
  11113. }
  11114. xhr.setRequestHeader(property, value);
  11115. }
  11116. if (this.isHttp && "begin" in args && "end" in args) {
  11117. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  11118. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  11119. } else {
  11120. pendingRequest.expectedStatus = OK_RESPONSE;
  11121. }
  11122. xhr.responseType = "arraybuffer";
  11123. if (args.onError) {
  11124. xhr.onerror = function (evt) {
  11125. args.onError(xhr.status);
  11126. };
  11127. }
  11128. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  11129. xhr.onprogress = this.onProgress.bind(this, xhrId);
  11130. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  11131. pendingRequest.onDone = args.onDone;
  11132. pendingRequest.onError = args.onError;
  11133. pendingRequest.onProgress = args.onProgress;
  11134. xhr.send(null);
  11135. return xhrId;
  11136. }
  11137. onProgress(xhrId, evt) {
  11138. const pendingRequest = this.pendingRequests[xhrId];
  11139. if (!pendingRequest) {
  11140. return;
  11141. }
  11142. if (pendingRequest.onProgress) {
  11143. pendingRequest.onProgress(evt);
  11144. }
  11145. }
  11146. onStateChange(xhrId, evt) {
  11147. const pendingRequest = this.pendingRequests[xhrId];
  11148. if (!pendingRequest) {
  11149. return;
  11150. }
  11151. const xhr = pendingRequest.xhr;
  11152. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  11153. pendingRequest.onHeadersReceived();
  11154. delete pendingRequest.onHeadersReceived;
  11155. }
  11156. if (xhr.readyState !== 4) {
  11157. return;
  11158. }
  11159. if (!(xhrId in this.pendingRequests)) {
  11160. return;
  11161. }
  11162. delete this.pendingRequests[xhrId];
  11163. if (xhr.status === 0 && this.isHttp) {
  11164. if (pendingRequest.onError) {
  11165. pendingRequest.onError(xhr.status);
  11166. }
  11167. return;
  11168. }
  11169. const xhrStatus = xhr.status || OK_RESPONSE;
  11170. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  11171. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  11172. if (pendingRequest.onError) {
  11173. pendingRequest.onError(xhr.status);
  11174. }
  11175. return;
  11176. }
  11177. const chunk = getArrayBuffer(xhr);
  11178. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  11179. const rangeHeader = xhr.getResponseHeader("Content-Range");
  11180. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  11181. pendingRequest.onDone({
  11182. begin: parseInt(matches[1], 10),
  11183. chunk
  11184. });
  11185. } else if (chunk) {
  11186. pendingRequest.onDone({
  11187. begin: 0,
  11188. chunk
  11189. });
  11190. } else if (pendingRequest.onError) {
  11191. pendingRequest.onError(xhr.status);
  11192. }
  11193. }
  11194. getRequestXhr(xhrId) {
  11195. return this.pendingRequests[xhrId].xhr;
  11196. }
  11197. isPendingRequest(xhrId) {
  11198. return xhrId in this.pendingRequests;
  11199. }
  11200. abortRequest(xhrId) {
  11201. const xhr = this.pendingRequests[xhrId].xhr;
  11202. delete this.pendingRequests[xhrId];
  11203. xhr.abort();
  11204. }
  11205. }
  11206. class PDFNetworkStream {
  11207. constructor(source) {
  11208. this._source = source;
  11209. this._manager = new NetworkManager(source.url, {
  11210. httpHeaders: source.httpHeaders,
  11211. withCredentials: source.withCredentials
  11212. });
  11213. this._rangeChunkSize = source.rangeChunkSize;
  11214. this._fullRequestReader = null;
  11215. this._rangeRequestReaders = [];
  11216. }
  11217. _onRangeRequestReaderClosed(reader) {
  11218. const i = this._rangeRequestReaders.indexOf(reader);
  11219. if (i >= 0) {
  11220. this._rangeRequestReaders.splice(i, 1);
  11221. }
  11222. }
  11223. getFullReader() {
  11224. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  11225. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  11226. return this._fullRequestReader;
  11227. }
  11228. getRangeReader(begin, end) {
  11229. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  11230. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  11231. this._rangeRequestReaders.push(reader);
  11232. return reader;
  11233. }
  11234. cancelAllRequests(reason) {
  11235. if (this._fullRequestReader) {
  11236. this._fullRequestReader.cancel(reason);
  11237. }
  11238. for (const reader of this._rangeRequestReaders.slice(0)) {
  11239. reader.cancel(reason);
  11240. }
  11241. }
  11242. }
  11243. exports.PDFNetworkStream = PDFNetworkStream;
  11244. class PDFNetworkStreamFullRequestReader {
  11245. constructor(manager, source) {
  11246. this._manager = manager;
  11247. const args = {
  11248. onHeadersReceived: this._onHeadersReceived.bind(this),
  11249. onDone: this._onDone.bind(this),
  11250. onError: this._onError.bind(this),
  11251. onProgress: this._onProgress.bind(this)
  11252. };
  11253. this._url = source.url;
  11254. this._fullRequestId = manager.requestFull(args);
  11255. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  11256. this._disableRange = source.disableRange || false;
  11257. this._contentLength = source.length;
  11258. this._rangeChunkSize = source.rangeChunkSize;
  11259. if (!this._rangeChunkSize && !this._disableRange) {
  11260. this._disableRange = true;
  11261. }
  11262. this._isStreamingSupported = false;
  11263. this._isRangeSupported = false;
  11264. this._cachedChunks = [];
  11265. this._requests = [];
  11266. this._done = false;
  11267. this._storedError = undefined;
  11268. this._filename = null;
  11269. this.onProgress = null;
  11270. }
  11271. _onHeadersReceived() {
  11272. const fullRequestXhrId = this._fullRequestId;
  11273. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  11274. const getResponseHeader = name => {
  11275. return fullRequestXhr.getResponseHeader(name);
  11276. };
  11277. const {
  11278. allowRangeRequests,
  11279. suggestedLength
  11280. } = (0, _network_utils.validateRangeRequestCapabilities)({
  11281. getResponseHeader,
  11282. isHttp: this._manager.isHttp,
  11283. rangeChunkSize: this._rangeChunkSize,
  11284. disableRange: this._disableRange
  11285. });
  11286. if (allowRangeRequests) {
  11287. this._isRangeSupported = true;
  11288. }
  11289. this._contentLength = suggestedLength || this._contentLength;
  11290. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  11291. if (this._isRangeSupported) {
  11292. this._manager.abortRequest(fullRequestXhrId);
  11293. }
  11294. this._headersReceivedCapability.resolve();
  11295. }
  11296. _onDone(args) {
  11297. if (args) {
  11298. if (this._requests.length > 0) {
  11299. const requestCapability = this._requests.shift();
  11300. requestCapability.resolve({
  11301. value: args.chunk,
  11302. done: false
  11303. });
  11304. } else {
  11305. this._cachedChunks.push(args.chunk);
  11306. }
  11307. }
  11308. this._done = true;
  11309. if (this._cachedChunks.length > 0) {
  11310. return;
  11311. }
  11312. for (const requestCapability of this._requests) {
  11313. requestCapability.resolve({
  11314. value: undefined,
  11315. done: true
  11316. });
  11317. }
  11318. this._requests.length = 0;
  11319. }
  11320. _onError(status) {
  11321. const url = this._url;
  11322. const exception = (0, _network_utils.createResponseStatusError)(status, url);
  11323. this._storedError = exception;
  11324. this._headersReceivedCapability.reject(exception);
  11325. for (const requestCapability of this._requests) {
  11326. requestCapability.reject(exception);
  11327. }
  11328. this._requests.length = 0;
  11329. this._cachedChunks.length = 0;
  11330. }
  11331. _onProgress(data) {
  11332. if (this.onProgress) {
  11333. this.onProgress({
  11334. loaded: data.loaded,
  11335. total: data.lengthComputable ? data.total : this._contentLength
  11336. });
  11337. }
  11338. }
  11339. get filename() {
  11340. return this._filename;
  11341. }
  11342. get isRangeSupported() {
  11343. return this._isRangeSupported;
  11344. }
  11345. get isStreamingSupported() {
  11346. return this._isStreamingSupported;
  11347. }
  11348. get contentLength() {
  11349. return this._contentLength;
  11350. }
  11351. get headersReady() {
  11352. return this._headersReceivedCapability.promise;
  11353. }
  11354. async read() {
  11355. if (this._storedError) {
  11356. throw this._storedError;
  11357. }
  11358. if (this._cachedChunks.length > 0) {
  11359. const chunk = this._cachedChunks.shift();
  11360. return {
  11361. value: chunk,
  11362. done: false
  11363. };
  11364. }
  11365. if (this._done) {
  11366. return {
  11367. value: undefined,
  11368. done: true
  11369. };
  11370. }
  11371. const requestCapability = (0, _util.createPromiseCapability)();
  11372. this._requests.push(requestCapability);
  11373. return requestCapability.promise;
  11374. }
  11375. cancel(reason) {
  11376. this._done = true;
  11377. this._headersReceivedCapability.reject(reason);
  11378. for (const requestCapability of this._requests) {
  11379. requestCapability.resolve({
  11380. value: undefined,
  11381. done: true
  11382. });
  11383. }
  11384. this._requests.length = 0;
  11385. if (this._manager.isPendingRequest(this._fullRequestId)) {
  11386. this._manager.abortRequest(this._fullRequestId);
  11387. }
  11388. this._fullRequestReader = null;
  11389. }
  11390. }
  11391. class PDFNetworkStreamRangeRequestReader {
  11392. constructor(manager, begin, end) {
  11393. this._manager = manager;
  11394. const args = {
  11395. onDone: this._onDone.bind(this),
  11396. onProgress: this._onProgress.bind(this)
  11397. };
  11398. this._requestId = manager.requestRange(begin, end, args);
  11399. this._requests = [];
  11400. this._queuedChunk = null;
  11401. this._done = false;
  11402. this.onProgress = null;
  11403. this.onClosed = null;
  11404. }
  11405. _close() {
  11406. if (this.onClosed) {
  11407. this.onClosed(this);
  11408. }
  11409. }
  11410. _onDone(data) {
  11411. const chunk = data.chunk;
  11412. if (this._requests.length > 0) {
  11413. const requestCapability = this._requests.shift();
  11414. requestCapability.resolve({
  11415. value: chunk,
  11416. done: false
  11417. });
  11418. } else {
  11419. this._queuedChunk = chunk;
  11420. }
  11421. this._done = true;
  11422. for (const requestCapability of this._requests) {
  11423. requestCapability.resolve({
  11424. value: undefined,
  11425. done: true
  11426. });
  11427. }
  11428. this._requests.length = 0;
  11429. this._close();
  11430. }
  11431. _onProgress(evt) {
  11432. if (!this.isStreamingSupported && this.onProgress) {
  11433. this.onProgress({
  11434. loaded: evt.loaded
  11435. });
  11436. }
  11437. }
  11438. get isStreamingSupported() {
  11439. return false;
  11440. }
  11441. async read() {
  11442. if (this._queuedChunk !== null) {
  11443. const chunk = this._queuedChunk;
  11444. this._queuedChunk = null;
  11445. return {
  11446. value: chunk,
  11447. done: false
  11448. };
  11449. }
  11450. if (this._done) {
  11451. return {
  11452. value: undefined,
  11453. done: true
  11454. };
  11455. }
  11456. const requestCapability = (0, _util.createPromiseCapability)();
  11457. this._requests.push(requestCapability);
  11458. return requestCapability.promise;
  11459. }
  11460. cancel(reason) {
  11461. this._done = true;
  11462. for (const requestCapability of this._requests) {
  11463. requestCapability.resolve({
  11464. value: undefined,
  11465. done: true
  11466. });
  11467. }
  11468. this._requests.length = 0;
  11469. if (this._manager.isPendingRequest(this._requestId)) {
  11470. this._manager.abortRequest(this._requestId);
  11471. }
  11472. this._close();
  11473. }
  11474. }
  11475. /***/ }),
  11476. /* 26 */
  11477. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11478. Object.defineProperty(exports, "__esModule", ({
  11479. value: true
  11480. }));
  11481. exports.PDFFetchStream = void 0;
  11482. var _util = __w_pdfjs_require__(2);
  11483. var _network_utils = __w_pdfjs_require__(23);
  11484. ;
  11485. function createFetchOptions(headers, withCredentials, abortController) {
  11486. return {
  11487. method: "GET",
  11488. headers,
  11489. signal: abortController?.signal,
  11490. mode: "cors",
  11491. credentials: withCredentials ? "include" : "same-origin",
  11492. redirect: "follow"
  11493. };
  11494. }
  11495. function createHeaders(httpHeaders) {
  11496. const headers = new Headers();
  11497. for (const property in httpHeaders) {
  11498. const value = httpHeaders[property];
  11499. if (typeof value === "undefined") {
  11500. continue;
  11501. }
  11502. headers.append(property, value);
  11503. }
  11504. return headers;
  11505. }
  11506. class PDFFetchStream {
  11507. constructor(source) {
  11508. this.source = source;
  11509. this.isHttp = /^https?:/i.test(source.url);
  11510. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  11511. this._fullRequestReader = null;
  11512. this._rangeRequestReaders = [];
  11513. }
  11514. get _progressiveDataLength() {
  11515. return this._fullRequestReader?._loaded ?? 0;
  11516. }
  11517. getFullReader() {
  11518. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  11519. this._fullRequestReader = new PDFFetchStreamReader(this);
  11520. return this._fullRequestReader;
  11521. }
  11522. getRangeReader(begin, end) {
  11523. if (end <= this._progressiveDataLength) {
  11524. return null;
  11525. }
  11526. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  11527. this._rangeRequestReaders.push(reader);
  11528. return reader;
  11529. }
  11530. cancelAllRequests(reason) {
  11531. if (this._fullRequestReader) {
  11532. this._fullRequestReader.cancel(reason);
  11533. }
  11534. for (const reader of this._rangeRequestReaders.slice(0)) {
  11535. reader.cancel(reason);
  11536. }
  11537. }
  11538. }
  11539. exports.PDFFetchStream = PDFFetchStream;
  11540. class PDFFetchStreamReader {
  11541. constructor(stream) {
  11542. this._stream = stream;
  11543. this._reader = null;
  11544. this._loaded = 0;
  11545. this._filename = null;
  11546. const source = stream.source;
  11547. this._withCredentials = source.withCredentials || false;
  11548. this._contentLength = source.length;
  11549. this._headersCapability = (0, _util.createPromiseCapability)();
  11550. this._disableRange = source.disableRange || false;
  11551. this._rangeChunkSize = source.rangeChunkSize;
  11552. if (!this._rangeChunkSize && !this._disableRange) {
  11553. this._disableRange = true;
  11554. }
  11555. if (typeof AbortController !== "undefined") {
  11556. this._abortController = new AbortController();
  11557. }
  11558. this._isStreamingSupported = !source.disableStream;
  11559. this._isRangeSupported = !source.disableRange;
  11560. this._headers = createHeaders(this._stream.httpHeaders);
  11561. const url = source.url;
  11562. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  11563. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  11564. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  11565. }
  11566. this._reader = response.body.getReader();
  11567. this._headersCapability.resolve();
  11568. const getResponseHeader = name => {
  11569. return response.headers.get(name);
  11570. };
  11571. const {
  11572. allowRangeRequests,
  11573. suggestedLength
  11574. } = (0, _network_utils.validateRangeRequestCapabilities)({
  11575. getResponseHeader,
  11576. isHttp: this._stream.isHttp,
  11577. rangeChunkSize: this._rangeChunkSize,
  11578. disableRange: this._disableRange
  11579. });
  11580. this._isRangeSupported = allowRangeRequests;
  11581. this._contentLength = suggestedLength || this._contentLength;
  11582. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  11583. if (!this._isStreamingSupported && this._isRangeSupported) {
  11584. this.cancel(new _util.AbortException("Streaming is disabled."));
  11585. }
  11586. }).catch(this._headersCapability.reject);
  11587. this.onProgress = null;
  11588. }
  11589. get headersReady() {
  11590. return this._headersCapability.promise;
  11591. }
  11592. get filename() {
  11593. return this._filename;
  11594. }
  11595. get contentLength() {
  11596. return this._contentLength;
  11597. }
  11598. get isRangeSupported() {
  11599. return this._isRangeSupported;
  11600. }
  11601. get isStreamingSupported() {
  11602. return this._isStreamingSupported;
  11603. }
  11604. async read() {
  11605. await this._headersCapability.promise;
  11606. const {
  11607. value,
  11608. done
  11609. } = await this._reader.read();
  11610. if (done) {
  11611. return {
  11612. value,
  11613. done
  11614. };
  11615. }
  11616. this._loaded += value.byteLength;
  11617. if (this.onProgress) {
  11618. this.onProgress({
  11619. loaded: this._loaded,
  11620. total: this._contentLength
  11621. });
  11622. }
  11623. const buffer = new Uint8Array(value).buffer;
  11624. return {
  11625. value: buffer,
  11626. done: false
  11627. };
  11628. }
  11629. cancel(reason) {
  11630. if (this._reader) {
  11631. this._reader.cancel(reason);
  11632. }
  11633. if (this._abortController) {
  11634. this._abortController.abort();
  11635. }
  11636. }
  11637. }
  11638. class PDFFetchStreamRangeReader {
  11639. constructor(stream, begin, end) {
  11640. this._stream = stream;
  11641. this._reader = null;
  11642. this._loaded = 0;
  11643. const source = stream.source;
  11644. this._withCredentials = source.withCredentials || false;
  11645. this._readCapability = (0, _util.createPromiseCapability)();
  11646. this._isStreamingSupported = !source.disableStream;
  11647. if (typeof AbortController !== "undefined") {
  11648. this._abortController = new AbortController();
  11649. }
  11650. this._headers = createHeaders(this._stream.httpHeaders);
  11651. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  11652. const url = source.url;
  11653. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  11654. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  11655. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  11656. }
  11657. this._readCapability.resolve();
  11658. this._reader = response.body.getReader();
  11659. }).catch(reason => {
  11660. if (reason?.name === "AbortError") {
  11661. return;
  11662. }
  11663. throw reason;
  11664. });
  11665. this.onProgress = null;
  11666. }
  11667. get isStreamingSupported() {
  11668. return this._isStreamingSupported;
  11669. }
  11670. async read() {
  11671. await this._readCapability.promise;
  11672. const {
  11673. value,
  11674. done
  11675. } = await this._reader.read();
  11676. if (done) {
  11677. return {
  11678. value,
  11679. done
  11680. };
  11681. }
  11682. this._loaded += value.byteLength;
  11683. if (this.onProgress) {
  11684. this.onProgress({
  11685. loaded: this._loaded
  11686. });
  11687. }
  11688. const buffer = new Uint8Array(value).buffer;
  11689. return {
  11690. value: buffer,
  11691. done: false
  11692. };
  11693. }
  11694. cancel(reason) {
  11695. if (this._reader) {
  11696. this._reader.cancel(reason);
  11697. }
  11698. if (this._abortController) {
  11699. this._abortController.abort();
  11700. }
  11701. }
  11702. }
  11703. /***/ })
  11704. /******/ ]);
  11705. /************************************************************************/
  11706. /******/ // The module cache
  11707. /******/ var __webpack_module_cache__ = {};
  11708. /******/
  11709. /******/ // The require function
  11710. /******/ function __w_pdfjs_require__(moduleId) {
  11711. /******/ // Check if module is in cache
  11712. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  11713. /******/ if (cachedModule !== undefined) {
  11714. /******/ return cachedModule.exports;
  11715. /******/ }
  11716. /******/ // Create a new module (and put it into the cache)
  11717. /******/ var module = __webpack_module_cache__[moduleId] = {
  11718. /******/ // no module.id needed
  11719. /******/ // no module.loaded needed
  11720. /******/ exports: {}
  11721. /******/ };
  11722. /******/
  11723. /******/ // Execute the module function
  11724. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  11725. /******/
  11726. /******/ // Return the exports of the module
  11727. /******/ return module.exports;
  11728. /******/ }
  11729. /******/
  11730. /************************************************************************/
  11731. var __webpack_exports__ = {};
  11732. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  11733. (() => {
  11734. var exports = __webpack_exports__;
  11735. Object.defineProperty(exports, "__esModule", ({
  11736. value: true
  11737. }));
  11738. Object.defineProperty(exports, "addLinkAttributes", ({
  11739. enumerable: true,
  11740. get: function () {
  11741. return _display_utils.addLinkAttributes;
  11742. }
  11743. }));
  11744. Object.defineProperty(exports, "getFilenameFromUrl", ({
  11745. enumerable: true,
  11746. get: function () {
  11747. return _display_utils.getFilenameFromUrl;
  11748. }
  11749. }));
  11750. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  11751. enumerable: true,
  11752. get: function () {
  11753. return _display_utils.getPdfFilenameFromUrl;
  11754. }
  11755. }));
  11756. Object.defineProperty(exports, "getXfaPageViewport", ({
  11757. enumerable: true,
  11758. get: function () {
  11759. return _display_utils.getXfaPageViewport;
  11760. }
  11761. }));
  11762. Object.defineProperty(exports, "isPdfFile", ({
  11763. enumerable: true,
  11764. get: function () {
  11765. return _display_utils.isPdfFile;
  11766. }
  11767. }));
  11768. Object.defineProperty(exports, "LinkTarget", ({
  11769. enumerable: true,
  11770. get: function () {
  11771. return _display_utils.LinkTarget;
  11772. }
  11773. }));
  11774. Object.defineProperty(exports, "loadScript", ({
  11775. enumerable: true,
  11776. get: function () {
  11777. return _display_utils.loadScript;
  11778. }
  11779. }));
  11780. Object.defineProperty(exports, "PDFDateString", ({
  11781. enumerable: true,
  11782. get: function () {
  11783. return _display_utils.PDFDateString;
  11784. }
  11785. }));
  11786. Object.defineProperty(exports, "RenderingCancelledException", ({
  11787. enumerable: true,
  11788. get: function () {
  11789. return _display_utils.RenderingCancelledException;
  11790. }
  11791. }));
  11792. Object.defineProperty(exports, "build", ({
  11793. enumerable: true,
  11794. get: function () {
  11795. return _api.build;
  11796. }
  11797. }));
  11798. Object.defineProperty(exports, "getDocument", ({
  11799. enumerable: true,
  11800. get: function () {
  11801. return _api.getDocument;
  11802. }
  11803. }));
  11804. Object.defineProperty(exports, "LoopbackPort", ({
  11805. enumerable: true,
  11806. get: function () {
  11807. return _api.LoopbackPort;
  11808. }
  11809. }));
  11810. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  11811. enumerable: true,
  11812. get: function () {
  11813. return _api.PDFDataRangeTransport;
  11814. }
  11815. }));
  11816. Object.defineProperty(exports, "PDFWorker", ({
  11817. enumerable: true,
  11818. get: function () {
  11819. return _api.PDFWorker;
  11820. }
  11821. }));
  11822. Object.defineProperty(exports, "version", ({
  11823. enumerable: true,
  11824. get: function () {
  11825. return _api.version;
  11826. }
  11827. }));
  11828. Object.defineProperty(exports, "CMapCompressionType", ({
  11829. enumerable: true,
  11830. get: function () {
  11831. return _util.CMapCompressionType;
  11832. }
  11833. }));
  11834. Object.defineProperty(exports, "createObjectURL", ({
  11835. enumerable: true,
  11836. get: function () {
  11837. return _util.createObjectURL;
  11838. }
  11839. }));
  11840. Object.defineProperty(exports, "createPromiseCapability", ({
  11841. enumerable: true,
  11842. get: function () {
  11843. return _util.createPromiseCapability;
  11844. }
  11845. }));
  11846. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  11847. enumerable: true,
  11848. get: function () {
  11849. return _util.createValidAbsoluteUrl;
  11850. }
  11851. }));
  11852. Object.defineProperty(exports, "InvalidPDFException", ({
  11853. enumerable: true,
  11854. get: function () {
  11855. return _util.InvalidPDFException;
  11856. }
  11857. }));
  11858. Object.defineProperty(exports, "MissingPDFException", ({
  11859. enumerable: true,
  11860. get: function () {
  11861. return _util.MissingPDFException;
  11862. }
  11863. }));
  11864. Object.defineProperty(exports, "OPS", ({
  11865. enumerable: true,
  11866. get: function () {
  11867. return _util.OPS;
  11868. }
  11869. }));
  11870. Object.defineProperty(exports, "PasswordResponses", ({
  11871. enumerable: true,
  11872. get: function () {
  11873. return _util.PasswordResponses;
  11874. }
  11875. }));
  11876. Object.defineProperty(exports, "PermissionFlag", ({
  11877. enumerable: true,
  11878. get: function () {
  11879. return _util.PermissionFlag;
  11880. }
  11881. }));
  11882. Object.defineProperty(exports, "removeNullCharacters", ({
  11883. enumerable: true,
  11884. get: function () {
  11885. return _util.removeNullCharacters;
  11886. }
  11887. }));
  11888. Object.defineProperty(exports, "shadow", ({
  11889. enumerable: true,
  11890. get: function () {
  11891. return _util.shadow;
  11892. }
  11893. }));
  11894. Object.defineProperty(exports, "UnexpectedResponseException", ({
  11895. enumerable: true,
  11896. get: function () {
  11897. return _util.UnexpectedResponseException;
  11898. }
  11899. }));
  11900. Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  11901. enumerable: true,
  11902. get: function () {
  11903. return _util.UNSUPPORTED_FEATURES;
  11904. }
  11905. }));
  11906. Object.defineProperty(exports, "Util", ({
  11907. enumerable: true,
  11908. get: function () {
  11909. return _util.Util;
  11910. }
  11911. }));
  11912. Object.defineProperty(exports, "VerbosityLevel", ({
  11913. enumerable: true,
  11914. get: function () {
  11915. return _util.VerbosityLevel;
  11916. }
  11917. }));
  11918. Object.defineProperty(exports, "AnnotationLayer", ({
  11919. enumerable: true,
  11920. get: function () {
  11921. return _annotation_layer.AnnotationLayer;
  11922. }
  11923. }));
  11924. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  11925. enumerable: true,
  11926. get: function () {
  11927. return _worker_options.GlobalWorkerOptions;
  11928. }
  11929. }));
  11930. Object.defineProperty(exports, "renderTextLayer", ({
  11931. enumerable: true,
  11932. get: function () {
  11933. return _text_layer.renderTextLayer;
  11934. }
  11935. }));
  11936. Object.defineProperty(exports, "SVGGraphics", ({
  11937. enumerable: true,
  11938. get: function () {
  11939. return _svg.SVGGraphics;
  11940. }
  11941. }));
  11942. Object.defineProperty(exports, "XfaLayer", ({
  11943. enumerable: true,
  11944. get: function () {
  11945. return _xfa_layer.XfaLayer;
  11946. }
  11947. }));
  11948. var _display_utils = __w_pdfjs_require__(1);
  11949. var _api = __w_pdfjs_require__(6);
  11950. var _util = __w_pdfjs_require__(2);
  11951. var _annotation_layer = __w_pdfjs_require__(17);
  11952. var _worker_options = __w_pdfjs_require__(12);
  11953. var _is_node = __w_pdfjs_require__(4);
  11954. var _text_layer = __w_pdfjs_require__(19);
  11955. var _svg = __w_pdfjs_require__(20);
  11956. var _xfa_layer = __w_pdfjs_require__(21);
  11957. const pdfjsVersion = '2.10.377';
  11958. const pdfjsBuild = '156762c48';
  11959. {
  11960. if (_is_node.isNodeJS) {
  11961. const {
  11962. PDFNodeStream
  11963. } = __w_pdfjs_require__(22);
  11964. (0, _api.setPDFNetworkStreamFactory)(params => {
  11965. return new PDFNodeStream(params);
  11966. });
  11967. } else {
  11968. const {
  11969. PDFNetworkStream
  11970. } = __w_pdfjs_require__(25);
  11971. const {
  11972. PDFFetchStream
  11973. } = __w_pdfjs_require__(26);
  11974. (0, _api.setPDFNetworkStreamFactory)(params => {
  11975. if ((0, _display_utils.isValidFetchUrl)(params.url)) {
  11976. return new PDFFetchStream(params);
  11977. }
  11978. return new PDFNetworkStream(params);
  11979. });
  11980. }
  11981. }
  11982. })();
  11983. /******/ return __webpack_exports__;
  11984. /******/ })()
  11985. ;
  11986. });
  11987. //# sourceMappingURL=pdf.js.map