pdf.js 381 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647
  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.isDataScheme = isDataScheme;
  46. exports.isFetchSupported = isFetchSupported;
  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.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.BaseCMapReaderFactory = exports.BaseCanvasFactory = void 0;
  51. var _util = __w_pdfjs_require__(2);
  52. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  53. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  54. const SVG_NS = "http://www.w3.org/2000/svg";
  55. class BaseCanvasFactory {
  56. constructor() {
  57. if (this.constructor === BaseCanvasFactory) {
  58. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  59. }
  60. }
  61. create(width, height) {
  62. (0, _util.unreachable)("Abstract method `create` called.");
  63. }
  64. reset(canvasAndContext, width, height) {
  65. if (!canvasAndContext.canvas) {
  66. throw new Error("Canvas is not specified");
  67. }
  68. if (width <= 0 || height <= 0) {
  69. throw new Error("Invalid canvas size");
  70. }
  71. canvasAndContext.canvas.width = width;
  72. canvasAndContext.canvas.height = height;
  73. }
  74. destroy(canvasAndContext) {
  75. if (!canvasAndContext.canvas) {
  76. throw new Error("Canvas is not specified");
  77. }
  78. canvasAndContext.canvas.width = 0;
  79. canvasAndContext.canvas.height = 0;
  80. canvasAndContext.canvas = null;
  81. canvasAndContext.context = null;
  82. }
  83. }
  84. exports.BaseCanvasFactory = BaseCanvasFactory;
  85. class DOMCanvasFactory extends BaseCanvasFactory {
  86. constructor({
  87. ownerDocument = globalThis.document
  88. } = {}) {
  89. super();
  90. this._document = ownerDocument;
  91. }
  92. create(width, height) {
  93. if (width <= 0 || height <= 0) {
  94. throw new Error("Invalid canvas size");
  95. }
  96. const canvas = this._document.createElement("canvas");
  97. const context = canvas.getContext("2d");
  98. canvas.width = width;
  99. canvas.height = height;
  100. return {
  101. canvas,
  102. context
  103. };
  104. }
  105. }
  106. exports.DOMCanvasFactory = DOMCanvasFactory;
  107. class BaseCMapReaderFactory {
  108. constructor({
  109. baseUrl = null,
  110. isCompressed = false
  111. }) {
  112. if (this.constructor === BaseCMapReaderFactory) {
  113. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  114. }
  115. this.baseUrl = baseUrl;
  116. this.isCompressed = isCompressed;
  117. }
  118. async fetch({
  119. name
  120. }) {
  121. if (!this.baseUrl) {
  122. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  123. }
  124. if (!name) {
  125. throw new Error("CMap name must be specified.");
  126. }
  127. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  128. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  129. return this._fetchData(url, compressionType).catch(reason => {
  130. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  131. });
  132. }
  133. _fetchData(url, compressionType) {
  134. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  135. }
  136. }
  137. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  138. class DOMCMapReaderFactory extends BaseCMapReaderFactory {
  139. _fetchData(url, compressionType) {
  140. if (isFetchSupported() && isValidFetchUrl(url, document.baseURI)) {
  141. return fetch(url).then(async response => {
  142. if (!response.ok) {
  143. throw new Error(response.statusText);
  144. }
  145. let cMapData;
  146. if (this.isCompressed) {
  147. cMapData = new Uint8Array(await response.arrayBuffer());
  148. } else {
  149. cMapData = (0, _util.stringToBytes)(await response.text());
  150. }
  151. return {
  152. cMapData,
  153. compressionType
  154. };
  155. });
  156. }
  157. return new Promise((resolve, reject) => {
  158. const request = new XMLHttpRequest();
  159. request.open("GET", url, true);
  160. if (this.isCompressed) {
  161. request.responseType = "arraybuffer";
  162. }
  163. request.onreadystatechange = () => {
  164. if (request.readyState !== XMLHttpRequest.DONE) {
  165. return;
  166. }
  167. if (request.status === 200 || request.status === 0) {
  168. let cMapData;
  169. if (this.isCompressed && request.response) {
  170. cMapData = new Uint8Array(request.response);
  171. } else if (!this.isCompressed && request.responseText) {
  172. cMapData = (0, _util.stringToBytes)(request.responseText);
  173. }
  174. if (cMapData) {
  175. resolve({
  176. cMapData,
  177. compressionType
  178. });
  179. return;
  180. }
  181. }
  182. reject(new Error(request.statusText));
  183. };
  184. request.send(null);
  185. });
  186. }
  187. }
  188. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  189. class DOMSVGFactory {
  190. create(width, height) {
  191. (0, _util.assert)(width > 0 && height > 0, "Invalid SVG dimensions");
  192. const svg = document.createElementNS(SVG_NS, "svg:svg");
  193. svg.setAttribute("version", "1.1");
  194. svg.setAttribute("width", width + "px");
  195. svg.setAttribute("height", height + "px");
  196. svg.setAttribute("preserveAspectRatio", "none");
  197. svg.setAttribute("viewBox", "0 0 " + width + " " + height);
  198. return svg;
  199. }
  200. createElement(type) {
  201. (0, _util.assert)(typeof type === "string", "Invalid SVG element type");
  202. return document.createElementNS(SVG_NS, type);
  203. }
  204. }
  205. exports.DOMSVGFactory = DOMSVGFactory;
  206. class PageViewport {
  207. constructor({
  208. viewBox,
  209. scale,
  210. rotation,
  211. offsetX = 0,
  212. offsetY = 0,
  213. dontFlip = false
  214. }) {
  215. this.viewBox = viewBox;
  216. this.scale = scale;
  217. this.rotation = rotation;
  218. this.offsetX = offsetX;
  219. this.offsetY = offsetY;
  220. const centerX = (viewBox[2] + viewBox[0]) / 2;
  221. const centerY = (viewBox[3] + viewBox[1]) / 2;
  222. let rotateA, rotateB, rotateC, rotateD;
  223. rotation %= 360;
  224. if (rotation < 0) {
  225. rotation += 360;
  226. }
  227. switch (rotation) {
  228. case 180:
  229. rotateA = -1;
  230. rotateB = 0;
  231. rotateC = 0;
  232. rotateD = 1;
  233. break;
  234. case 90:
  235. rotateA = 0;
  236. rotateB = 1;
  237. rotateC = 1;
  238. rotateD = 0;
  239. break;
  240. case 270:
  241. rotateA = 0;
  242. rotateB = -1;
  243. rotateC = -1;
  244. rotateD = 0;
  245. break;
  246. case 0:
  247. rotateA = 1;
  248. rotateB = 0;
  249. rotateC = 0;
  250. rotateD = -1;
  251. break;
  252. default:
  253. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  254. }
  255. if (dontFlip) {
  256. rotateC = -rotateC;
  257. rotateD = -rotateD;
  258. }
  259. let offsetCanvasX, offsetCanvasY;
  260. let width, height;
  261. if (rotateA === 0) {
  262. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  263. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  264. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  265. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  266. } else {
  267. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  268. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  269. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  270. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  271. }
  272. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  273. this.width = width;
  274. this.height = height;
  275. }
  276. clone({
  277. scale = this.scale,
  278. rotation = this.rotation,
  279. offsetX = this.offsetX,
  280. offsetY = this.offsetY,
  281. dontFlip = false
  282. } = {}) {
  283. return new PageViewport({
  284. viewBox: this.viewBox.slice(),
  285. scale,
  286. rotation,
  287. offsetX,
  288. offsetY,
  289. dontFlip
  290. });
  291. }
  292. convertToViewportPoint(x, y) {
  293. return _util.Util.applyTransform([x, y], this.transform);
  294. }
  295. convertToViewportRectangle(rect) {
  296. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  297. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  298. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  299. }
  300. convertToPdfPoint(x, y) {
  301. return _util.Util.applyInverseTransform([x, y], this.transform);
  302. }
  303. }
  304. exports.PageViewport = PageViewport;
  305. class RenderingCancelledException extends _util.BaseException {
  306. constructor(msg, type) {
  307. super(msg);
  308. this.type = type;
  309. }
  310. }
  311. exports.RenderingCancelledException = RenderingCancelledException;
  312. const LinkTarget = {
  313. NONE: 0,
  314. SELF: 1,
  315. BLANK: 2,
  316. PARENT: 3,
  317. TOP: 4
  318. };
  319. exports.LinkTarget = LinkTarget;
  320. function addLinkAttributes(link, {
  321. url,
  322. target,
  323. rel,
  324. enabled = true
  325. } = {}) {
  326. (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
  327. const urlNullRemoved = (0, _util.removeNullCharacters)(url);
  328. if (enabled) {
  329. link.href = link.title = urlNullRemoved;
  330. } else {
  331. link.href = "";
  332. link.title = `Disabled: ${urlNullRemoved}`;
  333. link.onclick = () => {
  334. return false;
  335. };
  336. }
  337. let targetStr = "";
  338. switch (target) {
  339. case LinkTarget.NONE:
  340. break;
  341. case LinkTarget.SELF:
  342. targetStr = "_self";
  343. break;
  344. case LinkTarget.BLANK:
  345. targetStr = "_blank";
  346. break;
  347. case LinkTarget.PARENT:
  348. targetStr = "_parent";
  349. break;
  350. case LinkTarget.TOP:
  351. targetStr = "_top";
  352. break;
  353. }
  354. link.target = targetStr;
  355. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  356. }
  357. function isDataScheme(url) {
  358. const ii = url.length;
  359. let i = 0;
  360. while (i < ii && url[i].trim() === "") {
  361. i++;
  362. }
  363. return url.substring(i, i + 5).toLowerCase() === "data:";
  364. }
  365. function isPdfFile(filename) {
  366. return typeof filename === "string" && /\.pdf$/i.test(filename);
  367. }
  368. function getFilenameFromUrl(url) {
  369. const anchor = url.indexOf("#");
  370. const query = url.indexOf("?");
  371. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  372. return url.substring(url.lastIndexOf("/", end) + 1, end);
  373. }
  374. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  375. if (typeof url !== "string") {
  376. return defaultFilename;
  377. }
  378. if (isDataScheme(url)) {
  379. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  380. return defaultFilename;
  381. }
  382. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  383. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  384. const splitURI = reURI.exec(url);
  385. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  386. if (suggestedFilename) {
  387. suggestedFilename = suggestedFilename[0];
  388. if (suggestedFilename.includes("%")) {
  389. try {
  390. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  391. } catch (ex) {}
  392. }
  393. }
  394. return suggestedFilename || defaultFilename;
  395. }
  396. class StatTimer {
  397. constructor() {
  398. this.started = Object.create(null);
  399. this.times = [];
  400. }
  401. time(name) {
  402. if (name in this.started) {
  403. (0, _util.warn)(`Timer is already running for ${name}`);
  404. }
  405. this.started[name] = Date.now();
  406. }
  407. timeEnd(name) {
  408. if (!(name in this.started)) {
  409. (0, _util.warn)(`Timer has not been started for ${name}`);
  410. }
  411. this.times.push({
  412. name,
  413. start: this.started[name],
  414. end: Date.now()
  415. });
  416. delete this.started[name];
  417. }
  418. toString() {
  419. const outBuf = [];
  420. let longest = 0;
  421. for (const time of this.times) {
  422. const name = time.name;
  423. if (name.length > longest) {
  424. longest = name.length;
  425. }
  426. }
  427. for (const time of this.times) {
  428. const duration = time.end - time.start;
  429. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  430. }
  431. return outBuf.join("");
  432. }
  433. }
  434. exports.StatTimer = StatTimer;
  435. function isFetchSupported() {
  436. return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype && typeof ReadableStream !== "undefined";
  437. }
  438. function isValidFetchUrl(url, baseUrl) {
  439. try {
  440. const {
  441. protocol
  442. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  443. return protocol === "http:" || protocol === "https:";
  444. } catch (ex) {
  445. return false;
  446. }
  447. }
  448. function loadScript(src, removeScriptElement = false) {
  449. return new Promise((resolve, reject) => {
  450. const script = document.createElement("script");
  451. script.src = src;
  452. script.onload = function (evt) {
  453. if (removeScriptElement) {
  454. script.remove();
  455. }
  456. resolve(evt);
  457. };
  458. script.onerror = function () {
  459. reject(new Error(`Cannot load script at: ${script.src}`));
  460. };
  461. (document.head || document.documentElement).appendChild(script);
  462. });
  463. }
  464. function deprecated(details) {
  465. console.log("Deprecated API usage: " + details);
  466. }
  467. let pdfDateStringRegex;
  468. class PDFDateString {
  469. static toDateObject(input) {
  470. if (!input || !(0, _util.isString)(input)) {
  471. return null;
  472. }
  473. if (!pdfDateStringRegex) {
  474. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  475. }
  476. const matches = pdfDateStringRegex.exec(input);
  477. if (!matches) {
  478. return null;
  479. }
  480. const year = parseInt(matches[1], 10);
  481. let month = parseInt(matches[2], 10);
  482. month = month >= 1 && month <= 12 ? month - 1 : 0;
  483. let day = parseInt(matches[3], 10);
  484. day = day >= 1 && day <= 31 ? day : 1;
  485. let hour = parseInt(matches[4], 10);
  486. hour = hour >= 0 && hour <= 23 ? hour : 0;
  487. let minute = parseInt(matches[5], 10);
  488. minute = minute >= 0 && minute <= 59 ? minute : 0;
  489. let second = parseInt(matches[6], 10);
  490. second = second >= 0 && second <= 59 ? second : 0;
  491. const universalTimeRelation = matches[7] || "Z";
  492. let offsetHour = parseInt(matches[8], 10);
  493. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  494. let offsetMinute = parseInt(matches[9], 10) || 0;
  495. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  496. if (universalTimeRelation === "-") {
  497. hour += offsetHour;
  498. minute += offsetMinute;
  499. } else if (universalTimeRelation === "+") {
  500. hour -= offsetHour;
  501. minute -= offsetMinute;
  502. }
  503. return new Date(Date.UTC(year, month, day, hour, minute, second));
  504. }
  505. }
  506. exports.PDFDateString = PDFDateString;
  507. /***/ }),
  508. /* 2 */
  509. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  510. Object.defineProperty(exports, "__esModule", ({
  511. value: true
  512. }));
  513. exports.arrayByteLength = arrayByteLength;
  514. exports.arraysToBytes = arraysToBytes;
  515. exports.assert = assert;
  516. exports.bytesToString = bytesToString;
  517. exports.createObjectURL = createObjectURL;
  518. exports.createPromiseCapability = createPromiseCapability;
  519. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  520. exports.escapeString = escapeString;
  521. exports.getModificationDate = getModificationDate;
  522. exports.getVerbosityLevel = getVerbosityLevel;
  523. exports.info = info;
  524. exports.isArrayBuffer = isArrayBuffer;
  525. exports.isArrayEqual = isArrayEqual;
  526. exports.isAscii = isAscii;
  527. exports.isBool = isBool;
  528. exports.isNum = isNum;
  529. exports.isSameOrigin = isSameOrigin;
  530. exports.isString = isString;
  531. exports.objectFromMap = objectFromMap;
  532. exports.objectSize = objectSize;
  533. exports.removeNullCharacters = removeNullCharacters;
  534. exports.setVerbosityLevel = setVerbosityLevel;
  535. exports.shadow = shadow;
  536. exports.string32 = string32;
  537. exports.stringToBytes = stringToBytes;
  538. exports.stringToPDFString = stringToPDFString;
  539. exports.stringToUTF16BEString = stringToUTF16BEString;
  540. exports.stringToUTF8String = stringToUTF8String;
  541. exports.unreachable = unreachable;
  542. exports.utf8StringToString = utf8StringToString;
  543. exports.warn = warn;
  544. 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;
  545. __w_pdfjs_require__(3);
  546. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  547. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  548. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  549. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  550. const PermissionFlag = {
  551. PRINT: 0x04,
  552. MODIFY_CONTENTS: 0x08,
  553. COPY: 0x10,
  554. MODIFY_ANNOTATIONS: 0x20,
  555. FILL_INTERACTIVE_FORMS: 0x100,
  556. COPY_FOR_ACCESSIBILITY: 0x200,
  557. ASSEMBLE: 0x400,
  558. PRINT_HIGH_QUALITY: 0x800
  559. };
  560. exports.PermissionFlag = PermissionFlag;
  561. const TextRenderingMode = {
  562. FILL: 0,
  563. STROKE: 1,
  564. FILL_STROKE: 2,
  565. INVISIBLE: 3,
  566. FILL_ADD_TO_PATH: 4,
  567. STROKE_ADD_TO_PATH: 5,
  568. FILL_STROKE_ADD_TO_PATH: 6,
  569. ADD_TO_PATH: 7,
  570. FILL_STROKE_MASK: 3,
  571. ADD_TO_PATH_FLAG: 4
  572. };
  573. exports.TextRenderingMode = TextRenderingMode;
  574. const ImageKind = {
  575. GRAYSCALE_1BPP: 1,
  576. RGB_24BPP: 2,
  577. RGBA_32BPP: 3
  578. };
  579. exports.ImageKind = ImageKind;
  580. const AnnotationType = {
  581. TEXT: 1,
  582. LINK: 2,
  583. FREETEXT: 3,
  584. LINE: 4,
  585. SQUARE: 5,
  586. CIRCLE: 6,
  587. POLYGON: 7,
  588. POLYLINE: 8,
  589. HIGHLIGHT: 9,
  590. UNDERLINE: 10,
  591. SQUIGGLY: 11,
  592. STRIKEOUT: 12,
  593. STAMP: 13,
  594. CARET: 14,
  595. INK: 15,
  596. POPUP: 16,
  597. FILEATTACHMENT: 17,
  598. SOUND: 18,
  599. MOVIE: 19,
  600. WIDGET: 20,
  601. SCREEN: 21,
  602. PRINTERMARK: 22,
  603. TRAPNET: 23,
  604. WATERMARK: 24,
  605. THREED: 25,
  606. REDACT: 26
  607. };
  608. exports.AnnotationType = AnnotationType;
  609. const AnnotationStateModelType = {
  610. MARKED: "Marked",
  611. REVIEW: "Review"
  612. };
  613. exports.AnnotationStateModelType = AnnotationStateModelType;
  614. const AnnotationMarkedState = {
  615. MARKED: "Marked",
  616. UNMARKED: "Unmarked"
  617. };
  618. exports.AnnotationMarkedState = AnnotationMarkedState;
  619. const AnnotationReviewState = {
  620. ACCEPTED: "Accepted",
  621. REJECTED: "Rejected",
  622. CANCELLED: "Cancelled",
  623. COMPLETED: "Completed",
  624. NONE: "None"
  625. };
  626. exports.AnnotationReviewState = AnnotationReviewState;
  627. const AnnotationReplyType = {
  628. GROUP: "Group",
  629. REPLY: "R"
  630. };
  631. exports.AnnotationReplyType = AnnotationReplyType;
  632. const AnnotationFlag = {
  633. INVISIBLE: 0x01,
  634. HIDDEN: 0x02,
  635. PRINT: 0x04,
  636. NOZOOM: 0x08,
  637. NOROTATE: 0x10,
  638. NOVIEW: 0x20,
  639. READONLY: 0x40,
  640. LOCKED: 0x80,
  641. TOGGLENOVIEW: 0x100,
  642. LOCKEDCONTENTS: 0x200
  643. };
  644. exports.AnnotationFlag = AnnotationFlag;
  645. const AnnotationFieldFlag = {
  646. READONLY: 0x0000001,
  647. REQUIRED: 0x0000002,
  648. NOEXPORT: 0x0000004,
  649. MULTILINE: 0x0001000,
  650. PASSWORD: 0x0002000,
  651. NOTOGGLETOOFF: 0x0004000,
  652. RADIO: 0x0008000,
  653. PUSHBUTTON: 0x0010000,
  654. COMBO: 0x0020000,
  655. EDIT: 0x0040000,
  656. SORT: 0x0080000,
  657. FILESELECT: 0x0100000,
  658. MULTISELECT: 0x0200000,
  659. DONOTSPELLCHECK: 0x0400000,
  660. DONOTSCROLL: 0x0800000,
  661. COMB: 0x1000000,
  662. RICHTEXT: 0x2000000,
  663. RADIOSINUNISON: 0x2000000,
  664. COMMITONSELCHANGE: 0x4000000
  665. };
  666. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  667. const AnnotationBorderStyleType = {
  668. SOLID: 1,
  669. DASHED: 2,
  670. BEVELED: 3,
  671. INSET: 4,
  672. UNDERLINE: 5
  673. };
  674. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  675. const AnnotationActionEventType = {
  676. E: "Mouse Enter",
  677. X: "Mouse Exit",
  678. D: "Mouse Down",
  679. U: "Mouse Up",
  680. Fo: "Focus",
  681. Bl: "Blur",
  682. PO: "PageOpen",
  683. PC: "PageClose",
  684. PV: "PageVisible",
  685. PI: "PageInvisible",
  686. K: "Keystroke",
  687. F: "Format",
  688. V: "Validate",
  689. C: "Calculate"
  690. };
  691. exports.AnnotationActionEventType = AnnotationActionEventType;
  692. const DocumentActionEventType = {
  693. WC: "WillClose",
  694. WS: "WillSave",
  695. DS: "DidSave",
  696. WP: "WillPrint",
  697. DP: "DidPrint"
  698. };
  699. exports.DocumentActionEventType = DocumentActionEventType;
  700. const PageActionEventType = {
  701. O: "PageOpen",
  702. C: "PageClose"
  703. };
  704. exports.PageActionEventType = PageActionEventType;
  705. const StreamType = {
  706. UNKNOWN: "UNKNOWN",
  707. FLATE: "FLATE",
  708. LZW: "LZW",
  709. DCT: "DCT",
  710. JPX: "JPX",
  711. JBIG: "JBIG",
  712. A85: "A85",
  713. AHX: "AHX",
  714. CCF: "CCF",
  715. RLX: "RLX"
  716. };
  717. exports.StreamType = StreamType;
  718. const FontType = {
  719. UNKNOWN: "UNKNOWN",
  720. TYPE1: "TYPE1",
  721. TYPE1C: "TYPE1C",
  722. CIDFONTTYPE0: "CIDFONTTYPE0",
  723. CIDFONTTYPE0C: "CIDFONTTYPE0C",
  724. TRUETYPE: "TRUETYPE",
  725. CIDFONTTYPE2: "CIDFONTTYPE2",
  726. TYPE3: "TYPE3",
  727. OPENTYPE: "OPENTYPE",
  728. TYPE0: "TYPE0",
  729. MMTYPE1: "MMTYPE1"
  730. };
  731. exports.FontType = FontType;
  732. const VerbosityLevel = {
  733. ERRORS: 0,
  734. WARNINGS: 1,
  735. INFOS: 5
  736. };
  737. exports.VerbosityLevel = VerbosityLevel;
  738. const CMapCompressionType = {
  739. NONE: 0,
  740. BINARY: 1,
  741. STREAM: 2
  742. };
  743. exports.CMapCompressionType = CMapCompressionType;
  744. const OPS = {
  745. dependency: 1,
  746. setLineWidth: 2,
  747. setLineCap: 3,
  748. setLineJoin: 4,
  749. setMiterLimit: 5,
  750. setDash: 6,
  751. setRenderingIntent: 7,
  752. setFlatness: 8,
  753. setGState: 9,
  754. save: 10,
  755. restore: 11,
  756. transform: 12,
  757. moveTo: 13,
  758. lineTo: 14,
  759. curveTo: 15,
  760. curveTo2: 16,
  761. curveTo3: 17,
  762. closePath: 18,
  763. rectangle: 19,
  764. stroke: 20,
  765. closeStroke: 21,
  766. fill: 22,
  767. eoFill: 23,
  768. fillStroke: 24,
  769. eoFillStroke: 25,
  770. closeFillStroke: 26,
  771. closeEOFillStroke: 27,
  772. endPath: 28,
  773. clip: 29,
  774. eoClip: 30,
  775. beginText: 31,
  776. endText: 32,
  777. setCharSpacing: 33,
  778. setWordSpacing: 34,
  779. setHScale: 35,
  780. setLeading: 36,
  781. setFont: 37,
  782. setTextRenderingMode: 38,
  783. setTextRise: 39,
  784. moveText: 40,
  785. setLeadingMoveText: 41,
  786. setTextMatrix: 42,
  787. nextLine: 43,
  788. showText: 44,
  789. showSpacedText: 45,
  790. nextLineShowText: 46,
  791. nextLineSetSpacingShowText: 47,
  792. setCharWidth: 48,
  793. setCharWidthAndBounds: 49,
  794. setStrokeColorSpace: 50,
  795. setFillColorSpace: 51,
  796. setStrokeColor: 52,
  797. setStrokeColorN: 53,
  798. setFillColor: 54,
  799. setFillColorN: 55,
  800. setStrokeGray: 56,
  801. setFillGray: 57,
  802. setStrokeRGBColor: 58,
  803. setFillRGBColor: 59,
  804. setStrokeCMYKColor: 60,
  805. setFillCMYKColor: 61,
  806. shadingFill: 62,
  807. beginInlineImage: 63,
  808. beginImageData: 64,
  809. endInlineImage: 65,
  810. paintXObject: 66,
  811. markPoint: 67,
  812. markPointProps: 68,
  813. beginMarkedContent: 69,
  814. beginMarkedContentProps: 70,
  815. endMarkedContent: 71,
  816. beginCompat: 72,
  817. endCompat: 73,
  818. paintFormXObjectBegin: 74,
  819. paintFormXObjectEnd: 75,
  820. beginGroup: 76,
  821. endGroup: 77,
  822. beginAnnotations: 78,
  823. endAnnotations: 79,
  824. beginAnnotation: 80,
  825. endAnnotation: 81,
  826. paintJpegXObject: 82,
  827. paintImageMaskXObject: 83,
  828. paintImageMaskXObjectGroup: 84,
  829. paintImageXObject: 85,
  830. paintInlineImageXObject: 86,
  831. paintInlineImageXObjectGroup: 87,
  832. paintImageXObjectRepeat: 88,
  833. paintImageMaskXObjectRepeat: 89,
  834. paintSolidColorImageMask: 90,
  835. constructPath: 91
  836. };
  837. exports.OPS = OPS;
  838. const UNSUPPORTED_FEATURES = {
  839. unknown: "unknown",
  840. forms: "forms",
  841. javaScript: "javaScript",
  842. signatures: "signatures",
  843. smask: "smask",
  844. shadingPattern: "shadingPattern",
  845. font: "font",
  846. errorTilingPattern: "errorTilingPattern",
  847. errorExtGState: "errorExtGState",
  848. errorXObject: "errorXObject",
  849. errorFontLoadType3: "errorFontLoadType3",
  850. errorFontState: "errorFontState",
  851. errorFontMissing: "errorFontMissing",
  852. errorFontTranslate: "errorFontTranslate",
  853. errorColorSpace: "errorColorSpace",
  854. errorOperatorList: "errorOperatorList",
  855. errorFontToUnicode: "errorFontToUnicode",
  856. errorFontLoadNative: "errorFontLoadNative",
  857. errorFontBuildPath: "errorFontBuildPath",
  858. errorFontGetPath: "errorFontGetPath",
  859. errorMarkedContent: "errorMarkedContent"
  860. };
  861. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  862. const PasswordResponses = {
  863. NEED_PASSWORD: 1,
  864. INCORRECT_PASSWORD: 2
  865. };
  866. exports.PasswordResponses = PasswordResponses;
  867. let verbosity = VerbosityLevel.WARNINGS;
  868. function setVerbosityLevel(level) {
  869. if (Number.isInteger(level)) {
  870. verbosity = level;
  871. }
  872. }
  873. function getVerbosityLevel() {
  874. return verbosity;
  875. }
  876. function info(msg) {
  877. if (verbosity >= VerbosityLevel.INFOS) {
  878. console.log(`Info: ${msg}`);
  879. }
  880. }
  881. function warn(msg) {
  882. if (verbosity >= VerbosityLevel.WARNINGS) {
  883. console.log(`Warning: ${msg}`);
  884. }
  885. }
  886. function unreachable(msg) {
  887. throw new Error(msg);
  888. }
  889. function assert(cond, msg) {
  890. if (!cond) {
  891. unreachable(msg);
  892. }
  893. }
  894. function isSameOrigin(baseUrl, otherUrl) {
  895. let base;
  896. try {
  897. base = new URL(baseUrl);
  898. if (!base.origin || base.origin === "null") {
  899. return false;
  900. }
  901. } catch (e) {
  902. return false;
  903. }
  904. const other = new URL(otherUrl, base);
  905. return base.origin === other.origin;
  906. }
  907. function _isValidProtocol(url) {
  908. if (!url) {
  909. return false;
  910. }
  911. switch (url.protocol) {
  912. case "http:":
  913. case "https:":
  914. case "ftp:":
  915. case "mailto:":
  916. case "tel:":
  917. return true;
  918. default:
  919. return false;
  920. }
  921. }
  922. function createValidAbsoluteUrl(url, baseUrl) {
  923. if (!url) {
  924. return null;
  925. }
  926. try {
  927. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  928. if (_isValidProtocol(absoluteUrl)) {
  929. return absoluteUrl;
  930. }
  931. } catch (ex) {}
  932. return null;
  933. }
  934. function shadow(obj, prop, value) {
  935. Object.defineProperty(obj, prop, {
  936. value,
  937. enumerable: true,
  938. configurable: true,
  939. writable: false
  940. });
  941. return value;
  942. }
  943. const BaseException = function BaseExceptionClosure() {
  944. function BaseException(message) {
  945. if (this.constructor === BaseException) {
  946. unreachable("Cannot initialize BaseException.");
  947. }
  948. this.message = message;
  949. this.name = this.constructor.name;
  950. }
  951. BaseException.prototype = new Error();
  952. BaseException.constructor = BaseException;
  953. return BaseException;
  954. }();
  955. exports.BaseException = BaseException;
  956. class PasswordException extends BaseException {
  957. constructor(msg, code) {
  958. super(msg);
  959. this.code = code;
  960. }
  961. }
  962. exports.PasswordException = PasswordException;
  963. class UnknownErrorException extends BaseException {
  964. constructor(msg, details) {
  965. super(msg);
  966. this.details = details;
  967. }
  968. }
  969. exports.UnknownErrorException = UnknownErrorException;
  970. class InvalidPDFException extends BaseException {}
  971. exports.InvalidPDFException = InvalidPDFException;
  972. class MissingPDFException extends BaseException {}
  973. exports.MissingPDFException = MissingPDFException;
  974. class UnexpectedResponseException extends BaseException {
  975. constructor(msg, status) {
  976. super(msg);
  977. this.status = status;
  978. }
  979. }
  980. exports.UnexpectedResponseException = UnexpectedResponseException;
  981. class FormatError extends BaseException {}
  982. exports.FormatError = FormatError;
  983. class AbortException extends BaseException {}
  984. exports.AbortException = AbortException;
  985. const NullCharactersRegExp = /\x00/g;
  986. function removeNullCharacters(str) {
  987. if (typeof str !== "string") {
  988. warn("The argument for removeNullCharacters must be a string.");
  989. return str;
  990. }
  991. return str.replace(NullCharactersRegExp, "");
  992. }
  993. function bytesToString(bytes) {
  994. assert(bytes !== null && typeof bytes === "object" && bytes.length !== undefined, "Invalid argument for bytesToString");
  995. const length = bytes.length;
  996. const MAX_ARGUMENT_COUNT = 8192;
  997. if (length < MAX_ARGUMENT_COUNT) {
  998. return String.fromCharCode.apply(null, bytes);
  999. }
  1000. const strBuf = [];
  1001. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  1002. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  1003. const chunk = bytes.subarray(i, chunkEnd);
  1004. strBuf.push(String.fromCharCode.apply(null, chunk));
  1005. }
  1006. return strBuf.join("");
  1007. }
  1008. function stringToBytes(str) {
  1009. assert(typeof str === "string", "Invalid argument for stringToBytes");
  1010. const length = str.length;
  1011. const bytes = new Uint8Array(length);
  1012. for (let i = 0; i < length; ++i) {
  1013. bytes[i] = str.charCodeAt(i) & 0xff;
  1014. }
  1015. return bytes;
  1016. }
  1017. function arrayByteLength(arr) {
  1018. if (arr.length !== undefined) {
  1019. return arr.length;
  1020. }
  1021. assert(arr.byteLength !== undefined, "arrayByteLength - invalid argument.");
  1022. return arr.byteLength;
  1023. }
  1024. function arraysToBytes(arr) {
  1025. const length = arr.length;
  1026. if (length === 1 && arr[0] instanceof Uint8Array) {
  1027. return arr[0];
  1028. }
  1029. let resultLength = 0;
  1030. for (let i = 0; i < length; i++) {
  1031. resultLength += arrayByteLength(arr[i]);
  1032. }
  1033. let pos = 0;
  1034. const data = new Uint8Array(resultLength);
  1035. for (let i = 0; i < length; i++) {
  1036. let item = arr[i];
  1037. if (!(item instanceof Uint8Array)) {
  1038. if (typeof item === "string") {
  1039. item = stringToBytes(item);
  1040. } else {
  1041. item = new Uint8Array(item);
  1042. }
  1043. }
  1044. const itemLength = item.byteLength;
  1045. data.set(item, pos);
  1046. pos += itemLength;
  1047. }
  1048. return data;
  1049. }
  1050. function string32(value) {
  1051. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  1052. }
  1053. function objectSize(obj) {
  1054. return Object.keys(obj).length;
  1055. }
  1056. function objectFromMap(map) {
  1057. const obj = Object.create(null);
  1058. for (const [key, value] of map) {
  1059. obj[key] = value;
  1060. }
  1061. return obj;
  1062. }
  1063. function isLittleEndian() {
  1064. const buffer8 = new Uint8Array(4);
  1065. buffer8[0] = 1;
  1066. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  1067. return view32[0] === 1;
  1068. }
  1069. const IsLittleEndianCached = {
  1070. get value() {
  1071. return shadow(this, "value", isLittleEndian());
  1072. }
  1073. };
  1074. exports.IsLittleEndianCached = IsLittleEndianCached;
  1075. function isEvalSupported() {
  1076. try {
  1077. new Function("");
  1078. return true;
  1079. } catch (e) {
  1080. return false;
  1081. }
  1082. }
  1083. const IsEvalSupportedCached = {
  1084. get value() {
  1085. return shadow(this, "value", isEvalSupported());
  1086. }
  1087. };
  1088. exports.IsEvalSupportedCached = IsEvalSupportedCached;
  1089. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  1090. class Util {
  1091. static makeHexColor(r, g, b) {
  1092. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  1093. }
  1094. static transform(m1, m2) {
  1095. 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]];
  1096. }
  1097. static applyTransform(p, m) {
  1098. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  1099. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  1100. return [xt, yt];
  1101. }
  1102. static applyInverseTransform(p, m) {
  1103. const d = m[0] * m[3] - m[1] * m[2];
  1104. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  1105. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  1106. return [xt, yt];
  1107. }
  1108. static getAxialAlignedBoundingBox(r, m) {
  1109. const p1 = Util.applyTransform(r, m);
  1110. const p2 = Util.applyTransform(r.slice(2, 4), m);
  1111. const p3 = Util.applyTransform([r[0], r[3]], m);
  1112. const p4 = Util.applyTransform([r[2], r[1]], m);
  1113. 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])];
  1114. }
  1115. static inverseTransform(m) {
  1116. const d = m[0] * m[3] - m[1] * m[2];
  1117. 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];
  1118. }
  1119. static apply3dTransform(m, v) {
  1120. 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]];
  1121. }
  1122. static singularValueDecompose2dScale(m) {
  1123. const transpose = [m[0], m[2], m[1], m[3]];
  1124. const a = m[0] * transpose[0] + m[1] * transpose[2];
  1125. const b = m[0] * transpose[1] + m[1] * transpose[3];
  1126. const c = m[2] * transpose[0] + m[3] * transpose[2];
  1127. const d = m[2] * transpose[1] + m[3] * transpose[3];
  1128. const first = (a + d) / 2;
  1129. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  1130. const sx = first + second || 1;
  1131. const sy = first - second || 1;
  1132. return [Math.sqrt(sx), Math.sqrt(sy)];
  1133. }
  1134. static normalizeRect(rect) {
  1135. const r = rect.slice(0);
  1136. if (rect[0] > rect[2]) {
  1137. r[0] = rect[2];
  1138. r[2] = rect[0];
  1139. }
  1140. if (rect[1] > rect[3]) {
  1141. r[1] = rect[3];
  1142. r[3] = rect[1];
  1143. }
  1144. return r;
  1145. }
  1146. static intersect(rect1, rect2) {
  1147. function compare(a, b) {
  1148. return a - b;
  1149. }
  1150. const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
  1151. const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare);
  1152. const result = [];
  1153. rect1 = Util.normalizeRect(rect1);
  1154. rect2 = Util.normalizeRect(rect2);
  1155. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  1156. result[0] = orderedX[1];
  1157. result[2] = orderedX[2];
  1158. } else {
  1159. return null;
  1160. }
  1161. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  1162. result[1] = orderedY[1];
  1163. result[3] = orderedY[2];
  1164. } else {
  1165. return null;
  1166. }
  1167. return result;
  1168. }
  1169. }
  1170. exports.Util = Util;
  1171. 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];
  1172. function stringToPDFString(str) {
  1173. const length = str.length,
  1174. strBuf = [];
  1175. if (str[0] === "\xFE" && str[1] === "\xFF") {
  1176. for (let i = 2; i < length; i += 2) {
  1177. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1178. }
  1179. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  1180. for (let i = 2; i < length; i += 2) {
  1181. strBuf.push(String.fromCharCode(str.charCodeAt(i + 1) << 8 | str.charCodeAt(i)));
  1182. }
  1183. } else {
  1184. for (let i = 0; i < length; ++i) {
  1185. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  1186. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1187. }
  1188. }
  1189. return strBuf.join("");
  1190. }
  1191. function escapeString(str) {
  1192. return str.replace(/([()\\\n\r])/g, match => {
  1193. if (match === "\n") {
  1194. return "\\n";
  1195. } else if (match === "\r") {
  1196. return "\\r";
  1197. }
  1198. return `\\${match}`;
  1199. });
  1200. }
  1201. function isAscii(str) {
  1202. return /^[\x00-\x7F]*$/.test(str);
  1203. }
  1204. function stringToUTF16BEString(str) {
  1205. const buf = ["\xFE\xFF"];
  1206. for (let i = 0, ii = str.length; i < ii; i++) {
  1207. const char = str.charCodeAt(i);
  1208. buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
  1209. }
  1210. return buf.join("");
  1211. }
  1212. function stringToUTF8String(str) {
  1213. return decodeURIComponent(escape(str));
  1214. }
  1215. function utf8StringToString(str) {
  1216. return unescape(encodeURIComponent(str));
  1217. }
  1218. function isBool(v) {
  1219. return typeof v === "boolean";
  1220. }
  1221. function isNum(v) {
  1222. return typeof v === "number";
  1223. }
  1224. function isString(v) {
  1225. return typeof v === "string";
  1226. }
  1227. function isArrayBuffer(v) {
  1228. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  1229. }
  1230. function isArrayEqual(arr1, arr2) {
  1231. if (arr1.length !== arr2.length) {
  1232. return false;
  1233. }
  1234. for (let i = 0, ii = arr1.length; i < ii; i++) {
  1235. if (arr1[i] !== arr2[i]) {
  1236. return false;
  1237. }
  1238. }
  1239. return true;
  1240. }
  1241. function getModificationDate(date = new Date()) {
  1242. 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")];
  1243. return buffer.join("");
  1244. }
  1245. function createPromiseCapability() {
  1246. const capability = Object.create(null);
  1247. let isSettled = false;
  1248. Object.defineProperty(capability, "settled", {
  1249. get() {
  1250. return isSettled;
  1251. }
  1252. });
  1253. capability.promise = new Promise(function (resolve, reject) {
  1254. capability.resolve = function (data) {
  1255. isSettled = true;
  1256. resolve(data);
  1257. };
  1258. capability.reject = function (reason) {
  1259. isSettled = true;
  1260. reject(reason);
  1261. };
  1262. });
  1263. return capability;
  1264. }
  1265. function createObjectURL(data, contentType = "", forceDataSchema = false) {
  1266. if (URL.createObjectURL && !forceDataSchema) {
  1267. return URL.createObjectURL(new Blob([data], {
  1268. type: contentType
  1269. }));
  1270. }
  1271. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1272. let buffer = `data:${contentType};base64,`;
  1273. for (let i = 0, ii = data.length; i < ii; i += 3) {
  1274. const b1 = data[i] & 0xff;
  1275. const b2 = data[i + 1] & 0xff;
  1276. const b3 = data[i + 2] & 0xff;
  1277. const d1 = b1 >> 2,
  1278. d2 = (b1 & 3) << 4 | b2 >> 4;
  1279. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  1280. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  1281. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1282. }
  1283. return buffer;
  1284. }
  1285. /***/ }),
  1286. /* 3 */
  1287. /***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
  1288. var _is_node = __w_pdfjs_require__(4);
  1289. ;
  1290. /***/ }),
  1291. /* 4 */
  1292. /***/ ((__unused_webpack_module, exports) => {
  1293. Object.defineProperty(exports, "__esModule", ({
  1294. value: true
  1295. }));
  1296. exports.isNodeJS = void 0;
  1297. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  1298. exports.isNodeJS = isNodeJS;
  1299. /***/ }),
  1300. /* 5 */
  1301. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1302. Object.defineProperty(exports, "__esModule", ({
  1303. value: true
  1304. }));
  1305. exports.getDocument = getDocument;
  1306. exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
  1307. exports.version = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultCMapReaderFactory = exports.DefaultCanvasFactory = exports.build = void 0;
  1308. var _util = __w_pdfjs_require__(2);
  1309. var _display_utils = __w_pdfjs_require__(1);
  1310. var _font_loader = __w_pdfjs_require__(6);
  1311. var _node_utils = __w_pdfjs_require__(7);
  1312. var _annotation_storage = __w_pdfjs_require__(8);
  1313. var _api_compatibility = __w_pdfjs_require__(9);
  1314. var _canvas = __w_pdfjs_require__(10);
  1315. var _worker_options = __w_pdfjs_require__(12);
  1316. var _is_node = __w_pdfjs_require__(4);
  1317. var _message_handler = __w_pdfjs_require__(13);
  1318. var _metadata = __w_pdfjs_require__(14);
  1319. var _optional_content_config = __w_pdfjs_require__(15);
  1320. var _transport_stream = __w_pdfjs_require__(16);
  1321. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  1322. const RENDERING_CANCELLED_TIMEOUT = 100;
  1323. const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
  1324. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  1325. const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
  1326. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  1327. let createPDFNetworkStream;
  1328. function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
  1329. createPDFNetworkStream = pdfNetworkStreamFactory;
  1330. }
  1331. function getDocument(src) {
  1332. const task = new PDFDocumentLoadingTask();
  1333. let source;
  1334. if (typeof src === "string" || src instanceof URL) {
  1335. source = {
  1336. url: src
  1337. };
  1338. } else if ((0, _util.isArrayBuffer)(src)) {
  1339. source = {
  1340. data: src
  1341. };
  1342. } else if (src instanceof PDFDataRangeTransport) {
  1343. source = {
  1344. range: src
  1345. };
  1346. } else {
  1347. if (typeof src !== "object") {
  1348. throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
  1349. }
  1350. if (!src.url && !src.data && !src.range) {
  1351. throw new Error("Invalid parameter object: need either .data, .range or .url");
  1352. }
  1353. source = src;
  1354. }
  1355. const params = Object.create(null);
  1356. let rangeTransport = null,
  1357. worker = null;
  1358. for (const key in source) {
  1359. const value = source[key];
  1360. switch (key) {
  1361. case "url":
  1362. if (typeof window !== "undefined") {
  1363. try {
  1364. params[key] = new URL(value, window.location).href;
  1365. continue;
  1366. } catch (ex) {
  1367. (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
  1368. }
  1369. } else if (typeof value === "string" || value instanceof URL) {
  1370. params[key] = value.toString();
  1371. continue;
  1372. }
  1373. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1374. case "range":
  1375. rangeTransport = value;
  1376. continue;
  1377. case "worker":
  1378. worker = value;
  1379. continue;
  1380. case "data":
  1381. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
  1382. params[key] = new Uint8Array(value);
  1383. } else if (value instanceof Uint8Array) {
  1384. break;
  1385. } else if (typeof value === "string") {
  1386. params[key] = (0, _util.stringToBytes)(value);
  1387. } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
  1388. params[key] = new Uint8Array(value);
  1389. } else if ((0, _util.isArrayBuffer)(value)) {
  1390. params[key] = new Uint8Array(value);
  1391. } else {
  1392. throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
  1393. }
  1394. continue;
  1395. }
  1396. params[key] = value;
  1397. }
  1398. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  1399. params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
  1400. params.ignoreErrors = params.stopAtErrors !== true;
  1401. params.fontExtraProperties = params.fontExtraProperties === true;
  1402. params.pdfBug = params.pdfBug === true;
  1403. params.enableXfa = params.enableXfa === true;
  1404. if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
  1405. params.docBaseUrl = null;
  1406. }
  1407. if (!Number.isInteger(params.maxImageSize)) {
  1408. params.maxImageSize = -1;
  1409. }
  1410. if (typeof params.isEvalSupported !== "boolean") {
  1411. params.isEvalSupported = true;
  1412. }
  1413. if (typeof params.disableFontFace !== "boolean") {
  1414. params.disableFontFace = _api_compatibility.apiCompatibilityParams.disableFontFace || false;
  1415. }
  1416. if (typeof params.ownerDocument === "undefined") {
  1417. params.ownerDocument = globalThis.document;
  1418. }
  1419. if (typeof params.disableRange !== "boolean") {
  1420. params.disableRange = false;
  1421. }
  1422. if (typeof params.disableStream !== "boolean") {
  1423. params.disableStream = false;
  1424. }
  1425. if (typeof params.disableAutoFetch !== "boolean") {
  1426. params.disableAutoFetch = false;
  1427. }
  1428. (0, _util.setVerbosityLevel)(params.verbosity);
  1429. if (!worker) {
  1430. const workerParams = {
  1431. verbosity: params.verbosity,
  1432. port: _worker_options.GlobalWorkerOptions.workerPort
  1433. };
  1434. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  1435. task._worker = worker;
  1436. }
  1437. const docId = task.docId;
  1438. worker.promise.then(function () {
  1439. if (task.destroyed) {
  1440. throw new Error("Loading aborted");
  1441. }
  1442. const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
  1443. const networkStreamPromise = new Promise(function (resolve) {
  1444. let networkStream;
  1445. if (rangeTransport) {
  1446. networkStream = new _transport_stream.PDFDataTransportStream({
  1447. length: params.length,
  1448. initialData: params.initialData,
  1449. progressiveDone: params.progressiveDone,
  1450. contentDispositionFilename: params.contentDispositionFilename,
  1451. disableRange: params.disableRange,
  1452. disableStream: params.disableStream
  1453. }, rangeTransport);
  1454. } else if (!params.data) {
  1455. networkStream = createPDFNetworkStream({
  1456. url: params.url,
  1457. length: params.length,
  1458. httpHeaders: params.httpHeaders,
  1459. withCredentials: params.withCredentials,
  1460. rangeChunkSize: params.rangeChunkSize,
  1461. disableRange: params.disableRange,
  1462. disableStream: params.disableStream
  1463. });
  1464. }
  1465. resolve(networkStream);
  1466. });
  1467. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1468. if (task.destroyed) {
  1469. throw new Error("Loading aborted");
  1470. }
  1471. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1472. messageHandler.postMessageTransfers = worker.postMessageTransfers;
  1473. const transport = new WorkerTransport(messageHandler, task, networkStream, params);
  1474. task._transport = transport;
  1475. messageHandler.send("Ready", null);
  1476. });
  1477. }).catch(task._capability.reject);
  1478. return task;
  1479. }
  1480. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  1481. if (worker.destroyed) {
  1482. return Promise.reject(new Error("Worker was destroyed"));
  1483. }
  1484. if (pdfDataRangeTransport) {
  1485. source.length = pdfDataRangeTransport.length;
  1486. source.initialData = pdfDataRangeTransport.initialData;
  1487. source.progressiveDone = pdfDataRangeTransport.progressiveDone;
  1488. source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
  1489. }
  1490. return worker.messageHandler.sendWithPromise("GetDocRequest", {
  1491. docId,
  1492. apiVersion: '2.9.359',
  1493. source: {
  1494. data: source.data,
  1495. url: source.url,
  1496. password: source.password,
  1497. disableAutoFetch: source.disableAutoFetch,
  1498. rangeChunkSize: source.rangeChunkSize,
  1499. length: source.length
  1500. },
  1501. maxImageSize: source.maxImageSize,
  1502. disableFontFace: source.disableFontFace,
  1503. postMessageTransfers: worker.postMessageTransfers,
  1504. docBaseUrl: source.docBaseUrl,
  1505. ignoreErrors: source.ignoreErrors,
  1506. isEvalSupported: source.isEvalSupported,
  1507. fontExtraProperties: source.fontExtraProperties,
  1508. enableXfa: source.enableXfa
  1509. }).then(function (workerId) {
  1510. if (worker.destroyed) {
  1511. throw new Error("Worker was destroyed");
  1512. }
  1513. return workerId;
  1514. });
  1515. }
  1516. const PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  1517. let nextDocumentId = 0;
  1518. class PDFDocumentLoadingTask {
  1519. constructor() {
  1520. this._capability = (0, _util.createPromiseCapability)();
  1521. this._transport = null;
  1522. this._worker = null;
  1523. this.docId = "d" + nextDocumentId++;
  1524. this.destroyed = false;
  1525. this.onPassword = null;
  1526. this.onProgress = null;
  1527. this.onUnsupportedFeature = null;
  1528. }
  1529. get promise() {
  1530. return this._capability.promise;
  1531. }
  1532. destroy() {
  1533. this.destroyed = true;
  1534. const transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  1535. return transportDestroyed.then(() => {
  1536. this._transport = null;
  1537. if (this._worker) {
  1538. this._worker.destroy();
  1539. this._worker = null;
  1540. }
  1541. });
  1542. }
  1543. }
  1544. return PDFDocumentLoadingTask;
  1545. }();
  1546. class PDFDataRangeTransport {
  1547. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1548. this.length = length;
  1549. this.initialData = initialData;
  1550. this.progressiveDone = progressiveDone;
  1551. this.contentDispositionFilename = contentDispositionFilename;
  1552. this._rangeListeners = [];
  1553. this._progressListeners = [];
  1554. this._progressiveReadListeners = [];
  1555. this._progressiveDoneListeners = [];
  1556. this._readyCapability = (0, _util.createPromiseCapability)();
  1557. }
  1558. addRangeListener(listener) {
  1559. this._rangeListeners.push(listener);
  1560. }
  1561. addProgressListener(listener) {
  1562. this._progressListeners.push(listener);
  1563. }
  1564. addProgressiveReadListener(listener) {
  1565. this._progressiveReadListeners.push(listener);
  1566. }
  1567. addProgressiveDoneListener(listener) {
  1568. this._progressiveDoneListeners.push(listener);
  1569. }
  1570. onDataRange(begin, chunk) {
  1571. for (const listener of this._rangeListeners) {
  1572. listener(begin, chunk);
  1573. }
  1574. }
  1575. onDataProgress(loaded, total) {
  1576. this._readyCapability.promise.then(() => {
  1577. for (const listener of this._progressListeners) {
  1578. listener(loaded, total);
  1579. }
  1580. });
  1581. }
  1582. onDataProgressiveRead(chunk) {
  1583. this._readyCapability.promise.then(() => {
  1584. for (const listener of this._progressiveReadListeners) {
  1585. listener(chunk);
  1586. }
  1587. });
  1588. }
  1589. onDataProgressiveDone() {
  1590. this._readyCapability.promise.then(() => {
  1591. for (const listener of this._progressiveDoneListeners) {
  1592. listener();
  1593. }
  1594. });
  1595. }
  1596. transportReady() {
  1597. this._readyCapability.resolve();
  1598. }
  1599. requestDataRange(begin, end) {
  1600. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1601. }
  1602. abort() {}
  1603. }
  1604. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1605. class PDFDocumentProxy {
  1606. constructor(pdfInfo, transport) {
  1607. this._pdfInfo = pdfInfo;
  1608. this._transport = transport;
  1609. }
  1610. get annotationStorage() {
  1611. return this._transport.annotationStorage;
  1612. }
  1613. get numPages() {
  1614. return this._pdfInfo.numPages;
  1615. }
  1616. get fingerprint() {
  1617. return this._pdfInfo.fingerprint;
  1618. }
  1619. get isPureXfa() {
  1620. return this._pdfInfo.isPureXfa;
  1621. }
  1622. getPage(pageNumber) {
  1623. return this._transport.getPage(pageNumber);
  1624. }
  1625. getPageIndex(ref) {
  1626. return this._transport.getPageIndex(ref);
  1627. }
  1628. getDestinations() {
  1629. return this._transport.getDestinations();
  1630. }
  1631. getDestination(id) {
  1632. return this._transport.getDestination(id);
  1633. }
  1634. getPageLabels() {
  1635. return this._transport.getPageLabels();
  1636. }
  1637. getPageLayout() {
  1638. return this._transport.getPageLayout();
  1639. }
  1640. getPageMode() {
  1641. return this._transport.getPageMode();
  1642. }
  1643. getViewerPreferences() {
  1644. return this._transport.getViewerPreferences();
  1645. }
  1646. getOpenAction() {
  1647. return this._transport.getOpenAction();
  1648. }
  1649. getAttachments() {
  1650. return this._transport.getAttachments();
  1651. }
  1652. getJavaScript() {
  1653. return this._transport.getJavaScript();
  1654. }
  1655. getJSActions() {
  1656. return this._transport.getDocJSActions();
  1657. }
  1658. getOutline() {
  1659. return this._transport.getOutline();
  1660. }
  1661. getOptionalContentConfig() {
  1662. return this._transport.getOptionalContentConfig();
  1663. }
  1664. getPermissions() {
  1665. return this._transport.getPermissions();
  1666. }
  1667. getMetadata() {
  1668. return this._transport.getMetadata();
  1669. }
  1670. getMarkInfo() {
  1671. return this._transport.getMarkInfo();
  1672. }
  1673. getData() {
  1674. return this._transport.getData();
  1675. }
  1676. getDownloadInfo() {
  1677. return this._transport.downloadInfoCapability.promise;
  1678. }
  1679. getStats() {
  1680. return this._transport.getStats();
  1681. }
  1682. cleanup(keepLoadedFonts = false) {
  1683. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1684. }
  1685. destroy() {
  1686. return this.loadingTask.destroy();
  1687. }
  1688. get loadingParams() {
  1689. return this._transport.loadingParams;
  1690. }
  1691. get loadingTask() {
  1692. return this._transport.loadingTask;
  1693. }
  1694. saveDocument() {
  1695. if (arguments.length > 0) {
  1696. (0, _display_utils.deprecated)("saveDocument no longer accepts any options.");
  1697. }
  1698. if (this._transport.annotationStorage.size <= 0) {
  1699. (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  1700. }
  1701. return this._transport.saveDocument();
  1702. }
  1703. getFieldObjects() {
  1704. return this._transport.getFieldObjects();
  1705. }
  1706. hasJSActions() {
  1707. return this._transport.hasJSActions();
  1708. }
  1709. getCalculationOrderIds() {
  1710. return this._transport.getCalculationOrderIds();
  1711. }
  1712. }
  1713. exports.PDFDocumentProxy = PDFDocumentProxy;
  1714. class PDFPageProxy {
  1715. constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
  1716. this._pageIndex = pageIndex;
  1717. this._pageInfo = pageInfo;
  1718. this._ownerDocument = ownerDocument;
  1719. this._transport = transport;
  1720. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1721. this._pdfBug = pdfBug;
  1722. this.commonObjs = transport.commonObjs;
  1723. this.objs = new PDFObjects();
  1724. this.cleanupAfterRender = false;
  1725. this.pendingCleanup = false;
  1726. this._intentStates = new Map();
  1727. this.destroyed = false;
  1728. }
  1729. get pageNumber() {
  1730. return this._pageIndex + 1;
  1731. }
  1732. get rotate() {
  1733. return this._pageInfo.rotate;
  1734. }
  1735. get ref() {
  1736. return this._pageInfo.ref;
  1737. }
  1738. get userUnit() {
  1739. return this._pageInfo.userUnit;
  1740. }
  1741. get view() {
  1742. return this._pageInfo.view;
  1743. }
  1744. getViewport({
  1745. scale,
  1746. rotation = this.rotate,
  1747. offsetX = 0,
  1748. offsetY = 0,
  1749. dontFlip = false
  1750. } = {}) {
  1751. return new _display_utils.PageViewport({
  1752. viewBox: this.view,
  1753. scale,
  1754. rotation,
  1755. offsetX,
  1756. offsetY,
  1757. dontFlip
  1758. });
  1759. }
  1760. getAnnotations({
  1761. intent = null
  1762. } = {}) {
  1763. if (!this._annotationsPromise || this._annotationsIntent !== intent) {
  1764. this._annotationsPromise = this._transport.getAnnotations(this._pageIndex, intent);
  1765. this._annotationsIntent = intent;
  1766. }
  1767. return this._annotationsPromise;
  1768. }
  1769. getJSActions() {
  1770. return this._jsActionsPromise || (this._jsActionsPromise = this._transport.getPageJSActions(this._pageIndex));
  1771. }
  1772. getXfa() {
  1773. return this._xfaPromise || (this._xfaPromise = this._transport.getPageXfa(this._pageIndex));
  1774. }
  1775. render({
  1776. canvasContext,
  1777. viewport,
  1778. intent = "display",
  1779. renderInteractiveForms = false,
  1780. transform = null,
  1781. imageLayer = null,
  1782. canvasFactory = null,
  1783. background = null,
  1784. includeAnnotationStorage = false,
  1785. optionalContentConfigPromise = null
  1786. }) {
  1787. var _intentState;
  1788. if (arguments[0]?.annotationStorage !== undefined) {
  1789. (0, _display_utils.deprecated)("render no longer accepts an `annotationStorage` option, " + "please use the `includeAnnotationStorage`-boolean instead.");
  1790. includeAnnotationStorage || (includeAnnotationStorage = !!arguments[0].annotationStorage);
  1791. }
  1792. if (this._stats) {
  1793. this._stats.time("Overall");
  1794. }
  1795. const renderingIntent = intent === "print" ? "print" : "display";
  1796. this.pendingCleanup = false;
  1797. if (!optionalContentConfigPromise) {
  1798. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1799. }
  1800. let intentState = this._intentStates.get(renderingIntent);
  1801. if (!intentState) {
  1802. intentState = Object.create(null);
  1803. this._intentStates.set(renderingIntent, intentState);
  1804. }
  1805. if (intentState.streamReaderCancelTimeout) {
  1806. clearTimeout(intentState.streamReaderCancelTimeout);
  1807. intentState.streamReaderCancelTimeout = null;
  1808. }
  1809. const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
  1810. ownerDocument: this._ownerDocument
  1811. });
  1812. const annotationStorage = includeAnnotationStorage ? this._transport.annotationStorage.serializable : null;
  1813. if (!intentState.displayReadyCapability) {
  1814. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  1815. intentState.operatorList = {
  1816. fnArray: [],
  1817. argsArray: [],
  1818. lastChunk: false
  1819. };
  1820. if (this._stats) {
  1821. this._stats.time("Page Request");
  1822. }
  1823. this._pumpOperatorList({
  1824. pageIndex: this._pageIndex,
  1825. intent: renderingIntent,
  1826. renderInteractiveForms: renderInteractiveForms === true,
  1827. annotationStorage
  1828. });
  1829. }
  1830. const complete = error => {
  1831. intentState.renderTasks.delete(internalRenderTask);
  1832. if (this.cleanupAfterRender || renderingIntent === "print") {
  1833. this.pendingCleanup = true;
  1834. }
  1835. this._tryCleanup();
  1836. if (error) {
  1837. internalRenderTask.capability.reject(error);
  1838. this._abortOperatorList({
  1839. intentState,
  1840. reason: error
  1841. });
  1842. } else {
  1843. internalRenderTask.capability.resolve();
  1844. }
  1845. if (this._stats) {
  1846. this._stats.timeEnd("Rendering");
  1847. this._stats.timeEnd("Overall");
  1848. }
  1849. };
  1850. const internalRenderTask = new InternalRenderTask({
  1851. callback: complete,
  1852. params: {
  1853. canvasContext,
  1854. viewport,
  1855. transform,
  1856. imageLayer,
  1857. background
  1858. },
  1859. objs: this.objs,
  1860. commonObjs: this.commonObjs,
  1861. operatorList: intentState.operatorList,
  1862. pageIndex: this._pageIndex,
  1863. canvasFactory: canvasFactoryInstance,
  1864. useRequestAnimationFrame: renderingIntent !== "print",
  1865. pdfBug: this._pdfBug
  1866. });
  1867. ((_intentState = intentState).renderTasks || (_intentState.renderTasks = new Set())).add(internalRenderTask);
  1868. const renderTask = internalRenderTask.task;
  1869. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  1870. if (this.pendingCleanup) {
  1871. complete();
  1872. return;
  1873. }
  1874. if (this._stats) {
  1875. this._stats.time("Rendering");
  1876. }
  1877. internalRenderTask.initializeGraphics({
  1878. transparency,
  1879. optionalContentConfig
  1880. });
  1881. internalRenderTask.operatorListChanged();
  1882. }).catch(complete);
  1883. return renderTask;
  1884. }
  1885. getOperatorList() {
  1886. function operatorListChanged() {
  1887. if (intentState.operatorList.lastChunk) {
  1888. intentState.opListReadCapability.resolve(intentState.operatorList);
  1889. intentState.renderTasks.delete(opListTask);
  1890. }
  1891. }
  1892. const renderingIntent = "oplist";
  1893. let intentState = this._intentStates.get(renderingIntent);
  1894. if (!intentState) {
  1895. intentState = Object.create(null);
  1896. this._intentStates.set(renderingIntent, intentState);
  1897. }
  1898. let opListTask;
  1899. if (!intentState.opListReadCapability) {
  1900. var _intentState2;
  1901. opListTask = Object.create(null);
  1902. opListTask.operatorListChanged = operatorListChanged;
  1903. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  1904. ((_intentState2 = intentState).renderTasks || (_intentState2.renderTasks = new Set())).add(opListTask);
  1905. intentState.operatorList = {
  1906. fnArray: [],
  1907. argsArray: [],
  1908. lastChunk: false
  1909. };
  1910. if (this._stats) {
  1911. this._stats.time("Page Request");
  1912. }
  1913. this._pumpOperatorList({
  1914. pageIndex: this._pageIndex,
  1915. intent: renderingIntent
  1916. });
  1917. }
  1918. return intentState.opListReadCapability.promise;
  1919. }
  1920. streamTextContent({
  1921. normalizeWhitespace = false,
  1922. disableCombineTextItems = false,
  1923. includeMarkedContent = false
  1924. } = {}) {
  1925. const TEXT_CONTENT_CHUNK_SIZE = 100;
  1926. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  1927. pageIndex: this._pageIndex,
  1928. normalizeWhitespace: normalizeWhitespace === true,
  1929. combineTextItems: disableCombineTextItems !== true,
  1930. includeMarkedContent: includeMarkedContent === true
  1931. }, {
  1932. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  1933. size(textContent) {
  1934. return textContent.items.length;
  1935. }
  1936. });
  1937. }
  1938. getTextContent(params = {}) {
  1939. const readableStream = this.streamTextContent(params);
  1940. return new Promise(function (resolve, reject) {
  1941. function pump() {
  1942. reader.read().then(function ({
  1943. value,
  1944. done
  1945. }) {
  1946. if (done) {
  1947. resolve(textContent);
  1948. return;
  1949. }
  1950. Object.assign(textContent.styles, value.styles);
  1951. textContent.items.push(...value.items);
  1952. pump();
  1953. }, reject);
  1954. }
  1955. const reader = readableStream.getReader();
  1956. const textContent = {
  1957. items: [],
  1958. styles: Object.create(null)
  1959. };
  1960. pump();
  1961. });
  1962. }
  1963. getStructTree() {
  1964. return this._structTreePromise || (this._structTreePromise = this._transport.getStructTree(this._pageIndex));
  1965. }
  1966. _destroy() {
  1967. this.destroyed = true;
  1968. this._transport.pageCache[this._pageIndex] = null;
  1969. const waitOn = [];
  1970. for (const [intent, intentState] of this._intentStates) {
  1971. this._abortOperatorList({
  1972. intentState,
  1973. reason: new Error("Page was destroyed."),
  1974. force: true
  1975. });
  1976. if (intent === "oplist") {
  1977. continue;
  1978. }
  1979. for (const internalRenderTask of intentState.renderTasks) {
  1980. waitOn.push(internalRenderTask.completed);
  1981. internalRenderTask.cancel();
  1982. }
  1983. }
  1984. this.objs.clear();
  1985. this._annotationsPromise = null;
  1986. this._jsActionsPromise = null;
  1987. this._xfaPromise = null;
  1988. this._structTreePromise = null;
  1989. this.pendingCleanup = false;
  1990. return Promise.all(waitOn);
  1991. }
  1992. cleanup(resetStats = false) {
  1993. this.pendingCleanup = true;
  1994. return this._tryCleanup(resetStats);
  1995. }
  1996. _tryCleanup(resetStats = false) {
  1997. if (!this.pendingCleanup) {
  1998. return false;
  1999. }
  2000. for (const {
  2001. renderTasks,
  2002. operatorList
  2003. } of this._intentStates.values()) {
  2004. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  2005. return false;
  2006. }
  2007. }
  2008. this._intentStates.clear();
  2009. this.objs.clear();
  2010. this._annotationsPromise = null;
  2011. this._jsActionsPromise = null;
  2012. this._xfaPromise = null;
  2013. this._structTreePromise = null;
  2014. if (resetStats && this._stats) {
  2015. this._stats = new _display_utils.StatTimer();
  2016. }
  2017. this.pendingCleanup = false;
  2018. return true;
  2019. }
  2020. _startRenderPage(transparency, intent) {
  2021. const intentState = this._intentStates.get(intent);
  2022. if (!intentState) {
  2023. return;
  2024. }
  2025. if (this._stats) {
  2026. this._stats.timeEnd("Page Request");
  2027. }
  2028. if (intentState.displayReadyCapability) {
  2029. intentState.displayReadyCapability.resolve(transparency);
  2030. }
  2031. }
  2032. _renderPageChunk(operatorListChunk, intentState) {
  2033. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2034. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2035. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  2036. }
  2037. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2038. for (const internalRenderTask of intentState.renderTasks) {
  2039. internalRenderTask.operatorListChanged();
  2040. }
  2041. if (operatorListChunk.lastChunk) {
  2042. this._tryCleanup();
  2043. }
  2044. }
  2045. _pumpOperatorList(args) {
  2046. (0, _util.assert)(args.intent, 'PDFPageProxy._pumpOperatorList: Expected "intent" argument.');
  2047. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", args);
  2048. const reader = readableStream.getReader();
  2049. const intentState = this._intentStates.get(args.intent);
  2050. intentState.streamReader = reader;
  2051. const pump = () => {
  2052. reader.read().then(({
  2053. value,
  2054. done
  2055. }) => {
  2056. if (done) {
  2057. intentState.streamReader = null;
  2058. return;
  2059. }
  2060. if (this._transport.destroyed) {
  2061. return;
  2062. }
  2063. this._renderPageChunk(value, intentState);
  2064. pump();
  2065. }, reason => {
  2066. intentState.streamReader = null;
  2067. if (this._transport.destroyed) {
  2068. return;
  2069. }
  2070. if (intentState.operatorList) {
  2071. intentState.operatorList.lastChunk = true;
  2072. for (const internalRenderTask of intentState.renderTasks) {
  2073. internalRenderTask.operatorListChanged();
  2074. }
  2075. this._tryCleanup();
  2076. }
  2077. if (intentState.displayReadyCapability) {
  2078. intentState.displayReadyCapability.reject(reason);
  2079. } else if (intentState.opListReadCapability) {
  2080. intentState.opListReadCapability.reject(reason);
  2081. } else {
  2082. throw reason;
  2083. }
  2084. });
  2085. };
  2086. pump();
  2087. }
  2088. _abortOperatorList({
  2089. intentState,
  2090. reason,
  2091. force = false
  2092. }) {
  2093. (0, _util.assert)(reason instanceof Error || typeof reason === "object" && reason !== null, 'PDFPageProxy._abortOperatorList: Expected "reason" argument.');
  2094. if (!intentState.streamReader) {
  2095. return;
  2096. }
  2097. if (!force) {
  2098. if (intentState.renderTasks.size > 0) {
  2099. return;
  2100. }
  2101. if (reason instanceof _display_utils.RenderingCancelledException) {
  2102. intentState.streamReaderCancelTimeout = setTimeout(() => {
  2103. this._abortOperatorList({
  2104. intentState,
  2105. reason,
  2106. force: true
  2107. });
  2108. intentState.streamReaderCancelTimeout = null;
  2109. }, RENDERING_CANCELLED_TIMEOUT);
  2110. return;
  2111. }
  2112. }
  2113. intentState.streamReader.cancel(new _util.AbortException(reason?.message));
  2114. intentState.streamReader = null;
  2115. if (this._transport.destroyed) {
  2116. return;
  2117. }
  2118. for (const [intent, curIntentState] of this._intentStates) {
  2119. if (curIntentState === intentState) {
  2120. this._intentStates.delete(intent);
  2121. break;
  2122. }
  2123. }
  2124. this.cleanup();
  2125. }
  2126. get stats() {
  2127. return this._stats;
  2128. }
  2129. }
  2130. exports.PDFPageProxy = PDFPageProxy;
  2131. class LoopbackPort {
  2132. constructor() {
  2133. this._listeners = [];
  2134. this._deferred = Promise.resolve(undefined);
  2135. }
  2136. postMessage(obj, transfers) {
  2137. function cloneValue(value) {
  2138. if (typeof value !== "object" || value === null) {
  2139. return value;
  2140. }
  2141. if (cloned.has(value)) {
  2142. return cloned.get(value);
  2143. }
  2144. let buffer, result;
  2145. if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) {
  2146. if (transfers?.includes(buffer)) {
  2147. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  2148. } else {
  2149. result = new value.constructor(value);
  2150. }
  2151. cloned.set(value, result);
  2152. return result;
  2153. }
  2154. if (value instanceof Map) {
  2155. result = new Map();
  2156. cloned.set(value, result);
  2157. for (const [key, val] of value) {
  2158. result.set(key, cloneValue(val));
  2159. }
  2160. return result;
  2161. }
  2162. if (value instanceof Set) {
  2163. result = new Set();
  2164. cloned.set(value, result);
  2165. for (const val of value) {
  2166. result.add(cloneValue(val));
  2167. }
  2168. return result;
  2169. }
  2170. if (value instanceof URL) {
  2171. throw new Error(`LoopbackPort.postMessage - cannot clone: ${value}`);
  2172. }
  2173. result = Array.isArray(value) ? [] : Object.create(null);
  2174. cloned.set(value, result);
  2175. for (const i in value) {
  2176. let desc,
  2177. p = value;
  2178. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  2179. p = Object.getPrototypeOf(p);
  2180. }
  2181. if (typeof desc.value === "undefined") {
  2182. continue;
  2183. }
  2184. if (typeof desc.value === "function") {
  2185. if (value.hasOwnProperty?.(i)) {
  2186. throw new Error(`LoopbackPort.postMessage - cannot clone: ${value[i]}`);
  2187. }
  2188. continue;
  2189. }
  2190. result[i] = cloneValue(desc.value);
  2191. }
  2192. return result;
  2193. }
  2194. const cloned = new WeakMap();
  2195. const event = {
  2196. data: cloneValue(obj)
  2197. };
  2198. this._deferred.then(() => {
  2199. for (const listener of this._listeners) {
  2200. listener.call(this, event);
  2201. }
  2202. });
  2203. }
  2204. addEventListener(name, listener) {
  2205. this._listeners.push(listener);
  2206. }
  2207. removeEventListener(name, listener) {
  2208. const i = this._listeners.indexOf(listener);
  2209. this._listeners.splice(i, 1);
  2210. }
  2211. terminate() {
  2212. this._listeners.length = 0;
  2213. }
  2214. }
  2215. exports.LoopbackPort = LoopbackPort;
  2216. const PDFWorker = function PDFWorkerClosure() {
  2217. const pdfWorkerPorts = new WeakMap();
  2218. let isWorkerDisabled = false;
  2219. let fallbackWorkerSrc;
  2220. let nextFakeWorkerId = 0;
  2221. let fakeWorkerCapability;
  2222. if (_is_node.isNodeJS && typeof require === "function") {
  2223. isWorkerDisabled = true;
  2224. fallbackWorkerSrc = "./pdf.worker.js";
  2225. } else if (typeof document === "object" && "currentScript" in document) {
  2226. const pdfjsFilePath = document.currentScript?.src;
  2227. if (pdfjsFilePath) {
  2228. fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  2229. }
  2230. }
  2231. function getWorkerSrc() {
  2232. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  2233. return _worker_options.GlobalWorkerOptions.workerSrc;
  2234. }
  2235. if (typeof fallbackWorkerSrc !== "undefined") {
  2236. if (!_is_node.isNodeJS) {
  2237. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  2238. }
  2239. return fallbackWorkerSrc;
  2240. }
  2241. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  2242. }
  2243. function getMainThreadWorkerMessageHandler() {
  2244. let mainWorkerMessageHandler;
  2245. try {
  2246. mainWorkerMessageHandler = globalThis.pdfjsWorker?.WorkerMessageHandler;
  2247. } catch (ex) {}
  2248. return mainWorkerMessageHandler || null;
  2249. }
  2250. function setupFakeWorkerGlobal() {
  2251. if (fakeWorkerCapability) {
  2252. return fakeWorkerCapability.promise;
  2253. }
  2254. fakeWorkerCapability = (0, _util.createPromiseCapability)();
  2255. const loader = async function () {
  2256. const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler();
  2257. if (mainWorkerMessageHandler) {
  2258. return mainWorkerMessageHandler;
  2259. }
  2260. if (_is_node.isNodeJS && typeof require === "function") {
  2261. const worker = eval("require")(getWorkerSrc());
  2262. return worker.WorkerMessageHandler;
  2263. }
  2264. await (0, _display_utils.loadScript)(getWorkerSrc());
  2265. return window.pdfjsWorker.WorkerMessageHandler;
  2266. };
  2267. loader().then(fakeWorkerCapability.resolve, fakeWorkerCapability.reject);
  2268. return fakeWorkerCapability.promise;
  2269. }
  2270. function createCDNWrapper(url) {
  2271. const wrapper = "importScripts('" + url + "');";
  2272. return URL.createObjectURL(new Blob([wrapper]));
  2273. }
  2274. class PDFWorker {
  2275. constructor({
  2276. name = null,
  2277. port = null,
  2278. verbosity = (0, _util.getVerbosityLevel)()
  2279. } = {}) {
  2280. if (port && pdfWorkerPorts.has(port)) {
  2281. throw new Error("Cannot use more than one PDFWorker per port");
  2282. }
  2283. this.name = name;
  2284. this.destroyed = false;
  2285. this.postMessageTransfers = true;
  2286. this.verbosity = verbosity;
  2287. this._readyCapability = (0, _util.createPromiseCapability)();
  2288. this._port = null;
  2289. this._webWorker = null;
  2290. this._messageHandler = null;
  2291. if (port) {
  2292. pdfWorkerPorts.set(port, this);
  2293. this._initializeFromPort(port);
  2294. return;
  2295. }
  2296. this._initialize();
  2297. }
  2298. get promise() {
  2299. return this._readyCapability.promise;
  2300. }
  2301. get port() {
  2302. return this._port;
  2303. }
  2304. get messageHandler() {
  2305. return this._messageHandler;
  2306. }
  2307. _initializeFromPort(port) {
  2308. this._port = port;
  2309. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  2310. this._messageHandler.on("ready", function () {});
  2311. this._readyCapability.resolve();
  2312. }
  2313. _initialize() {
  2314. if (typeof Worker !== "undefined" && !isWorkerDisabled && !getMainThreadWorkerMessageHandler()) {
  2315. let workerSrc = getWorkerSrc();
  2316. try {
  2317. if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) {
  2318. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  2319. }
  2320. const worker = new Worker(workerSrc);
  2321. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  2322. const terminateEarly = () => {
  2323. worker.removeEventListener("error", onWorkerError);
  2324. messageHandler.destroy();
  2325. worker.terminate();
  2326. if (this.destroyed) {
  2327. this._readyCapability.reject(new Error("Worker was destroyed"));
  2328. } else {
  2329. this._setupFakeWorker();
  2330. }
  2331. };
  2332. const onWorkerError = () => {
  2333. if (!this._webWorker) {
  2334. terminateEarly();
  2335. }
  2336. };
  2337. worker.addEventListener("error", onWorkerError);
  2338. messageHandler.on("test", data => {
  2339. worker.removeEventListener("error", onWorkerError);
  2340. if (this.destroyed) {
  2341. terminateEarly();
  2342. return;
  2343. }
  2344. if (data) {
  2345. this._messageHandler = messageHandler;
  2346. this._port = worker;
  2347. this._webWorker = worker;
  2348. if (!data.supportTransfers) {
  2349. this.postMessageTransfers = false;
  2350. }
  2351. this._readyCapability.resolve();
  2352. messageHandler.send("configure", {
  2353. verbosity: this.verbosity
  2354. });
  2355. } else {
  2356. this._setupFakeWorker();
  2357. messageHandler.destroy();
  2358. worker.terminate();
  2359. }
  2360. });
  2361. messageHandler.on("ready", data => {
  2362. worker.removeEventListener("error", onWorkerError);
  2363. if (this.destroyed) {
  2364. terminateEarly();
  2365. return;
  2366. }
  2367. try {
  2368. sendTest();
  2369. } catch (e) {
  2370. this._setupFakeWorker();
  2371. }
  2372. });
  2373. const sendTest = () => {
  2374. const testObj = new Uint8Array([this.postMessageTransfers ? 255 : 0]);
  2375. try {
  2376. messageHandler.send("test", testObj, [testObj.buffer]);
  2377. } catch (ex) {
  2378. (0, _util.warn)("Cannot use postMessage transfers.");
  2379. testObj[0] = 0;
  2380. messageHandler.send("test", testObj);
  2381. }
  2382. };
  2383. sendTest();
  2384. return;
  2385. } catch (e) {
  2386. (0, _util.info)("The worker has been disabled.");
  2387. }
  2388. }
  2389. this._setupFakeWorker();
  2390. }
  2391. _setupFakeWorker() {
  2392. if (!isWorkerDisabled) {
  2393. (0, _util.warn)("Setting up fake worker.");
  2394. isWorkerDisabled = true;
  2395. }
  2396. setupFakeWorkerGlobal().then(WorkerMessageHandler => {
  2397. if (this.destroyed) {
  2398. this._readyCapability.reject(new Error("Worker was destroyed"));
  2399. return;
  2400. }
  2401. const port = new LoopbackPort();
  2402. this._port = port;
  2403. const id = "fake" + nextFakeWorkerId++;
  2404. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  2405. WorkerMessageHandler.setup(workerHandler, port);
  2406. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  2407. this._messageHandler = messageHandler;
  2408. this._readyCapability.resolve();
  2409. messageHandler.send("configure", {
  2410. verbosity: this.verbosity
  2411. });
  2412. }).catch(reason => {
  2413. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  2414. });
  2415. }
  2416. destroy() {
  2417. this.destroyed = true;
  2418. if (this._webWorker) {
  2419. this._webWorker.terminate();
  2420. this._webWorker = null;
  2421. }
  2422. pdfWorkerPorts.delete(this._port);
  2423. this._port = null;
  2424. if (this._messageHandler) {
  2425. this._messageHandler.destroy();
  2426. this._messageHandler = null;
  2427. }
  2428. }
  2429. static fromPort(params) {
  2430. if (!params || !params.port) {
  2431. throw new Error("PDFWorker.fromPort - invalid method signature.");
  2432. }
  2433. if (pdfWorkerPorts.has(params.port)) {
  2434. return pdfWorkerPorts.get(params.port);
  2435. }
  2436. return new PDFWorker(params);
  2437. }
  2438. static getWorkerSrc() {
  2439. return getWorkerSrc();
  2440. }
  2441. }
  2442. return PDFWorker;
  2443. }();
  2444. exports.PDFWorker = PDFWorker;
  2445. class WorkerTransport {
  2446. constructor(messageHandler, loadingTask, networkStream, params) {
  2447. this.messageHandler = messageHandler;
  2448. this.loadingTask = loadingTask;
  2449. this.commonObjs = new PDFObjects();
  2450. this.fontLoader = new _font_loader.FontLoader({
  2451. docId: loadingTask.docId,
  2452. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2453. ownerDocument: params.ownerDocument
  2454. });
  2455. this._params = params;
  2456. this.CMapReaderFactory = new params.CMapReaderFactory({
  2457. baseUrl: params.cMapUrl,
  2458. isCompressed: params.cMapPacked
  2459. });
  2460. this.destroyed = false;
  2461. this.destroyCapability = null;
  2462. this._passwordCapability = null;
  2463. this._networkStream = networkStream;
  2464. this._fullReader = null;
  2465. this._lastProgress = null;
  2466. this.pageCache = [];
  2467. this.pagePromises = [];
  2468. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  2469. this.setupMessageHandler();
  2470. }
  2471. get annotationStorage() {
  2472. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2473. }
  2474. destroy() {
  2475. if (this.destroyCapability) {
  2476. return this.destroyCapability.promise;
  2477. }
  2478. this.destroyed = true;
  2479. this.destroyCapability = (0, _util.createPromiseCapability)();
  2480. if (this._passwordCapability) {
  2481. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2482. }
  2483. const waitOn = [];
  2484. for (const page of this.pageCache) {
  2485. if (page) {
  2486. waitOn.push(page._destroy());
  2487. }
  2488. }
  2489. this.pageCache.length = 0;
  2490. this.pagePromises.length = 0;
  2491. if (this.hasOwnProperty("annotationStorage")) {
  2492. this.annotationStorage.resetModified();
  2493. }
  2494. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2495. waitOn.push(terminated);
  2496. Promise.all(waitOn).then(() => {
  2497. this.commonObjs.clear();
  2498. this.fontLoader.clear();
  2499. this._hasJSActionsPromise = null;
  2500. if (this._networkStream) {
  2501. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2502. }
  2503. if (this.messageHandler) {
  2504. this.messageHandler.destroy();
  2505. this.messageHandler = null;
  2506. }
  2507. this.destroyCapability.resolve();
  2508. }, this.destroyCapability.reject);
  2509. return this.destroyCapability.promise;
  2510. }
  2511. setupMessageHandler() {
  2512. const {
  2513. messageHandler,
  2514. loadingTask
  2515. } = this;
  2516. messageHandler.on("GetReader", (data, sink) => {
  2517. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2518. this._fullReader = this._networkStream.getFullReader();
  2519. this._fullReader.onProgress = evt => {
  2520. this._lastProgress = {
  2521. loaded: evt.loaded,
  2522. total: evt.total
  2523. };
  2524. };
  2525. sink.onPull = () => {
  2526. this._fullReader.read().then(function ({
  2527. value,
  2528. done
  2529. }) {
  2530. if (done) {
  2531. sink.close();
  2532. return;
  2533. }
  2534. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
  2535. sink.enqueue(new Uint8Array(value), 1, [value]);
  2536. }).catch(reason => {
  2537. sink.error(reason);
  2538. });
  2539. };
  2540. sink.onCancel = reason => {
  2541. this._fullReader.cancel(reason);
  2542. sink.ready.catch(readyReason => {
  2543. if (this.destroyed) {
  2544. return;
  2545. }
  2546. throw readyReason;
  2547. });
  2548. };
  2549. });
  2550. messageHandler.on("ReaderHeadersReady", data => {
  2551. const headersCapability = (0, _util.createPromiseCapability)();
  2552. const fullReader = this._fullReader;
  2553. fullReader.headersReady.then(() => {
  2554. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2555. if (this._lastProgress && loadingTask.onProgress) {
  2556. loadingTask.onProgress(this._lastProgress);
  2557. }
  2558. fullReader.onProgress = evt => {
  2559. if (loadingTask.onProgress) {
  2560. loadingTask.onProgress({
  2561. loaded: evt.loaded,
  2562. total: evt.total
  2563. });
  2564. }
  2565. };
  2566. }
  2567. headersCapability.resolve({
  2568. isStreamingSupported: fullReader.isStreamingSupported,
  2569. isRangeSupported: fullReader.isRangeSupported,
  2570. contentLength: fullReader.contentLength
  2571. });
  2572. }, headersCapability.reject);
  2573. return headersCapability.promise;
  2574. });
  2575. messageHandler.on("GetRangeReader", (data, sink) => {
  2576. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2577. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2578. if (!rangeReader) {
  2579. sink.close();
  2580. return;
  2581. }
  2582. sink.onPull = () => {
  2583. rangeReader.read().then(function ({
  2584. value,
  2585. done
  2586. }) {
  2587. if (done) {
  2588. sink.close();
  2589. return;
  2590. }
  2591. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
  2592. sink.enqueue(new Uint8Array(value), 1, [value]);
  2593. }).catch(reason => {
  2594. sink.error(reason);
  2595. });
  2596. };
  2597. sink.onCancel = reason => {
  2598. rangeReader.cancel(reason);
  2599. sink.ready.catch(readyReason => {
  2600. if (this.destroyed) {
  2601. return;
  2602. }
  2603. throw readyReason;
  2604. });
  2605. };
  2606. });
  2607. messageHandler.on("GetDoc", ({
  2608. pdfInfo
  2609. }) => {
  2610. this._numPages = pdfInfo.numPages;
  2611. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2612. });
  2613. messageHandler.on("DocException", function (ex) {
  2614. let reason;
  2615. switch (ex.name) {
  2616. case "PasswordException":
  2617. reason = new _util.PasswordException(ex.message, ex.code);
  2618. break;
  2619. case "InvalidPDFException":
  2620. reason = new _util.InvalidPDFException(ex.message);
  2621. break;
  2622. case "MissingPDFException":
  2623. reason = new _util.MissingPDFException(ex.message);
  2624. break;
  2625. case "UnexpectedResponseException":
  2626. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2627. break;
  2628. case "UnknownErrorException":
  2629. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2630. break;
  2631. }
  2632. if (!(reason instanceof Error)) {
  2633. const msg = "DocException - expected a valid Error.";
  2634. (0, _util.warn)(msg);
  2635. }
  2636. loadingTask._capability.reject(reason);
  2637. });
  2638. messageHandler.on("PasswordRequest", exception => {
  2639. this._passwordCapability = (0, _util.createPromiseCapability)();
  2640. if (loadingTask.onPassword) {
  2641. const updatePassword = password => {
  2642. this._passwordCapability.resolve({
  2643. password
  2644. });
  2645. };
  2646. try {
  2647. loadingTask.onPassword(updatePassword, exception.code);
  2648. } catch (ex) {
  2649. this._passwordCapability.reject(ex);
  2650. }
  2651. } else {
  2652. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2653. }
  2654. return this._passwordCapability.promise;
  2655. });
  2656. messageHandler.on("DataLoaded", data => {
  2657. if (loadingTask.onProgress) {
  2658. loadingTask.onProgress({
  2659. loaded: data.length,
  2660. total: data.length
  2661. });
  2662. }
  2663. this.downloadInfoCapability.resolve(data);
  2664. });
  2665. messageHandler.on("StartRenderPage", data => {
  2666. if (this.destroyed) {
  2667. return;
  2668. }
  2669. const page = this.pageCache[data.pageIndex];
  2670. page._startRenderPage(data.transparency, data.intent);
  2671. });
  2672. messageHandler.on("commonobj", data => {
  2673. if (this.destroyed) {
  2674. return;
  2675. }
  2676. const [id, type, exportedData] = data;
  2677. if (this.commonObjs.has(id)) {
  2678. return;
  2679. }
  2680. switch (type) {
  2681. case "Font":
  2682. const params = this._params;
  2683. if ("error" in exportedData) {
  2684. const exportedError = exportedData.error;
  2685. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2686. this.commonObjs.resolve(id, exportedError);
  2687. break;
  2688. }
  2689. let fontRegistry = null;
  2690. if (params.pdfBug && globalThis.FontInspector?.enabled) {
  2691. fontRegistry = {
  2692. registerFont(font, url) {
  2693. globalThis.FontInspector.fontAdded(font, url);
  2694. }
  2695. };
  2696. }
  2697. const font = new _font_loader.FontFaceObject(exportedData, {
  2698. isEvalSupported: params.isEvalSupported,
  2699. disableFontFace: params.disableFontFace,
  2700. ignoreErrors: params.ignoreErrors,
  2701. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2702. fontRegistry
  2703. });
  2704. this.fontLoader.bind(font).catch(reason => {
  2705. return messageHandler.sendWithPromise("FontFallback", {
  2706. id
  2707. });
  2708. }).finally(() => {
  2709. if (!params.fontExtraProperties && font.data) {
  2710. font.data = null;
  2711. }
  2712. this.commonObjs.resolve(id, font);
  2713. });
  2714. break;
  2715. case "FontPath":
  2716. case "Image":
  2717. this.commonObjs.resolve(id, exportedData);
  2718. break;
  2719. default:
  2720. throw new Error(`Got unknown common object type ${type}`);
  2721. }
  2722. });
  2723. messageHandler.on("obj", data => {
  2724. if (this.destroyed) {
  2725. return undefined;
  2726. }
  2727. const [id, pageIndex, type, imageData] = data;
  2728. const pageProxy = this.pageCache[pageIndex];
  2729. if (pageProxy.objs.has(id)) {
  2730. return undefined;
  2731. }
  2732. switch (type) {
  2733. case "Image":
  2734. pageProxy.objs.resolve(id, imageData);
  2735. const MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2736. if (imageData?.data?.length > MAX_IMAGE_SIZE_TO_STORE) {
  2737. pageProxy.cleanupAfterRender = true;
  2738. }
  2739. break;
  2740. default:
  2741. throw new Error(`Got unknown object type ${type}`);
  2742. }
  2743. return undefined;
  2744. });
  2745. messageHandler.on("DocProgress", data => {
  2746. if (this.destroyed) {
  2747. return;
  2748. }
  2749. if (loadingTask.onProgress) {
  2750. loadingTask.onProgress({
  2751. loaded: data.loaded,
  2752. total: data.total
  2753. });
  2754. }
  2755. });
  2756. messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
  2757. messageHandler.on("FetchBuiltInCMap", (data, sink) => {
  2758. if (this.destroyed) {
  2759. sink.error(new Error("Worker was destroyed"));
  2760. return;
  2761. }
  2762. let fetched = false;
  2763. sink.onPull = () => {
  2764. if (fetched) {
  2765. sink.close();
  2766. return;
  2767. }
  2768. fetched = true;
  2769. this.CMapReaderFactory.fetch(data).then(function (builtInCMap) {
  2770. sink.enqueue(builtInCMap, 1, [builtInCMap.cMapData.buffer]);
  2771. }).catch(function (reason) {
  2772. sink.error(reason);
  2773. });
  2774. };
  2775. });
  2776. }
  2777. _onUnsupportedFeature({
  2778. featureId
  2779. }) {
  2780. if (this.destroyed) {
  2781. return;
  2782. }
  2783. if (this.loadingTask.onUnsupportedFeature) {
  2784. this.loadingTask.onUnsupportedFeature(featureId);
  2785. }
  2786. }
  2787. getData() {
  2788. return this.messageHandler.sendWithPromise("GetData", null);
  2789. }
  2790. getPage(pageNumber) {
  2791. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  2792. return Promise.reject(new Error("Invalid page request"));
  2793. }
  2794. const pageIndex = pageNumber - 1;
  2795. if (pageIndex in this.pagePromises) {
  2796. return this.pagePromises[pageIndex];
  2797. }
  2798. const promise = this.messageHandler.sendWithPromise("GetPage", {
  2799. pageIndex
  2800. }).then(pageInfo => {
  2801. if (this.destroyed) {
  2802. throw new Error("Transport destroyed");
  2803. }
  2804. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
  2805. this.pageCache[pageIndex] = page;
  2806. return page;
  2807. });
  2808. this.pagePromises[pageIndex] = promise;
  2809. return promise;
  2810. }
  2811. getPageIndex(ref) {
  2812. return this.messageHandler.sendWithPromise("GetPageIndex", {
  2813. ref
  2814. }).catch(function (reason) {
  2815. return Promise.reject(new Error(reason));
  2816. });
  2817. }
  2818. getAnnotations(pageIndex, intent) {
  2819. return this.messageHandler.sendWithPromise("GetAnnotations", {
  2820. pageIndex,
  2821. intent
  2822. });
  2823. }
  2824. saveDocument() {
  2825. return this.messageHandler.sendWithPromise("SaveDocument", {
  2826. numPages: this._numPages,
  2827. annotationStorage: this.annotationStorage.serializable,
  2828. filename: this._fullReader?.filename ?? null
  2829. }).finally(() => {
  2830. this.annotationStorage.resetModified();
  2831. });
  2832. }
  2833. getFieldObjects() {
  2834. return this.messageHandler.sendWithPromise("GetFieldObjects", null);
  2835. }
  2836. hasJSActions() {
  2837. return this._hasJSActionsPromise || (this._hasJSActionsPromise = this.messageHandler.sendWithPromise("HasJSActions", null));
  2838. }
  2839. getCalculationOrderIds() {
  2840. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  2841. }
  2842. getDestinations() {
  2843. return this.messageHandler.sendWithPromise("GetDestinations", null);
  2844. }
  2845. getDestination(id) {
  2846. if (typeof id !== "string") {
  2847. return Promise.reject(new Error("Invalid destination request."));
  2848. }
  2849. return this.messageHandler.sendWithPromise("GetDestination", {
  2850. id
  2851. });
  2852. }
  2853. getPageLabels() {
  2854. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  2855. }
  2856. getPageLayout() {
  2857. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  2858. }
  2859. getPageMode() {
  2860. return this.messageHandler.sendWithPromise("GetPageMode", null);
  2861. }
  2862. getViewerPreferences() {
  2863. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  2864. }
  2865. getOpenAction() {
  2866. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  2867. }
  2868. getAttachments() {
  2869. return this.messageHandler.sendWithPromise("GetAttachments", null);
  2870. }
  2871. getJavaScript() {
  2872. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  2873. }
  2874. getDocJSActions() {
  2875. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  2876. }
  2877. getPageJSActions(pageIndex) {
  2878. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  2879. pageIndex
  2880. });
  2881. }
  2882. getPageXfa(pageIndex) {
  2883. return this.messageHandler.sendWithPromise("GetPageXfa", {
  2884. pageIndex
  2885. });
  2886. }
  2887. getStructTree(pageIndex) {
  2888. return this.messageHandler.sendWithPromise("GetStructTree", {
  2889. pageIndex
  2890. });
  2891. }
  2892. getOutline() {
  2893. return this.messageHandler.sendWithPromise("GetOutline", null);
  2894. }
  2895. getOptionalContentConfig() {
  2896. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  2897. return new _optional_content_config.OptionalContentConfig(results);
  2898. });
  2899. }
  2900. getPermissions() {
  2901. return this.messageHandler.sendWithPromise("GetPermissions", null);
  2902. }
  2903. getMetadata() {
  2904. return this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
  2905. return {
  2906. info: results[0],
  2907. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  2908. contentDispositionFilename: this._fullReader?.filename ?? null,
  2909. contentLength: this._fullReader?.contentLength ?? null
  2910. };
  2911. });
  2912. }
  2913. getMarkInfo() {
  2914. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  2915. }
  2916. getStats() {
  2917. return this.messageHandler.sendWithPromise("GetStats", null);
  2918. }
  2919. async startCleanup(keepLoadedFonts = false) {
  2920. await this.messageHandler.sendWithPromise("Cleanup", null);
  2921. if (this.destroyed) {
  2922. return;
  2923. }
  2924. for (let i = 0, ii = this.pageCache.length; i < ii; i++) {
  2925. const page = this.pageCache[i];
  2926. if (!page) {
  2927. continue;
  2928. }
  2929. const cleanupSuccessful = page.cleanup();
  2930. if (!cleanupSuccessful) {
  2931. throw new Error(`startCleanup: Page ${i + 1} is currently rendering.`);
  2932. }
  2933. }
  2934. this.commonObjs.clear();
  2935. if (!keepLoadedFonts) {
  2936. this.fontLoader.clear();
  2937. }
  2938. this._hasJSActionsPromise = null;
  2939. }
  2940. get loadingParams() {
  2941. const params = this._params;
  2942. return (0, _util.shadow)(this, "loadingParams", {
  2943. disableAutoFetch: params.disableAutoFetch,
  2944. disableFontFace: params.disableFontFace
  2945. });
  2946. }
  2947. }
  2948. class PDFObjects {
  2949. constructor() {
  2950. this._objs = Object.create(null);
  2951. }
  2952. _ensureObj(objId) {
  2953. if (this._objs[objId]) {
  2954. return this._objs[objId];
  2955. }
  2956. return this._objs[objId] = {
  2957. capability: (0, _util.createPromiseCapability)(),
  2958. data: null,
  2959. resolved: false
  2960. };
  2961. }
  2962. get(objId, callback = null) {
  2963. if (callback) {
  2964. this._ensureObj(objId).capability.promise.then(callback);
  2965. return null;
  2966. }
  2967. const obj = this._objs[objId];
  2968. if (!obj || !obj.resolved) {
  2969. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  2970. }
  2971. return obj.data;
  2972. }
  2973. has(objId) {
  2974. const obj = this._objs[objId];
  2975. return obj?.resolved || false;
  2976. }
  2977. resolve(objId, data) {
  2978. const obj = this._ensureObj(objId);
  2979. obj.resolved = true;
  2980. obj.data = data;
  2981. obj.capability.resolve(data);
  2982. }
  2983. clear() {
  2984. this._objs = Object.create(null);
  2985. }
  2986. }
  2987. class RenderTask {
  2988. constructor(internalRenderTask) {
  2989. this._internalRenderTask = internalRenderTask;
  2990. this.onContinue = null;
  2991. }
  2992. get promise() {
  2993. return this._internalRenderTask.capability.promise;
  2994. }
  2995. cancel() {
  2996. this._internalRenderTask.cancel();
  2997. }
  2998. }
  2999. const InternalRenderTask = function InternalRenderTaskClosure() {
  3000. const canvasInRendering = new WeakSet();
  3001. class InternalRenderTask {
  3002. constructor({
  3003. callback,
  3004. params,
  3005. objs,
  3006. commonObjs,
  3007. operatorList,
  3008. pageIndex,
  3009. canvasFactory,
  3010. useRequestAnimationFrame = false,
  3011. pdfBug = false
  3012. }) {
  3013. this.callback = callback;
  3014. this.params = params;
  3015. this.objs = objs;
  3016. this.commonObjs = commonObjs;
  3017. this.operatorListIdx = null;
  3018. this.operatorList = operatorList;
  3019. this._pageIndex = pageIndex;
  3020. this.canvasFactory = canvasFactory;
  3021. this._pdfBug = pdfBug;
  3022. this.running = false;
  3023. this.graphicsReadyCallback = null;
  3024. this.graphicsReady = false;
  3025. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  3026. this.cancelled = false;
  3027. this.capability = (0, _util.createPromiseCapability)();
  3028. this.task = new RenderTask(this);
  3029. this._cancelBound = this.cancel.bind(this);
  3030. this._continueBound = this._continue.bind(this);
  3031. this._scheduleNextBound = this._scheduleNext.bind(this);
  3032. this._nextBound = this._next.bind(this);
  3033. this._canvas = params.canvasContext.canvas;
  3034. }
  3035. get completed() {
  3036. return this.capability.promise.catch(function () {});
  3037. }
  3038. initializeGraphics({
  3039. transparency = false,
  3040. optionalContentConfig
  3041. }) {
  3042. if (this.cancelled) {
  3043. return;
  3044. }
  3045. if (this._canvas) {
  3046. if (canvasInRendering.has(this._canvas)) {
  3047. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  3048. }
  3049. canvasInRendering.add(this._canvas);
  3050. }
  3051. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  3052. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  3053. this.stepper.init(this.operatorList);
  3054. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  3055. }
  3056. const {
  3057. canvasContext,
  3058. viewport,
  3059. transform,
  3060. imageLayer,
  3061. background
  3062. } = this.params;
  3063. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig);
  3064. this.gfx.beginDrawing({
  3065. transform,
  3066. viewport,
  3067. transparency,
  3068. background
  3069. });
  3070. this.operatorListIdx = 0;
  3071. this.graphicsReady = true;
  3072. if (this.graphicsReadyCallback) {
  3073. this.graphicsReadyCallback();
  3074. }
  3075. }
  3076. cancel(error = null) {
  3077. this.running = false;
  3078. this.cancelled = true;
  3079. if (this.gfx) {
  3080. this.gfx.endDrawing();
  3081. }
  3082. if (this._canvas) {
  3083. canvasInRendering.delete(this._canvas);
  3084. }
  3085. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
  3086. }
  3087. operatorListChanged() {
  3088. if (!this.graphicsReady) {
  3089. if (!this.graphicsReadyCallback) {
  3090. this.graphicsReadyCallback = this._continueBound;
  3091. }
  3092. return;
  3093. }
  3094. if (this.stepper) {
  3095. this.stepper.updateOperatorList(this.operatorList);
  3096. }
  3097. if (this.running) {
  3098. return;
  3099. }
  3100. this._continue();
  3101. }
  3102. _continue() {
  3103. this.running = true;
  3104. if (this.cancelled) {
  3105. return;
  3106. }
  3107. if (this.task.onContinue) {
  3108. this.task.onContinue(this._scheduleNextBound);
  3109. } else {
  3110. this._scheduleNext();
  3111. }
  3112. }
  3113. _scheduleNext() {
  3114. if (this._useRequestAnimationFrame) {
  3115. window.requestAnimationFrame(() => {
  3116. this._nextBound().catch(this._cancelBound);
  3117. });
  3118. } else {
  3119. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  3120. }
  3121. }
  3122. async _next() {
  3123. if (this.cancelled) {
  3124. return;
  3125. }
  3126. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  3127. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  3128. this.running = false;
  3129. if (this.operatorList.lastChunk) {
  3130. this.gfx.endDrawing();
  3131. if (this._canvas) {
  3132. canvasInRendering.delete(this._canvas);
  3133. }
  3134. this.callback();
  3135. }
  3136. }
  3137. }
  3138. }
  3139. return InternalRenderTask;
  3140. }();
  3141. const version = '2.9.359';
  3142. exports.version = version;
  3143. const build = 'e667c8cbc';
  3144. exports.build = build;
  3145. /***/ }),
  3146. /* 6 */
  3147. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3148. Object.defineProperty(exports, "__esModule", ({
  3149. value: true
  3150. }));
  3151. exports.FontLoader = exports.FontFaceObject = void 0;
  3152. var _util = __w_pdfjs_require__(2);
  3153. class BaseFontLoader {
  3154. constructor({
  3155. docId,
  3156. onUnsupportedFeature,
  3157. ownerDocument = globalThis.document
  3158. }) {
  3159. if (this.constructor === BaseFontLoader) {
  3160. (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
  3161. }
  3162. this.docId = docId;
  3163. this._onUnsupportedFeature = onUnsupportedFeature;
  3164. this._document = ownerDocument;
  3165. this.nativeFontFaces = [];
  3166. this.styleElement = null;
  3167. }
  3168. addNativeFontFace(nativeFontFace) {
  3169. this.nativeFontFaces.push(nativeFontFace);
  3170. this._document.fonts.add(nativeFontFace);
  3171. }
  3172. insertRule(rule) {
  3173. let styleElement = this.styleElement;
  3174. if (!styleElement) {
  3175. styleElement = this.styleElement = this._document.createElement("style");
  3176. styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
  3177. this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
  3178. }
  3179. const styleSheet = styleElement.sheet;
  3180. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  3181. }
  3182. clear() {
  3183. for (const nativeFontFace of this.nativeFontFaces) {
  3184. this._document.fonts.delete(nativeFontFace);
  3185. }
  3186. this.nativeFontFaces.length = 0;
  3187. if (this.styleElement) {
  3188. this.styleElement.remove();
  3189. this.styleElement = null;
  3190. }
  3191. }
  3192. async bind(font) {
  3193. if (font.attached || font.missingFile) {
  3194. return;
  3195. }
  3196. font.attached = true;
  3197. if (this.isFontLoadingAPISupported) {
  3198. const nativeFontFace = font.createNativeFontFace();
  3199. if (nativeFontFace) {
  3200. this.addNativeFontFace(nativeFontFace);
  3201. try {
  3202. await nativeFontFace.loaded;
  3203. } catch (ex) {
  3204. this._onUnsupportedFeature({
  3205. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  3206. });
  3207. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  3208. font.disableFontFace = true;
  3209. throw ex;
  3210. }
  3211. }
  3212. return;
  3213. }
  3214. const rule = font.createFontFaceRule();
  3215. if (rule) {
  3216. this.insertRule(rule);
  3217. if (this.isSyncFontLoadingSupported) {
  3218. return;
  3219. }
  3220. await new Promise(resolve => {
  3221. const request = this._queueLoadingCallback(resolve);
  3222. this._prepareFontLoadEvent([rule], [font], request);
  3223. });
  3224. }
  3225. }
  3226. _queueLoadingCallback(callback) {
  3227. (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
  3228. }
  3229. get isFontLoadingAPISupported() {
  3230. return (0, _util.shadow)(this, "isFontLoadingAPISupported", !!this._document?.fonts);
  3231. }
  3232. get isSyncFontLoadingSupported() {
  3233. (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
  3234. }
  3235. get _loadTestFont() {
  3236. (0, _util.unreachable)("Abstract method `_loadTestFont`.");
  3237. }
  3238. _prepareFontLoadEvent(rules, fontsToLoad, request) {
  3239. (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
  3240. }
  3241. }
  3242. let FontLoader;
  3243. exports.FontLoader = FontLoader;
  3244. {
  3245. exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
  3246. constructor(params) {
  3247. super(params);
  3248. this.loadingContext = {
  3249. requests: [],
  3250. nextRequestId: 0
  3251. };
  3252. this.loadTestFontId = 0;
  3253. }
  3254. get isSyncFontLoadingSupported() {
  3255. let supported = false;
  3256. if (typeof navigator === "undefined") {
  3257. supported = true;
  3258. } else {
  3259. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  3260. if (m?.[1] >= 14) {
  3261. supported = true;
  3262. }
  3263. }
  3264. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  3265. }
  3266. _queueLoadingCallback(callback) {
  3267. function completeRequest() {
  3268. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  3269. request.done = true;
  3270. while (context.requests.length > 0 && context.requests[0].done) {
  3271. const otherRequest = context.requests.shift();
  3272. setTimeout(otherRequest.callback, 0);
  3273. }
  3274. }
  3275. const context = this.loadingContext;
  3276. const request = {
  3277. id: `pdfjs-font-loading-${context.nextRequestId++}`,
  3278. done: false,
  3279. complete: completeRequest,
  3280. callback
  3281. };
  3282. context.requests.push(request);
  3283. return request;
  3284. }
  3285. get _loadTestFont() {
  3286. const getLoadTestFont = function () {
  3287. 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==");
  3288. };
  3289. return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
  3290. }
  3291. _prepareFontLoadEvent(rules, fonts, request) {
  3292. function int32(data, offset) {
  3293. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  3294. }
  3295. function spliceString(s, offset, remove, insert) {
  3296. const chunk1 = s.substring(0, offset);
  3297. const chunk2 = s.substring(offset + remove);
  3298. return chunk1 + insert + chunk2;
  3299. }
  3300. let i, ii;
  3301. const canvas = this._document.createElement("canvas");
  3302. canvas.width = 1;
  3303. canvas.height = 1;
  3304. const ctx = canvas.getContext("2d");
  3305. let called = 0;
  3306. function isFontReady(name, callback) {
  3307. called++;
  3308. if (called > 30) {
  3309. (0, _util.warn)("Load test font never loaded.");
  3310. callback();
  3311. return;
  3312. }
  3313. ctx.font = "30px " + name;
  3314. ctx.fillText(".", 0, 20);
  3315. const imageData = ctx.getImageData(0, 0, 1, 1);
  3316. if (imageData.data[3] > 0) {
  3317. callback();
  3318. return;
  3319. }
  3320. setTimeout(isFontReady.bind(null, name, callback));
  3321. }
  3322. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  3323. let data = this._loadTestFont;
  3324. const COMMENT_OFFSET = 976;
  3325. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  3326. const CFF_CHECKSUM_OFFSET = 16;
  3327. const XXXX_VALUE = 0x58585858;
  3328. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  3329. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  3330. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  3331. }
  3332. if (i < loadTestFontId.length) {
  3333. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  3334. }
  3335. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  3336. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  3337. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  3338. this.insertRule(rule);
  3339. const names = [];
  3340. for (const font of fonts) {
  3341. names.push(font.loadedName);
  3342. }
  3343. names.push(loadTestFontId);
  3344. const div = this._document.createElement("div");
  3345. div.style.visibility = "hidden";
  3346. div.style.width = div.style.height = "10px";
  3347. div.style.position = "absolute";
  3348. div.style.top = div.style.left = "0px";
  3349. for (const name of names) {
  3350. const span = this._document.createElement("span");
  3351. span.textContent = "Hi";
  3352. span.style.fontFamily = name;
  3353. div.appendChild(span);
  3354. }
  3355. this._document.body.appendChild(div);
  3356. isFontReady(loadTestFontId, () => {
  3357. this._document.body.removeChild(div);
  3358. request.complete();
  3359. });
  3360. }
  3361. };
  3362. }
  3363. class FontFaceObject {
  3364. constructor(translatedData, {
  3365. isEvalSupported = true,
  3366. disableFontFace = false,
  3367. ignoreErrors = false,
  3368. onUnsupportedFeature,
  3369. fontRegistry = null
  3370. }) {
  3371. this.compiledGlyphs = Object.create(null);
  3372. for (const i in translatedData) {
  3373. this[i] = translatedData[i];
  3374. }
  3375. this.isEvalSupported = isEvalSupported !== false;
  3376. this.disableFontFace = disableFontFace === true;
  3377. this.ignoreErrors = ignoreErrors === true;
  3378. this._onUnsupportedFeature = onUnsupportedFeature;
  3379. this.fontRegistry = fontRegistry;
  3380. }
  3381. createNativeFontFace() {
  3382. if (!this.data || this.disableFontFace) {
  3383. return null;
  3384. }
  3385. let nativeFontFace;
  3386. if (!this.cssFontInfo) {
  3387. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  3388. } else {
  3389. const css = {
  3390. weight: this.cssFontInfo.fontWeight
  3391. };
  3392. if (this.cssFontInfo.italicAngle) {
  3393. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  3394. }
  3395. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  3396. }
  3397. if (this.fontRegistry) {
  3398. this.fontRegistry.registerFont(this);
  3399. }
  3400. return nativeFontFace;
  3401. }
  3402. createFontFaceRule() {
  3403. if (!this.data || this.disableFontFace) {
  3404. return null;
  3405. }
  3406. const data = (0, _util.bytesToString)(this.data);
  3407. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  3408. let rule;
  3409. if (!this.cssFontInfo) {
  3410. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  3411. } else {
  3412. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  3413. if (this.cssFontInfo.italicAngle) {
  3414. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  3415. }
  3416. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  3417. }
  3418. if (this.fontRegistry) {
  3419. this.fontRegistry.registerFont(this, url);
  3420. }
  3421. return rule;
  3422. }
  3423. getPathGenerator(objs, character) {
  3424. if (this.compiledGlyphs[character] !== undefined) {
  3425. return this.compiledGlyphs[character];
  3426. }
  3427. let cmds;
  3428. try {
  3429. cmds = objs.get(this.loadedName + "_path_" + character);
  3430. } catch (ex) {
  3431. if (!this.ignoreErrors) {
  3432. throw ex;
  3433. }
  3434. this._onUnsupportedFeature({
  3435. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  3436. });
  3437. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  3438. return this.compiledGlyphs[character] = function (c, size) {};
  3439. }
  3440. if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
  3441. const jsBuf = [];
  3442. for (const current of cmds) {
  3443. const args = current.args !== undefined ? current.args.join(",") : "";
  3444. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  3445. }
  3446. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  3447. }
  3448. return this.compiledGlyphs[character] = function (c, size) {
  3449. for (const current of cmds) {
  3450. if (current.cmd === "scale") {
  3451. current.args = [size, -size];
  3452. }
  3453. c[current.cmd].apply(c, current.args);
  3454. }
  3455. };
  3456. }
  3457. }
  3458. exports.FontFaceObject = FontFaceObject;
  3459. /***/ }),
  3460. /* 7 */
  3461. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3462. Object.defineProperty(exports, "__esModule", ({
  3463. value: true
  3464. }));
  3465. exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = void 0;
  3466. var _display_utils = __w_pdfjs_require__(1);
  3467. var _is_node = __w_pdfjs_require__(4);
  3468. var _util = __w_pdfjs_require__(2);
  3469. let NodeCanvasFactory = class {
  3470. constructor() {
  3471. (0, _util.unreachable)("Not implemented: NodeCanvasFactory");
  3472. }
  3473. };
  3474. exports.NodeCanvasFactory = NodeCanvasFactory;
  3475. let NodeCMapReaderFactory = class {
  3476. constructor() {
  3477. (0, _util.unreachable)("Not implemented: NodeCMapReaderFactory");
  3478. }
  3479. };
  3480. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  3481. if (_is_node.isNodeJS) {
  3482. exports.NodeCanvasFactory = NodeCanvasFactory = class extends _display_utils.BaseCanvasFactory {
  3483. create(width, height) {
  3484. if (width <= 0 || height <= 0) {
  3485. throw new Error("Invalid canvas size");
  3486. }
  3487. const Canvas = require("canvas");
  3488. const canvas = Canvas.createCanvas(width, height);
  3489. return {
  3490. canvas,
  3491. context: canvas.getContext("2d")
  3492. };
  3493. }
  3494. };
  3495. exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _display_utils.BaseCMapReaderFactory {
  3496. _fetchData(url, compressionType) {
  3497. return new Promise((resolve, reject) => {
  3498. const fs = require("fs");
  3499. fs.readFile(url, (error, data) => {
  3500. if (error || !data) {
  3501. reject(new Error(error));
  3502. return;
  3503. }
  3504. resolve({
  3505. cMapData: new Uint8Array(data),
  3506. compressionType
  3507. });
  3508. });
  3509. });
  3510. }
  3511. };
  3512. }
  3513. /***/ }),
  3514. /* 8 */
  3515. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3516. Object.defineProperty(exports, "__esModule", ({
  3517. value: true
  3518. }));
  3519. exports.AnnotationStorage = void 0;
  3520. var _util = __w_pdfjs_require__(2);
  3521. class AnnotationStorage {
  3522. constructor() {
  3523. this._storage = new Map();
  3524. this._modified = false;
  3525. this.onSetModified = null;
  3526. this.onResetModified = null;
  3527. }
  3528. getValue(key, defaultValue) {
  3529. const obj = this._storage.get(key);
  3530. return obj !== undefined ? obj : defaultValue;
  3531. }
  3532. setValue(key, value) {
  3533. const obj = this._storage.get(key);
  3534. let modified = false;
  3535. if (obj !== undefined) {
  3536. for (const [entry, val] of Object.entries(value)) {
  3537. if (obj[entry] !== val) {
  3538. modified = true;
  3539. obj[entry] = val;
  3540. }
  3541. }
  3542. } else {
  3543. this._storage.set(key, value);
  3544. modified = true;
  3545. }
  3546. if (modified) {
  3547. this._setModified();
  3548. }
  3549. }
  3550. getAll() {
  3551. return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
  3552. }
  3553. get size() {
  3554. return this._storage.size;
  3555. }
  3556. _setModified() {
  3557. if (!this._modified) {
  3558. this._modified = true;
  3559. if (typeof this.onSetModified === "function") {
  3560. this.onSetModified();
  3561. }
  3562. }
  3563. }
  3564. resetModified() {
  3565. if (this._modified) {
  3566. this._modified = false;
  3567. if (typeof this.onResetModified === "function") {
  3568. this.onResetModified();
  3569. }
  3570. }
  3571. }
  3572. get serializable() {
  3573. return this._storage.size > 0 ? this._storage : null;
  3574. }
  3575. }
  3576. exports.AnnotationStorage = AnnotationStorage;
  3577. /***/ }),
  3578. /* 9 */
  3579. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3580. Object.defineProperty(exports, "__esModule", ({
  3581. value: true
  3582. }));
  3583. exports.apiCompatibilityParams = void 0;
  3584. var _is_node = __w_pdfjs_require__(4);
  3585. const compatibilityParams = Object.create(null);
  3586. {
  3587. (function checkFontFace() {
  3588. if (_is_node.isNodeJS) {
  3589. compatibilityParams.disableFontFace = true;
  3590. }
  3591. })();
  3592. }
  3593. const apiCompatibilityParams = Object.freeze(compatibilityParams);
  3594. exports.apiCompatibilityParams = apiCompatibilityParams;
  3595. /***/ }),
  3596. /* 10 */
  3597. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3598. Object.defineProperty(exports, "__esModule", ({
  3599. value: true
  3600. }));
  3601. exports.CanvasGraphics = void 0;
  3602. var _util = __w_pdfjs_require__(2);
  3603. var _pattern_helper = __w_pdfjs_require__(11);
  3604. const MIN_FONT_SIZE = 16;
  3605. const MAX_FONT_SIZE = 100;
  3606. const MAX_GROUP_SIZE = 4096;
  3607. const COMPILE_TYPE3_GLYPHS = true;
  3608. const MAX_SIZE_TO_COMPILE = 1000;
  3609. const FULL_CHUNK_HEIGHT = 16;
  3610. const LINEWIDTH_SCALE_FACTOR = 1.000001;
  3611. function addContextCurrentTransform(ctx) {
  3612. if (ctx.mozCurrentTransform) {
  3613. return;
  3614. }
  3615. ctx._originalSave = ctx.save;
  3616. ctx._originalRestore = ctx.restore;
  3617. ctx._originalRotate = ctx.rotate;
  3618. ctx._originalScale = ctx.scale;
  3619. ctx._originalTranslate = ctx.translate;
  3620. ctx._originalTransform = ctx.transform;
  3621. ctx._originalSetTransform = ctx.setTransform;
  3622. ctx._originalResetTransform = ctx.resetTransform;
  3623. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  3624. ctx._transformStack = [];
  3625. try {
  3626. const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth");
  3627. ctx._setLineWidth = desc.set;
  3628. ctx._getLineWidth = desc.get;
  3629. Object.defineProperty(ctx, "lineWidth", {
  3630. set: function setLineWidth(width) {
  3631. this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR);
  3632. },
  3633. get: function getLineWidth() {
  3634. return this._getLineWidth();
  3635. }
  3636. });
  3637. } catch (_) {}
  3638. Object.defineProperty(ctx, "mozCurrentTransform", {
  3639. get: function getCurrentTransform() {
  3640. return this._transformMatrix;
  3641. }
  3642. });
  3643. Object.defineProperty(ctx, "mozCurrentTransformInverse", {
  3644. get: function getCurrentTransformInverse() {
  3645. const [a, b, c, d, e, f] = this._transformMatrix;
  3646. const ad_bc = a * d - b * c;
  3647. const bc_ad = b * c - a * d;
  3648. 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];
  3649. }
  3650. });
  3651. ctx.save = function ctxSave() {
  3652. const old = this._transformMatrix;
  3653. this._transformStack.push(old);
  3654. this._transformMatrix = old.slice(0, 6);
  3655. this._originalSave();
  3656. };
  3657. ctx.restore = function ctxRestore() {
  3658. const prev = this._transformStack.pop();
  3659. if (prev) {
  3660. this._transformMatrix = prev;
  3661. this._originalRestore();
  3662. }
  3663. };
  3664. ctx.translate = function ctxTranslate(x, y) {
  3665. const m = this._transformMatrix;
  3666. m[4] = m[0] * x + m[2] * y + m[4];
  3667. m[5] = m[1] * x + m[3] * y + m[5];
  3668. this._originalTranslate(x, y);
  3669. };
  3670. ctx.scale = function ctxScale(x, y) {
  3671. const m = this._transformMatrix;
  3672. m[0] = m[0] * x;
  3673. m[1] = m[1] * x;
  3674. m[2] = m[2] * y;
  3675. m[3] = m[3] * y;
  3676. this._originalScale(x, y);
  3677. };
  3678. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3679. const m = this._transformMatrix;
  3680. 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]];
  3681. ctx._originalTransform(a, b, c, d, e, f);
  3682. };
  3683. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3684. this._transformMatrix = [a, b, c, d, e, f];
  3685. ctx._originalSetTransform(a, b, c, d, e, f);
  3686. };
  3687. ctx.resetTransform = function ctxResetTransform() {
  3688. this._transformMatrix = [1, 0, 0, 1, 0, 0];
  3689. ctx._originalResetTransform();
  3690. };
  3691. ctx.rotate = function ctxRotate(angle) {
  3692. const cosValue = Math.cos(angle);
  3693. const sinValue = Math.sin(angle);
  3694. const m = this._transformMatrix;
  3695. 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]];
  3696. this._originalRotate(angle);
  3697. };
  3698. }
  3699. class CachedCanvases {
  3700. constructor(canvasFactory) {
  3701. this.canvasFactory = canvasFactory;
  3702. this.cache = Object.create(null);
  3703. }
  3704. getCanvas(id, width, height, trackTransform) {
  3705. let canvasEntry;
  3706. if (this.cache[id] !== undefined) {
  3707. canvasEntry = this.cache[id];
  3708. this.canvasFactory.reset(canvasEntry, width, height);
  3709. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3710. } else {
  3711. canvasEntry = this.canvasFactory.create(width, height);
  3712. this.cache[id] = canvasEntry;
  3713. }
  3714. if (trackTransform) {
  3715. addContextCurrentTransform(canvasEntry.context);
  3716. }
  3717. return canvasEntry;
  3718. }
  3719. clear() {
  3720. for (const id in this.cache) {
  3721. const canvasEntry = this.cache[id];
  3722. this.canvasFactory.destroy(canvasEntry);
  3723. delete this.cache[id];
  3724. }
  3725. }
  3726. }
  3727. function compileType3Glyph(imgData) {
  3728. const POINT_TO_PROCESS_LIMIT = 1000;
  3729. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3730. const width = imgData.width,
  3731. height = imgData.height,
  3732. width1 = width + 1;
  3733. let i, ii, j, j0;
  3734. const points = new Uint8Array(width1 * (height + 1));
  3735. const lineSize = width + 7 & ~7,
  3736. data0 = imgData.data;
  3737. const data = new Uint8Array(lineSize * height);
  3738. let pos = 0;
  3739. for (i = 0, ii = data0.length; i < ii; i++) {
  3740. const elem = data0[i];
  3741. let mask = 128;
  3742. while (mask > 0) {
  3743. data[pos++] = elem & mask ? 0 : 255;
  3744. mask >>= 1;
  3745. }
  3746. }
  3747. let count = 0;
  3748. pos = 0;
  3749. if (data[pos] !== 0) {
  3750. points[0] = 1;
  3751. ++count;
  3752. }
  3753. for (j = 1; j < width; j++) {
  3754. if (data[pos] !== data[pos + 1]) {
  3755. points[j] = data[pos] ? 2 : 1;
  3756. ++count;
  3757. }
  3758. pos++;
  3759. }
  3760. if (data[pos] !== 0) {
  3761. points[j] = 2;
  3762. ++count;
  3763. }
  3764. for (i = 1; i < height; i++) {
  3765. pos = i * lineSize;
  3766. j0 = i * width1;
  3767. if (data[pos - lineSize] !== data[pos]) {
  3768. points[j0] = data[pos] ? 1 : 8;
  3769. ++count;
  3770. }
  3771. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3772. for (j = 1; j < width; j++) {
  3773. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  3774. if (POINT_TYPES[sum]) {
  3775. points[j0 + j] = POINT_TYPES[sum];
  3776. ++count;
  3777. }
  3778. pos++;
  3779. }
  3780. if (data[pos - lineSize] !== data[pos]) {
  3781. points[j0 + j] = data[pos] ? 2 : 4;
  3782. ++count;
  3783. }
  3784. if (count > POINT_TO_PROCESS_LIMIT) {
  3785. return null;
  3786. }
  3787. }
  3788. pos = lineSize * (height - 1);
  3789. j0 = i * width1;
  3790. if (data[pos] !== 0) {
  3791. points[j0] = 8;
  3792. ++count;
  3793. }
  3794. for (j = 1; j < width; j++) {
  3795. if (data[pos] !== data[pos + 1]) {
  3796. points[j0 + j] = data[pos] ? 4 : 8;
  3797. ++count;
  3798. }
  3799. pos++;
  3800. }
  3801. if (data[pos] !== 0) {
  3802. points[j0 + j] = 4;
  3803. ++count;
  3804. }
  3805. if (count > POINT_TO_PROCESS_LIMIT) {
  3806. return null;
  3807. }
  3808. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3809. const outlines = [];
  3810. for (i = 0; count && i <= height; i++) {
  3811. let p = i * width1;
  3812. const end = p + width;
  3813. while (p < end && !points[p]) {
  3814. p++;
  3815. }
  3816. if (p === end) {
  3817. continue;
  3818. }
  3819. const coords = [p % width1, i];
  3820. const p0 = p;
  3821. let type = points[p];
  3822. do {
  3823. const step = steps[type];
  3824. do {
  3825. p += step;
  3826. } while (!points[p]);
  3827. const pp = points[p];
  3828. if (pp !== 5 && pp !== 10) {
  3829. type = pp;
  3830. points[p] = 0;
  3831. } else {
  3832. type = pp & 0x33 * type >> 4;
  3833. points[p] &= type >> 2 | type << 2;
  3834. }
  3835. coords.push(p % width1, p / width1 | 0);
  3836. if (!points[p]) {
  3837. --count;
  3838. }
  3839. } while (p0 !== p);
  3840. outlines.push(coords);
  3841. --i;
  3842. }
  3843. const drawOutline = function (c) {
  3844. c.save();
  3845. c.scale(1 / width, -1 / height);
  3846. c.translate(0, -height);
  3847. c.beginPath();
  3848. for (let k = 0, kk = outlines.length; k < kk; k++) {
  3849. const o = outlines[k];
  3850. c.moveTo(o[0], o[1]);
  3851. for (let l = 2, ll = o.length; l < ll; l += 2) {
  3852. c.lineTo(o[l], o[l + 1]);
  3853. }
  3854. }
  3855. c.fill();
  3856. c.beginPath();
  3857. c.restore();
  3858. };
  3859. return drawOutline;
  3860. }
  3861. class CanvasExtraState {
  3862. constructor() {
  3863. this.alphaIsShape = false;
  3864. this.fontSize = 0;
  3865. this.fontSizeScale = 1;
  3866. this.textMatrix = _util.IDENTITY_MATRIX;
  3867. this.textMatrixScale = 1;
  3868. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  3869. this.leading = 0;
  3870. this.x = 0;
  3871. this.y = 0;
  3872. this.lineX = 0;
  3873. this.lineY = 0;
  3874. this.charSpacing = 0;
  3875. this.wordSpacing = 0;
  3876. this.textHScale = 1;
  3877. this.textRenderingMode = _util.TextRenderingMode.FILL;
  3878. this.textRise = 0;
  3879. this.fillColor = "#000000";
  3880. this.strokeColor = "#000000";
  3881. this.patternFill = false;
  3882. this.fillAlpha = 1;
  3883. this.strokeAlpha = 1;
  3884. this.lineWidth = 1;
  3885. this.activeSMask = null;
  3886. this.resumeSMaskCtx = null;
  3887. this.transferMaps = null;
  3888. }
  3889. clone() {
  3890. return Object.create(this);
  3891. }
  3892. setCurrentPoint(x, y) {
  3893. this.x = x;
  3894. this.y = y;
  3895. }
  3896. }
  3897. const CanvasGraphics = function CanvasGraphicsClosure() {
  3898. const EXECUTION_TIME = 15;
  3899. const EXECUTION_STEPS = 10;
  3900. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  3901. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  3902. ctx.putImageData(imgData, 0, 0);
  3903. return;
  3904. }
  3905. const height = imgData.height,
  3906. width = imgData.width;
  3907. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3908. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3909. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3910. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3911. let srcPos = 0,
  3912. destPos;
  3913. const src = imgData.data;
  3914. const dest = chunkImgData.data;
  3915. let i, j, thisChunkHeight, elemsInThisChunk;
  3916. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  3917. if (transferMaps) {
  3918. switch (transferMaps.length) {
  3919. case 1:
  3920. transferMapRed = transferMaps[0];
  3921. transferMapGreen = transferMaps[0];
  3922. transferMapBlue = transferMaps[0];
  3923. transferMapGray = transferMaps[0];
  3924. break;
  3925. case 4:
  3926. transferMapRed = transferMaps[0];
  3927. transferMapGreen = transferMaps[1];
  3928. transferMapBlue = transferMaps[2];
  3929. transferMapGray = transferMaps[3];
  3930. break;
  3931. }
  3932. }
  3933. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  3934. const srcLength = src.byteLength;
  3935. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  3936. const dest32DataLength = dest32.length;
  3937. const fullSrcDiff = width + 7 >> 3;
  3938. let white = 0xffffffff;
  3939. let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff;
  3940. if (transferMapGray) {
  3941. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  3942. [white, black] = [black, white];
  3943. }
  3944. }
  3945. for (i = 0; i < totalChunks; i++) {
  3946. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3947. destPos = 0;
  3948. for (j = 0; j < thisChunkHeight; j++) {
  3949. const srcDiff = srcLength - srcPos;
  3950. let k = 0;
  3951. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  3952. const kEndUnrolled = kEnd & ~7;
  3953. let mask = 0;
  3954. let srcByte = 0;
  3955. for (; k < kEndUnrolled; k += 8) {
  3956. srcByte = src[srcPos++];
  3957. dest32[destPos++] = srcByte & 128 ? white : black;
  3958. dest32[destPos++] = srcByte & 64 ? white : black;
  3959. dest32[destPos++] = srcByte & 32 ? white : black;
  3960. dest32[destPos++] = srcByte & 16 ? white : black;
  3961. dest32[destPos++] = srcByte & 8 ? white : black;
  3962. dest32[destPos++] = srcByte & 4 ? white : black;
  3963. dest32[destPos++] = srcByte & 2 ? white : black;
  3964. dest32[destPos++] = srcByte & 1 ? white : black;
  3965. }
  3966. for (; k < kEnd; k++) {
  3967. if (mask === 0) {
  3968. srcByte = src[srcPos++];
  3969. mask = 128;
  3970. }
  3971. dest32[destPos++] = srcByte & mask ? white : black;
  3972. mask >>= 1;
  3973. }
  3974. }
  3975. while (destPos < dest32DataLength) {
  3976. dest32[destPos++] = 0;
  3977. }
  3978. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3979. }
  3980. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  3981. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  3982. j = 0;
  3983. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  3984. for (i = 0; i < fullChunks; i++) {
  3985. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3986. srcPos += elemsInThisChunk;
  3987. if (hasTransferMaps) {
  3988. for (let k = 0; k < elemsInThisChunk; k += 4) {
  3989. if (transferMapRed) {
  3990. dest[k + 0] = transferMapRed[dest[k + 0]];
  3991. }
  3992. if (transferMapGreen) {
  3993. dest[k + 1] = transferMapGreen[dest[k + 1]];
  3994. }
  3995. if (transferMapBlue) {
  3996. dest[k + 2] = transferMapBlue[dest[k + 2]];
  3997. }
  3998. }
  3999. }
  4000. ctx.putImageData(chunkImgData, 0, j);
  4001. j += FULL_CHUNK_HEIGHT;
  4002. }
  4003. if (i < totalChunks) {
  4004. elemsInThisChunk = width * partialChunkHeight * 4;
  4005. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  4006. if (hasTransferMaps) {
  4007. for (let k = 0; k < elemsInThisChunk; k += 4) {
  4008. if (transferMapRed) {
  4009. dest[k + 0] = transferMapRed[dest[k + 0]];
  4010. }
  4011. if (transferMapGreen) {
  4012. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4013. }
  4014. if (transferMapBlue) {
  4015. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4016. }
  4017. }
  4018. }
  4019. ctx.putImageData(chunkImgData, 0, j);
  4020. }
  4021. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  4022. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  4023. thisChunkHeight = FULL_CHUNK_HEIGHT;
  4024. elemsInThisChunk = width * thisChunkHeight;
  4025. for (i = 0; i < totalChunks; i++) {
  4026. if (i >= fullChunks) {
  4027. thisChunkHeight = partialChunkHeight;
  4028. elemsInThisChunk = width * thisChunkHeight;
  4029. }
  4030. destPos = 0;
  4031. for (j = elemsInThisChunk; j--;) {
  4032. dest[destPos++] = src[srcPos++];
  4033. dest[destPos++] = src[srcPos++];
  4034. dest[destPos++] = src[srcPos++];
  4035. dest[destPos++] = 255;
  4036. }
  4037. if (hasTransferMaps) {
  4038. for (let k = 0; k < destPos; k += 4) {
  4039. if (transferMapRed) {
  4040. dest[k + 0] = transferMapRed[dest[k + 0]];
  4041. }
  4042. if (transferMapGreen) {
  4043. dest[k + 1] = transferMapGreen[dest[k + 1]];
  4044. }
  4045. if (transferMapBlue) {
  4046. dest[k + 2] = transferMapBlue[dest[k + 2]];
  4047. }
  4048. }
  4049. }
  4050. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4051. }
  4052. } else {
  4053. throw new Error(`bad image kind: ${imgData.kind}`);
  4054. }
  4055. }
  4056. function putBinaryImageMask(ctx, imgData) {
  4057. const height = imgData.height,
  4058. width = imgData.width;
  4059. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  4060. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  4061. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  4062. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  4063. let srcPos = 0;
  4064. const src = imgData.data;
  4065. const dest = chunkImgData.data;
  4066. for (let i = 0; i < totalChunks; i++) {
  4067. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  4068. let destPos = 3;
  4069. for (let j = 0; j < thisChunkHeight; j++) {
  4070. let elem,
  4071. mask = 0;
  4072. for (let k = 0; k < width; k++) {
  4073. if (!mask) {
  4074. elem = src[srcPos++];
  4075. mask = 128;
  4076. }
  4077. dest[destPos] = elem & mask ? 0 : 255;
  4078. destPos += 4;
  4079. mask >>= 1;
  4080. }
  4081. }
  4082. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  4083. }
  4084. }
  4085. function copyCtxState(sourceCtx, destCtx) {
  4086. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  4087. for (let i = 0, ii = properties.length; i < ii; i++) {
  4088. const property = properties[i];
  4089. if (sourceCtx[property] !== undefined) {
  4090. destCtx[property] = sourceCtx[property];
  4091. }
  4092. }
  4093. if (sourceCtx.setLineDash !== undefined) {
  4094. destCtx.setLineDash(sourceCtx.getLineDash());
  4095. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  4096. }
  4097. }
  4098. function resetCtxToDefault(ctx) {
  4099. ctx.strokeStyle = "#000000";
  4100. ctx.fillStyle = "#000000";
  4101. ctx.fillRule = "nonzero";
  4102. ctx.globalAlpha = 1;
  4103. ctx.lineWidth = 1;
  4104. ctx.lineCap = "butt";
  4105. ctx.lineJoin = "miter";
  4106. ctx.miterLimit = 10;
  4107. ctx.globalCompositeOperation = "source-over";
  4108. ctx.font = "10px sans-serif";
  4109. if (ctx.setLineDash !== undefined) {
  4110. ctx.setLineDash([]);
  4111. ctx.lineDashOffset = 0;
  4112. }
  4113. }
  4114. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  4115. const length = bytes.length;
  4116. for (let i = 3; i < length; i += 4) {
  4117. const alpha = bytes[i];
  4118. if (alpha === 0) {
  4119. bytes[i - 3] = r0;
  4120. bytes[i - 2] = g0;
  4121. bytes[i - 1] = b0;
  4122. } else if (alpha < 255) {
  4123. const alpha_ = 255 - alpha;
  4124. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  4125. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  4126. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  4127. }
  4128. }
  4129. }
  4130. function composeSMaskAlpha(maskData, layerData, transferMap) {
  4131. const length = maskData.length;
  4132. const scale = 1 / 255;
  4133. for (let i = 3; i < length; i += 4) {
  4134. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  4135. layerData[i] = layerData[i] * alpha * scale | 0;
  4136. }
  4137. }
  4138. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  4139. const length = maskData.length;
  4140. for (let i = 3; i < length; i += 4) {
  4141. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  4142. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  4143. }
  4144. }
  4145. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  4146. const hasBackdrop = !!backdrop;
  4147. const r0 = hasBackdrop ? backdrop[0] : 0;
  4148. const g0 = hasBackdrop ? backdrop[1] : 0;
  4149. const b0 = hasBackdrop ? backdrop[2] : 0;
  4150. let composeFn;
  4151. if (subtype === "Luminosity") {
  4152. composeFn = composeSMaskLuminosity;
  4153. } else {
  4154. composeFn = composeSMaskAlpha;
  4155. }
  4156. const PIXELS_TO_PROCESS = 1048576;
  4157. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  4158. for (let row = 0; row < height; row += chunkSize) {
  4159. const chunkHeight = Math.min(chunkSize, height - row);
  4160. const maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  4161. const layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  4162. if (hasBackdrop) {
  4163. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  4164. }
  4165. composeFn(maskData.data, layerData.data, transferMap);
  4166. maskCtx.putImageData(layerData, 0, row);
  4167. }
  4168. }
  4169. function composeSMask(ctx, smask, layerCtx) {
  4170. const mask = smask.canvas;
  4171. const maskCtx = smask.context;
  4172. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  4173. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, smask.backdrop, smask.transferMap);
  4174. ctx.drawImage(mask, 0, 0);
  4175. }
  4176. const LINE_CAP_STYLES = ["butt", "round", "square"];
  4177. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  4178. const NORMAL_CLIP = {};
  4179. const EO_CLIP = {};
  4180. class CanvasGraphics {
  4181. constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig) {
  4182. this.ctx = canvasCtx;
  4183. this.current = new CanvasExtraState();
  4184. this.stateStack = [];
  4185. this.pendingClip = null;
  4186. this.pendingEOFill = false;
  4187. this.res = null;
  4188. this.xobjs = null;
  4189. this.commonObjs = commonObjs;
  4190. this.objs = objs;
  4191. this.canvasFactory = canvasFactory;
  4192. this.imageLayer = imageLayer;
  4193. this.groupStack = [];
  4194. this.processingType3 = null;
  4195. this.baseTransform = null;
  4196. this.baseTransformStack = [];
  4197. this.groupLevel = 0;
  4198. this.smaskStack = [];
  4199. this.smaskCounter = 0;
  4200. this.tempSMask = null;
  4201. this.contentVisible = true;
  4202. this.markedContentStack = [];
  4203. this.optionalContentConfig = optionalContentConfig;
  4204. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  4205. if (canvasCtx) {
  4206. addContextCurrentTransform(canvasCtx);
  4207. }
  4208. this._cachedGetSinglePixelWidth = null;
  4209. }
  4210. beginDrawing({
  4211. transform,
  4212. viewport,
  4213. transparency = false,
  4214. background = null
  4215. }) {
  4216. const width = this.ctx.canvas.width;
  4217. const height = this.ctx.canvas.height;
  4218. this.ctx.save();
  4219. this.ctx.fillStyle = background || "rgb(255, 255, 255)";
  4220. this.ctx.fillRect(0, 0, width, height);
  4221. this.ctx.restore();
  4222. if (transparency) {
  4223. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
  4224. this.compositeCtx = this.ctx;
  4225. this.transparentCanvas = transparentCanvas.canvas;
  4226. this.ctx = transparentCanvas.context;
  4227. this.ctx.save();
  4228. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  4229. }
  4230. this.ctx.save();
  4231. resetCtxToDefault(this.ctx);
  4232. if (transform) {
  4233. this.ctx.transform.apply(this.ctx, transform);
  4234. }
  4235. this.ctx.transform.apply(this.ctx, viewport.transform);
  4236. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  4237. this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]);
  4238. if (this.imageLayer) {
  4239. this.imageLayer.beginLayout();
  4240. }
  4241. }
  4242. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  4243. const argsArray = operatorList.argsArray;
  4244. const fnArray = operatorList.fnArray;
  4245. let i = executionStartIdx || 0;
  4246. const argsArrayLen = argsArray.length;
  4247. if (argsArrayLen === i) {
  4248. return i;
  4249. }
  4250. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  4251. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  4252. let steps = 0;
  4253. const commonObjs = this.commonObjs;
  4254. const objs = this.objs;
  4255. let fnId;
  4256. while (true) {
  4257. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  4258. stepper.breakIt(i, continueCallback);
  4259. return i;
  4260. }
  4261. fnId = fnArray[i];
  4262. if (fnId !== _util.OPS.dependency) {
  4263. this[fnId].apply(this, argsArray[i]);
  4264. } else {
  4265. for (const depObjId of argsArray[i]) {
  4266. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  4267. if (!objsPool.has(depObjId)) {
  4268. objsPool.get(depObjId, continueCallback);
  4269. return i;
  4270. }
  4271. }
  4272. }
  4273. i++;
  4274. if (i === argsArrayLen) {
  4275. return i;
  4276. }
  4277. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  4278. if (Date.now() > endTime) {
  4279. continueCallback();
  4280. return i;
  4281. }
  4282. steps = 0;
  4283. }
  4284. }
  4285. }
  4286. endDrawing() {
  4287. while (this.stateStack.length || this.current.activeSMask !== null) {
  4288. this.restore();
  4289. }
  4290. this.ctx.restore();
  4291. if (this.transparentCanvas) {
  4292. this.ctx = this.compositeCtx;
  4293. this.ctx.save();
  4294. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  4295. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  4296. this.ctx.restore();
  4297. this.transparentCanvas = null;
  4298. }
  4299. this.cachedCanvases.clear();
  4300. if (this.imageLayer) {
  4301. this.imageLayer.endLayout();
  4302. }
  4303. }
  4304. setLineWidth(width) {
  4305. this.current.lineWidth = width;
  4306. this.ctx.lineWidth = width;
  4307. }
  4308. setLineCap(style) {
  4309. this.ctx.lineCap = LINE_CAP_STYLES[style];
  4310. }
  4311. setLineJoin(style) {
  4312. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  4313. }
  4314. setMiterLimit(limit) {
  4315. this.ctx.miterLimit = limit;
  4316. }
  4317. setDash(dashArray, dashPhase) {
  4318. const ctx = this.ctx;
  4319. if (ctx.setLineDash !== undefined) {
  4320. ctx.setLineDash(dashArray);
  4321. ctx.lineDashOffset = dashPhase;
  4322. }
  4323. }
  4324. setRenderingIntent(intent) {}
  4325. setFlatness(flatness) {}
  4326. setGState(states) {
  4327. for (let i = 0, ii = states.length; i < ii; i++) {
  4328. const state = states[i];
  4329. const key = state[0];
  4330. const value = state[1];
  4331. switch (key) {
  4332. case "LW":
  4333. this.setLineWidth(value);
  4334. break;
  4335. case "LC":
  4336. this.setLineCap(value);
  4337. break;
  4338. case "LJ":
  4339. this.setLineJoin(value);
  4340. break;
  4341. case "ML":
  4342. this.setMiterLimit(value);
  4343. break;
  4344. case "D":
  4345. this.setDash(value[0], value[1]);
  4346. break;
  4347. case "RI":
  4348. this.setRenderingIntent(value);
  4349. break;
  4350. case "FL":
  4351. this.setFlatness(value);
  4352. break;
  4353. case "Font":
  4354. this.setFont(value[0], value[1]);
  4355. break;
  4356. case "CA":
  4357. this.current.strokeAlpha = state[1];
  4358. break;
  4359. case "ca":
  4360. this.current.fillAlpha = state[1];
  4361. this.ctx.globalAlpha = state[1];
  4362. break;
  4363. case "BM":
  4364. this.ctx.globalCompositeOperation = value;
  4365. break;
  4366. case "SMask":
  4367. if (this.current.activeSMask) {
  4368. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  4369. this.suspendSMaskGroup();
  4370. } else {
  4371. this.endSMaskGroup();
  4372. }
  4373. }
  4374. this.current.activeSMask = value ? this.tempSMask : null;
  4375. if (this.current.activeSMask) {
  4376. this.beginSMaskGroup();
  4377. }
  4378. this.tempSMask = null;
  4379. break;
  4380. case "TR":
  4381. this.current.transferMaps = value;
  4382. }
  4383. }
  4384. }
  4385. beginSMaskGroup() {
  4386. const activeSMask = this.current.activeSMask;
  4387. const drawnWidth = activeSMask.canvas.width;
  4388. const drawnHeight = activeSMask.canvas.height;
  4389. const cacheId = "smaskGroupAt" + this.groupLevel;
  4390. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  4391. const currentCtx = this.ctx;
  4392. const currentTransform = currentCtx.mozCurrentTransform;
  4393. this.ctx.save();
  4394. const groupCtx = scratchCanvas.context;
  4395. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  4396. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  4397. groupCtx.transform.apply(groupCtx, currentTransform);
  4398. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  4399. copyCtxState(currentCtx, groupCtx);
  4400. this.ctx = groupCtx;
  4401. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  4402. this.groupStack.push(currentCtx);
  4403. this.groupLevel++;
  4404. }
  4405. suspendSMaskGroup() {
  4406. const groupCtx = this.ctx;
  4407. this.groupLevel--;
  4408. this.ctx = this.groupStack.pop();
  4409. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4410. this.ctx.restore();
  4411. this.ctx.save();
  4412. copyCtxState(groupCtx, this.ctx);
  4413. this.current.resumeSMaskCtx = groupCtx;
  4414. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  4415. this.ctx.transform.apply(this.ctx, deltaTransform);
  4416. groupCtx.save();
  4417. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  4418. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  4419. groupCtx.restore();
  4420. }
  4421. resumeSMaskGroup() {
  4422. const groupCtx = this.current.resumeSMaskCtx;
  4423. const currentCtx = this.ctx;
  4424. this.ctx = groupCtx;
  4425. this.groupStack.push(currentCtx);
  4426. this.groupLevel++;
  4427. }
  4428. endSMaskGroup() {
  4429. const groupCtx = this.ctx;
  4430. this.groupLevel--;
  4431. this.ctx = this.groupStack.pop();
  4432. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4433. this.ctx.restore();
  4434. copyCtxState(groupCtx, this.ctx);
  4435. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  4436. this.ctx.transform.apply(this.ctx, deltaTransform);
  4437. }
  4438. save() {
  4439. this.ctx.save();
  4440. const old = this.current;
  4441. this.stateStack.push(old);
  4442. this.current = old.clone();
  4443. this.current.resumeSMaskCtx = null;
  4444. }
  4445. restore() {
  4446. if (this.current.resumeSMaskCtx) {
  4447. this.resumeSMaskGroup();
  4448. }
  4449. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  4450. this.endSMaskGroup();
  4451. }
  4452. if (this.stateStack.length !== 0) {
  4453. this.current = this.stateStack.pop();
  4454. this.ctx.restore();
  4455. this.pendingClip = null;
  4456. this._cachedGetSinglePixelWidth = null;
  4457. } else {
  4458. this.current.activeSMask = null;
  4459. }
  4460. }
  4461. transform(a, b, c, d, e, f) {
  4462. this.ctx.transform(a, b, c, d, e, f);
  4463. this._cachedGetSinglePixelWidth = null;
  4464. }
  4465. constructPath(ops, args) {
  4466. const ctx = this.ctx;
  4467. const current = this.current;
  4468. let x = current.x,
  4469. y = current.y;
  4470. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  4471. switch (ops[i] | 0) {
  4472. case _util.OPS.rectangle:
  4473. x = args[j++];
  4474. y = args[j++];
  4475. const width = args[j++];
  4476. const height = args[j++];
  4477. const xw = x + width;
  4478. const yh = y + height;
  4479. ctx.moveTo(x, y);
  4480. if (width === 0 || height === 0) {
  4481. ctx.lineTo(xw, yh);
  4482. } else {
  4483. ctx.lineTo(xw, y);
  4484. ctx.lineTo(xw, yh);
  4485. ctx.lineTo(x, yh);
  4486. }
  4487. ctx.closePath();
  4488. break;
  4489. case _util.OPS.moveTo:
  4490. x = args[j++];
  4491. y = args[j++];
  4492. ctx.moveTo(x, y);
  4493. break;
  4494. case _util.OPS.lineTo:
  4495. x = args[j++];
  4496. y = args[j++];
  4497. ctx.lineTo(x, y);
  4498. break;
  4499. case _util.OPS.curveTo:
  4500. x = args[j + 4];
  4501. y = args[j + 5];
  4502. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  4503. j += 6;
  4504. break;
  4505. case _util.OPS.curveTo2:
  4506. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  4507. x = args[j + 2];
  4508. y = args[j + 3];
  4509. j += 4;
  4510. break;
  4511. case _util.OPS.curveTo3:
  4512. x = args[j + 2];
  4513. y = args[j + 3];
  4514. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  4515. j += 4;
  4516. break;
  4517. case _util.OPS.closePath:
  4518. ctx.closePath();
  4519. break;
  4520. }
  4521. }
  4522. current.setCurrentPoint(x, y);
  4523. }
  4524. closePath() {
  4525. this.ctx.closePath();
  4526. }
  4527. stroke(consumePath) {
  4528. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  4529. const ctx = this.ctx;
  4530. const strokeColor = this.current.strokeColor;
  4531. ctx.globalAlpha = this.current.strokeAlpha;
  4532. if (this.contentVisible) {
  4533. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  4534. const lineWidth = this.getSinglePixelWidth();
  4535. ctx.save();
  4536. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  4537. ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
  4538. ctx.stroke();
  4539. ctx.restore();
  4540. } else {
  4541. const lineWidth = this.getSinglePixelWidth();
  4542. if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) {
  4543. ctx.save();
  4544. ctx.resetTransform();
  4545. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  4546. ctx.stroke();
  4547. ctx.restore();
  4548. } else {
  4549. ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
  4550. ctx.stroke();
  4551. }
  4552. }
  4553. }
  4554. if (consumePath) {
  4555. this.consumePath();
  4556. }
  4557. ctx.globalAlpha = this.current.fillAlpha;
  4558. }
  4559. closeStroke() {
  4560. this.closePath();
  4561. this.stroke();
  4562. }
  4563. fill(consumePath) {
  4564. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  4565. const ctx = this.ctx;
  4566. const fillColor = this.current.fillColor;
  4567. const isPatternFill = this.current.patternFill;
  4568. let needRestore = false;
  4569. if (isPatternFill) {
  4570. ctx.save();
  4571. ctx.fillStyle = fillColor.getPattern(ctx, this);
  4572. needRestore = true;
  4573. }
  4574. if (this.contentVisible) {
  4575. if (this.pendingEOFill) {
  4576. ctx.fill("evenodd");
  4577. this.pendingEOFill = false;
  4578. } else {
  4579. ctx.fill();
  4580. }
  4581. }
  4582. if (needRestore) {
  4583. ctx.restore();
  4584. }
  4585. if (consumePath) {
  4586. this.consumePath();
  4587. }
  4588. }
  4589. eoFill() {
  4590. this.pendingEOFill = true;
  4591. this.fill();
  4592. }
  4593. fillStroke() {
  4594. this.fill(false);
  4595. this.stroke(false);
  4596. this.consumePath();
  4597. }
  4598. eoFillStroke() {
  4599. this.pendingEOFill = true;
  4600. this.fillStroke();
  4601. }
  4602. closeFillStroke() {
  4603. this.closePath();
  4604. this.fillStroke();
  4605. }
  4606. closeEOFillStroke() {
  4607. this.pendingEOFill = true;
  4608. this.closePath();
  4609. this.fillStroke();
  4610. }
  4611. endPath() {
  4612. this.consumePath();
  4613. }
  4614. clip() {
  4615. this.pendingClip = NORMAL_CLIP;
  4616. }
  4617. eoClip() {
  4618. this.pendingClip = EO_CLIP;
  4619. }
  4620. beginText() {
  4621. this.current.textMatrix = _util.IDENTITY_MATRIX;
  4622. this.current.textMatrixScale = 1;
  4623. this.current.x = this.current.lineX = 0;
  4624. this.current.y = this.current.lineY = 0;
  4625. }
  4626. endText() {
  4627. const paths = this.pendingTextPaths;
  4628. const ctx = this.ctx;
  4629. if (paths === undefined) {
  4630. ctx.beginPath();
  4631. return;
  4632. }
  4633. ctx.save();
  4634. ctx.beginPath();
  4635. for (let i = 0; i < paths.length; i++) {
  4636. const path = paths[i];
  4637. ctx.setTransform.apply(ctx, path.transform);
  4638. ctx.translate(path.x, path.y);
  4639. path.addToPath(ctx, path.fontSize);
  4640. }
  4641. ctx.restore();
  4642. ctx.clip();
  4643. ctx.beginPath();
  4644. delete this.pendingTextPaths;
  4645. }
  4646. setCharSpacing(spacing) {
  4647. this.current.charSpacing = spacing;
  4648. }
  4649. setWordSpacing(spacing) {
  4650. this.current.wordSpacing = spacing;
  4651. }
  4652. setHScale(scale) {
  4653. this.current.textHScale = scale / 100;
  4654. }
  4655. setLeading(leading) {
  4656. this.current.leading = -leading;
  4657. }
  4658. setFont(fontRefName, size) {
  4659. const fontObj = this.commonObjs.get(fontRefName);
  4660. const current = this.current;
  4661. if (!fontObj) {
  4662. throw new Error(`Can't find font for ${fontRefName}`);
  4663. }
  4664. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  4665. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  4666. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  4667. }
  4668. if (size < 0) {
  4669. size = -size;
  4670. current.fontDirection = -1;
  4671. } else {
  4672. current.fontDirection = 1;
  4673. }
  4674. this.current.font = fontObj;
  4675. this.current.fontSize = size;
  4676. if (fontObj.isType3Font) {
  4677. return;
  4678. }
  4679. const name = fontObj.loadedName || "sans-serif";
  4680. let bold = "normal";
  4681. if (fontObj.black) {
  4682. bold = "900";
  4683. } else if (fontObj.bold) {
  4684. bold = "bold";
  4685. }
  4686. const italic = fontObj.italic ? "italic" : "normal";
  4687. const typeface = `"${name}", ${fontObj.fallbackName}`;
  4688. let browserFontSize = size;
  4689. if (size < MIN_FONT_SIZE) {
  4690. browserFontSize = MIN_FONT_SIZE;
  4691. } else if (size > MAX_FONT_SIZE) {
  4692. browserFontSize = MAX_FONT_SIZE;
  4693. }
  4694. this.current.fontSizeScale = size / browserFontSize;
  4695. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  4696. }
  4697. setTextRenderingMode(mode) {
  4698. this.current.textRenderingMode = mode;
  4699. }
  4700. setTextRise(rise) {
  4701. this.current.textRise = rise;
  4702. }
  4703. moveText(x, y) {
  4704. this.current.x = this.current.lineX += x;
  4705. this.current.y = this.current.lineY += y;
  4706. }
  4707. setLeadingMoveText(x, y) {
  4708. this.setLeading(-y);
  4709. this.moveText(x, y);
  4710. }
  4711. setTextMatrix(a, b, c, d, e, f) {
  4712. this.current.textMatrix = [a, b, c, d, e, f];
  4713. this.current.textMatrixScale = Math.hypot(a, b);
  4714. this.current.x = this.current.lineX = 0;
  4715. this.current.y = this.current.lineY = 0;
  4716. }
  4717. nextLine() {
  4718. this.moveText(0, this.current.leading);
  4719. }
  4720. paintChar(character, x, y, patternTransform, resetLineWidthToOne) {
  4721. const ctx = this.ctx;
  4722. const current = this.current;
  4723. const font = current.font;
  4724. const textRenderingMode = current.textRenderingMode;
  4725. const fontSize = current.fontSize / current.fontSizeScale;
  4726. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  4727. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  4728. const patternFill = current.patternFill && !font.missingFile;
  4729. let addToPath;
  4730. if (font.disableFontFace || isAddToPathSet || patternFill) {
  4731. addToPath = font.getPathGenerator(this.commonObjs, character);
  4732. }
  4733. if (font.disableFontFace || patternFill) {
  4734. ctx.save();
  4735. ctx.translate(x, y);
  4736. ctx.beginPath();
  4737. addToPath(ctx, fontSize);
  4738. if (patternTransform) {
  4739. ctx.setTransform.apply(ctx, patternTransform);
  4740. }
  4741. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4742. ctx.fill();
  4743. }
  4744. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4745. if (resetLineWidthToOne) {
  4746. ctx.resetTransform();
  4747. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  4748. }
  4749. ctx.stroke();
  4750. }
  4751. ctx.restore();
  4752. } else {
  4753. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4754. ctx.fillText(character, x, y);
  4755. }
  4756. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4757. if (resetLineWidthToOne) {
  4758. ctx.save();
  4759. ctx.moveTo(x, y);
  4760. ctx.resetTransform();
  4761. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  4762. ctx.strokeText(character, 0, 0);
  4763. ctx.restore();
  4764. } else {
  4765. ctx.strokeText(character, x, y);
  4766. }
  4767. }
  4768. }
  4769. if (isAddToPathSet) {
  4770. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4771. paths.push({
  4772. transform: ctx.mozCurrentTransform,
  4773. x,
  4774. y,
  4775. fontSize,
  4776. addToPath
  4777. });
  4778. }
  4779. }
  4780. get isFontSubpixelAAEnabled() {
  4781. const {
  4782. context: ctx
  4783. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  4784. ctx.scale(1.5, 1);
  4785. ctx.fillText("I", 0, 10);
  4786. const data = ctx.getImageData(0, 0, 10, 10).data;
  4787. let enabled = false;
  4788. for (let i = 3; i < data.length; i += 4) {
  4789. if (data[i] > 0 && data[i] < 255) {
  4790. enabled = true;
  4791. break;
  4792. }
  4793. }
  4794. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  4795. }
  4796. showText(glyphs) {
  4797. const current = this.current;
  4798. const font = current.font;
  4799. if (font.isType3Font) {
  4800. return this.showType3Text(glyphs);
  4801. }
  4802. const fontSize = current.fontSize;
  4803. if (fontSize === 0) {
  4804. return undefined;
  4805. }
  4806. const ctx = this.ctx;
  4807. const fontSizeScale = current.fontSizeScale;
  4808. const charSpacing = current.charSpacing;
  4809. const wordSpacing = current.wordSpacing;
  4810. const fontDirection = current.fontDirection;
  4811. const textHScale = current.textHScale * fontDirection;
  4812. const glyphsLength = glyphs.length;
  4813. const vertical = font.vertical;
  4814. const spacingDir = vertical ? 1 : -1;
  4815. const defaultVMetrics = font.defaultVMetrics;
  4816. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  4817. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  4818. ctx.save();
  4819. let patternTransform;
  4820. if (current.patternFill) {
  4821. ctx.save();
  4822. const pattern = current.fillColor.getPattern(ctx, this);
  4823. patternTransform = ctx.mozCurrentTransform;
  4824. ctx.restore();
  4825. ctx.fillStyle = pattern;
  4826. }
  4827. ctx.transform.apply(ctx, current.textMatrix);
  4828. ctx.translate(current.x, current.y + current.textRise);
  4829. if (fontDirection > 0) {
  4830. ctx.scale(textHScale, -1);
  4831. } else {
  4832. ctx.scale(textHScale, 1);
  4833. }
  4834. let lineWidth = current.lineWidth;
  4835. let resetLineWidthToOne = false;
  4836. const scale = current.textMatrixScale;
  4837. if (scale === 0 || lineWidth === 0) {
  4838. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  4839. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  4840. this._cachedGetSinglePixelWidth = null;
  4841. lineWidth = this.getSinglePixelWidth();
  4842. resetLineWidthToOne = lineWidth < 0;
  4843. }
  4844. } else {
  4845. lineWidth /= scale;
  4846. }
  4847. if (fontSizeScale !== 1.0) {
  4848. ctx.scale(fontSizeScale, fontSizeScale);
  4849. lineWidth /= fontSizeScale;
  4850. }
  4851. ctx.lineWidth = lineWidth;
  4852. let x = 0,
  4853. i;
  4854. for (i = 0; i < glyphsLength; ++i) {
  4855. const glyph = glyphs[i];
  4856. if ((0, _util.isNum)(glyph)) {
  4857. x += spacingDir * glyph * fontSize / 1000;
  4858. continue;
  4859. }
  4860. let restoreNeeded = false;
  4861. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  4862. const character = glyph.fontChar;
  4863. const accent = glyph.accent;
  4864. let scaledX, scaledY;
  4865. let width = glyph.width;
  4866. if (vertical) {
  4867. const vmetric = glyph.vmetric || defaultVMetrics;
  4868. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  4869. const vy = vmetric[2] * widthAdvanceScale;
  4870. width = vmetric ? -vmetric[0] : width;
  4871. scaledX = vx / fontSizeScale;
  4872. scaledY = (x + vy) / fontSizeScale;
  4873. } else {
  4874. scaledX = x / fontSizeScale;
  4875. scaledY = 0;
  4876. }
  4877. if (font.remeasure && width > 0) {
  4878. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  4879. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  4880. const characterScaleX = width / measuredWidth;
  4881. restoreNeeded = true;
  4882. ctx.save();
  4883. ctx.scale(characterScaleX, 1);
  4884. scaledX /= characterScaleX;
  4885. } else if (width !== measuredWidth) {
  4886. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  4887. }
  4888. }
  4889. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  4890. if (simpleFillText && !accent) {
  4891. ctx.fillText(character, scaledX, scaledY);
  4892. } else {
  4893. this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne);
  4894. if (accent) {
  4895. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  4896. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  4897. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne);
  4898. }
  4899. }
  4900. }
  4901. let charWidth;
  4902. if (vertical) {
  4903. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  4904. } else {
  4905. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  4906. }
  4907. x += charWidth;
  4908. if (restoreNeeded) {
  4909. ctx.restore();
  4910. }
  4911. }
  4912. if (vertical) {
  4913. current.y -= x;
  4914. } else {
  4915. current.x += x * textHScale;
  4916. }
  4917. ctx.restore();
  4918. return undefined;
  4919. }
  4920. showType3Text(glyphs) {
  4921. const ctx = this.ctx;
  4922. const current = this.current;
  4923. const font = current.font;
  4924. const fontSize = current.fontSize;
  4925. const fontDirection = current.fontDirection;
  4926. const spacingDir = font.vertical ? 1 : -1;
  4927. const charSpacing = current.charSpacing;
  4928. const wordSpacing = current.wordSpacing;
  4929. const textHScale = current.textHScale * fontDirection;
  4930. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  4931. const glyphsLength = glyphs.length;
  4932. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  4933. let i, glyph, width, spacingLength;
  4934. if (isTextInvisible || fontSize === 0) {
  4935. return;
  4936. }
  4937. this._cachedGetSinglePixelWidth = null;
  4938. ctx.save();
  4939. ctx.transform.apply(ctx, current.textMatrix);
  4940. ctx.translate(current.x, current.y);
  4941. ctx.scale(textHScale, fontDirection);
  4942. for (i = 0; i < glyphsLength; ++i) {
  4943. glyph = glyphs[i];
  4944. if ((0, _util.isNum)(glyph)) {
  4945. spacingLength = spacingDir * glyph * fontSize / 1000;
  4946. this.ctx.translate(spacingLength, 0);
  4947. current.x += spacingLength * textHScale;
  4948. continue;
  4949. }
  4950. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  4951. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  4952. if (!operatorList) {
  4953. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  4954. continue;
  4955. }
  4956. if (this.contentVisible) {
  4957. this.processingType3 = glyph;
  4958. this.save();
  4959. ctx.scale(fontSize, fontSize);
  4960. ctx.transform.apply(ctx, fontMatrix);
  4961. this.executeOperatorList(operatorList);
  4962. this.restore();
  4963. }
  4964. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  4965. width = transformed[0] * fontSize + spacing;
  4966. ctx.translate(width, 0);
  4967. current.x += width * textHScale;
  4968. }
  4969. ctx.restore();
  4970. this.processingType3 = null;
  4971. }
  4972. setCharWidth(xWidth, yWidth) {}
  4973. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  4974. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4975. this.clip();
  4976. this.endPath();
  4977. }
  4978. getColorN_Pattern(IR) {
  4979. let pattern;
  4980. if (IR[0] === "TilingPattern") {
  4981. const color = IR[1];
  4982. const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  4983. const canvasGraphicsFactory = {
  4984. createCanvasGraphics: ctx => {
  4985. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
  4986. }
  4987. };
  4988. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  4989. } else {
  4990. pattern = (0, _pattern_helper.getShadingPattern)(IR);
  4991. }
  4992. return pattern;
  4993. }
  4994. setStrokeColorN() {
  4995. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4996. }
  4997. setFillColorN() {
  4998. this.current.fillColor = this.getColorN_Pattern(arguments);
  4999. this.current.patternFill = true;
  5000. }
  5001. setStrokeRGBColor(r, g, b) {
  5002. const color = _util.Util.makeHexColor(r, g, b);
  5003. this.ctx.strokeStyle = color;
  5004. this.current.strokeColor = color;
  5005. }
  5006. setFillRGBColor(r, g, b) {
  5007. const color = _util.Util.makeHexColor(r, g, b);
  5008. this.ctx.fillStyle = color;
  5009. this.current.fillColor = color;
  5010. this.current.patternFill = false;
  5011. }
  5012. shadingFill(patternIR) {
  5013. if (!this.contentVisible) {
  5014. return;
  5015. }
  5016. const ctx = this.ctx;
  5017. this.save();
  5018. const pattern = (0, _pattern_helper.getShadingPattern)(patternIR);
  5019. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  5020. const inv = ctx.mozCurrentTransformInverse;
  5021. if (inv) {
  5022. const canvas = ctx.canvas;
  5023. const width = canvas.width;
  5024. const height = canvas.height;
  5025. const bl = _util.Util.applyTransform([0, 0], inv);
  5026. const br = _util.Util.applyTransform([0, height], inv);
  5027. const ul = _util.Util.applyTransform([width, 0], inv);
  5028. const ur = _util.Util.applyTransform([width, height], inv);
  5029. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  5030. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  5031. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  5032. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  5033. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  5034. } else {
  5035. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  5036. }
  5037. this.restore();
  5038. }
  5039. beginInlineImage() {
  5040. (0, _util.unreachable)("Should not call beginInlineImage");
  5041. }
  5042. beginImageData() {
  5043. (0, _util.unreachable)("Should not call beginImageData");
  5044. }
  5045. paintFormXObjectBegin(matrix, bbox) {
  5046. if (!this.contentVisible) {
  5047. return;
  5048. }
  5049. this.save();
  5050. this.baseTransformStack.push(this.baseTransform);
  5051. if (Array.isArray(matrix) && matrix.length === 6) {
  5052. this.transform.apply(this, matrix);
  5053. }
  5054. this.baseTransform = this.ctx.mozCurrentTransform;
  5055. if (bbox) {
  5056. const width = bbox[2] - bbox[0];
  5057. const height = bbox[3] - bbox[1];
  5058. this.ctx.rect(bbox[0], bbox[1], width, height);
  5059. this.clip();
  5060. this.endPath();
  5061. }
  5062. }
  5063. paintFormXObjectEnd() {
  5064. if (!this.contentVisible) {
  5065. return;
  5066. }
  5067. this.restore();
  5068. this.baseTransform = this.baseTransformStack.pop();
  5069. }
  5070. beginGroup(group) {
  5071. if (!this.contentVisible) {
  5072. return;
  5073. }
  5074. this.save();
  5075. const currentCtx = this.ctx;
  5076. if (!group.isolated) {
  5077. (0, _util.info)("TODO: Support non-isolated groups.");
  5078. }
  5079. if (group.knockout) {
  5080. (0, _util.warn)("Knockout groups not supported.");
  5081. }
  5082. const currentTransform = currentCtx.mozCurrentTransform;
  5083. if (group.matrix) {
  5084. currentCtx.transform.apply(currentCtx, group.matrix);
  5085. }
  5086. if (!group.bbox) {
  5087. throw new Error("Bounding box is required.");
  5088. }
  5089. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  5090. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  5091. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  5092. const offsetX = Math.floor(bounds[0]);
  5093. const offsetY = Math.floor(bounds[1]);
  5094. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  5095. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  5096. let scaleX = 1,
  5097. scaleY = 1;
  5098. if (drawnWidth > MAX_GROUP_SIZE) {
  5099. scaleX = drawnWidth / MAX_GROUP_SIZE;
  5100. drawnWidth = MAX_GROUP_SIZE;
  5101. }
  5102. if (drawnHeight > MAX_GROUP_SIZE) {
  5103. scaleY = drawnHeight / MAX_GROUP_SIZE;
  5104. drawnHeight = MAX_GROUP_SIZE;
  5105. }
  5106. let cacheId = "groupAt" + this.groupLevel;
  5107. if (group.smask) {
  5108. cacheId += "_smask_" + this.smaskCounter++ % 2;
  5109. }
  5110. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  5111. const groupCtx = scratchCanvas.context;
  5112. groupCtx.scale(1 / scaleX, 1 / scaleY);
  5113. groupCtx.translate(-offsetX, -offsetY);
  5114. groupCtx.transform.apply(groupCtx, currentTransform);
  5115. if (group.smask) {
  5116. this.smaskStack.push({
  5117. canvas: scratchCanvas.canvas,
  5118. context: groupCtx,
  5119. offsetX,
  5120. offsetY,
  5121. scaleX,
  5122. scaleY,
  5123. subtype: group.smask.subtype,
  5124. backdrop: group.smask.backdrop,
  5125. transferMap: group.smask.transferMap || null,
  5126. startTransformInverse: null
  5127. });
  5128. } else {
  5129. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  5130. currentCtx.translate(offsetX, offsetY);
  5131. currentCtx.scale(scaleX, scaleY);
  5132. }
  5133. copyCtxState(currentCtx, groupCtx);
  5134. this.ctx = groupCtx;
  5135. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  5136. this.groupStack.push(currentCtx);
  5137. this.groupLevel++;
  5138. this.current.activeSMask = null;
  5139. }
  5140. endGroup(group) {
  5141. if (!this.contentVisible) {
  5142. return;
  5143. }
  5144. this.groupLevel--;
  5145. const groupCtx = this.ctx;
  5146. this.ctx = this.groupStack.pop();
  5147. if (this.ctx.imageSmoothingEnabled !== undefined) {
  5148. this.ctx.imageSmoothingEnabled = false;
  5149. } else {
  5150. this.ctx.mozImageSmoothingEnabled = false;
  5151. }
  5152. if (group.smask) {
  5153. this.tempSMask = this.smaskStack.pop();
  5154. } else {
  5155. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  5156. }
  5157. this.restore();
  5158. }
  5159. beginAnnotations() {
  5160. this.save();
  5161. if (this.baseTransform) {
  5162. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  5163. }
  5164. }
  5165. endAnnotations() {
  5166. this.restore();
  5167. }
  5168. beginAnnotation(rect, transform, matrix) {
  5169. this.save();
  5170. resetCtxToDefault(this.ctx);
  5171. this.current = new CanvasExtraState();
  5172. if (Array.isArray(rect) && rect.length === 4) {
  5173. const width = rect[2] - rect[0];
  5174. const height = rect[3] - rect[1];
  5175. this.ctx.rect(rect[0], rect[1], width, height);
  5176. this.clip();
  5177. this.endPath();
  5178. }
  5179. this.transform.apply(this, transform);
  5180. this.transform.apply(this, matrix);
  5181. }
  5182. endAnnotation() {
  5183. this.restore();
  5184. }
  5185. paintImageMaskXObject(img) {
  5186. if (!this.contentVisible) {
  5187. return;
  5188. }
  5189. const ctx = this.ctx;
  5190. const width = img.width,
  5191. height = img.height;
  5192. const fillColor = this.current.fillColor;
  5193. const isPatternFill = this.current.patternFill;
  5194. const glyph = this.processingType3;
  5195. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  5196. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  5197. glyph.compiled = compileType3Glyph({
  5198. data: img.data,
  5199. width,
  5200. height
  5201. });
  5202. } else {
  5203. glyph.compiled = null;
  5204. }
  5205. }
  5206. if (glyph?.compiled) {
  5207. glyph.compiled(ctx);
  5208. return;
  5209. }
  5210. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5211. const maskCtx = maskCanvas.context;
  5212. maskCtx.save();
  5213. putBinaryImageMask(maskCtx, img);
  5214. maskCtx.globalCompositeOperation = "source-in";
  5215. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  5216. maskCtx.fillRect(0, 0, width, height);
  5217. maskCtx.restore();
  5218. this.paintInlineImageXObject(maskCanvas.canvas);
  5219. }
  5220. paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  5221. if (!this.contentVisible) {
  5222. return;
  5223. }
  5224. const width = imgData.width;
  5225. const height = imgData.height;
  5226. const fillColor = this.current.fillColor;
  5227. const isPatternFill = this.current.patternFill;
  5228. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5229. const maskCtx = maskCanvas.context;
  5230. maskCtx.save();
  5231. putBinaryImageMask(maskCtx, imgData);
  5232. maskCtx.globalCompositeOperation = "source-in";
  5233. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  5234. maskCtx.fillRect(0, 0, width, height);
  5235. maskCtx.restore();
  5236. const ctx = this.ctx;
  5237. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  5238. ctx.save();
  5239. ctx.transform(scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]);
  5240. ctx.scale(1, -1);
  5241. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  5242. ctx.restore();
  5243. }
  5244. }
  5245. paintImageMaskXObjectGroup(images) {
  5246. if (!this.contentVisible) {
  5247. return;
  5248. }
  5249. const ctx = this.ctx;
  5250. const fillColor = this.current.fillColor;
  5251. const isPatternFill = this.current.patternFill;
  5252. for (let i = 0, ii = images.length; i < ii; i++) {
  5253. const image = images[i];
  5254. const width = image.width,
  5255. height = image.height;
  5256. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5257. const maskCtx = maskCanvas.context;
  5258. maskCtx.save();
  5259. putBinaryImageMask(maskCtx, image);
  5260. maskCtx.globalCompositeOperation = "source-in";
  5261. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  5262. maskCtx.fillRect(0, 0, width, height);
  5263. maskCtx.restore();
  5264. ctx.save();
  5265. ctx.transform.apply(ctx, image.transform);
  5266. ctx.scale(1, -1);
  5267. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  5268. ctx.restore();
  5269. }
  5270. }
  5271. paintImageXObject(objId) {
  5272. if (!this.contentVisible) {
  5273. return;
  5274. }
  5275. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  5276. if (!imgData) {
  5277. (0, _util.warn)("Dependent image isn't ready yet");
  5278. return;
  5279. }
  5280. this.paintInlineImageXObject(imgData);
  5281. }
  5282. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  5283. if (!this.contentVisible) {
  5284. return;
  5285. }
  5286. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  5287. if (!imgData) {
  5288. (0, _util.warn)("Dependent image isn't ready yet");
  5289. return;
  5290. }
  5291. const width = imgData.width;
  5292. const height = imgData.height;
  5293. const map = [];
  5294. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  5295. map.push({
  5296. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  5297. x: 0,
  5298. y: 0,
  5299. w: width,
  5300. h: height
  5301. });
  5302. }
  5303. this.paintInlineImageXObjectGroup(imgData, map);
  5304. }
  5305. paintInlineImageXObject(imgData) {
  5306. if (!this.contentVisible) {
  5307. return;
  5308. }
  5309. const width = imgData.width;
  5310. const height = imgData.height;
  5311. const ctx = this.ctx;
  5312. this.save();
  5313. ctx.scale(1 / width, -1 / height);
  5314. const currentTransform = ctx.mozCurrentTransformInverse;
  5315. let widthScale = Math.max(Math.hypot(currentTransform[0], currentTransform[1]), 1);
  5316. let heightScale = Math.max(Math.hypot(currentTransform[2], currentTransform[3]), 1);
  5317. let imgToPaint, tmpCanvas, tmpCtx;
  5318. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  5319. imgToPaint = imgData;
  5320. } else {
  5321. tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  5322. tmpCtx = tmpCanvas.context;
  5323. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  5324. imgToPaint = tmpCanvas.canvas;
  5325. }
  5326. let paintWidth = width,
  5327. paintHeight = height;
  5328. let tmpCanvasId = "prescale1";
  5329. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  5330. let newWidth = paintWidth,
  5331. newHeight = paintHeight;
  5332. if (widthScale > 2 && paintWidth > 1) {
  5333. newWidth = Math.ceil(paintWidth / 2);
  5334. widthScale /= paintWidth / newWidth;
  5335. }
  5336. if (heightScale > 2 && paintHeight > 1) {
  5337. newHeight = Math.ceil(paintHeight / 2);
  5338. heightScale /= paintHeight / newHeight;
  5339. }
  5340. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  5341. tmpCtx = tmpCanvas.context;
  5342. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5343. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  5344. imgToPaint = tmpCanvas.canvas;
  5345. paintWidth = newWidth;
  5346. paintHeight = newHeight;
  5347. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  5348. }
  5349. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  5350. if (this.imageLayer) {
  5351. const position = this.getCanvasPosition(0, -height);
  5352. this.imageLayer.appendImage({
  5353. imgData,
  5354. left: position[0],
  5355. top: position[1],
  5356. width: width / currentTransform[0],
  5357. height: height / currentTransform[3]
  5358. });
  5359. }
  5360. this.restore();
  5361. }
  5362. paintInlineImageXObjectGroup(imgData, map) {
  5363. if (!this.contentVisible) {
  5364. return;
  5365. }
  5366. const ctx = this.ctx;
  5367. const w = imgData.width;
  5368. const h = imgData.height;
  5369. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  5370. const tmpCtx = tmpCanvas.context;
  5371. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  5372. for (let i = 0, ii = map.length; i < ii; i++) {
  5373. const entry = map[i];
  5374. ctx.save();
  5375. ctx.transform.apply(ctx, entry.transform);
  5376. ctx.scale(1, -1);
  5377. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  5378. if (this.imageLayer) {
  5379. const position = this.getCanvasPosition(entry.x, entry.y);
  5380. this.imageLayer.appendImage({
  5381. imgData,
  5382. left: position[0],
  5383. top: position[1],
  5384. width: w,
  5385. height: h
  5386. });
  5387. }
  5388. ctx.restore();
  5389. }
  5390. }
  5391. paintSolidColorImageMask() {
  5392. if (!this.contentVisible) {
  5393. return;
  5394. }
  5395. this.ctx.fillRect(0, 0, 1, 1);
  5396. }
  5397. markPoint(tag) {}
  5398. markPointProps(tag, properties) {}
  5399. beginMarkedContent(tag) {
  5400. this.markedContentStack.push({
  5401. visible: true
  5402. });
  5403. }
  5404. beginMarkedContentProps(tag, properties) {
  5405. if (tag === "OC") {
  5406. this.markedContentStack.push({
  5407. visible: this.optionalContentConfig.isVisible(properties)
  5408. });
  5409. } else {
  5410. this.markedContentStack.push({
  5411. visible: true
  5412. });
  5413. }
  5414. this.contentVisible = this.isContentVisible();
  5415. }
  5416. endMarkedContent() {
  5417. this.markedContentStack.pop();
  5418. this.contentVisible = this.isContentVisible();
  5419. }
  5420. beginCompat() {}
  5421. endCompat() {}
  5422. consumePath() {
  5423. const ctx = this.ctx;
  5424. if (this.pendingClip) {
  5425. if (this.pendingClip === EO_CLIP) {
  5426. ctx.clip("evenodd");
  5427. } else {
  5428. ctx.clip();
  5429. }
  5430. this.pendingClip = null;
  5431. }
  5432. ctx.beginPath();
  5433. }
  5434. getSinglePixelWidth() {
  5435. if (this._cachedGetSinglePixelWidth === null) {
  5436. const m = this.ctx.mozCurrentTransform;
  5437. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  5438. const sqNorm1 = m[0] ** 2 + m[2] ** 2;
  5439. const sqNorm2 = m[1] ** 2 + m[3] ** 2;
  5440. const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet;
  5441. if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) {
  5442. this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight);
  5443. } else if (absDet > Number.EPSILON) {
  5444. this._cachedGetSinglePixelWidth = pixelHeight;
  5445. } else {
  5446. this._cachedGetSinglePixelWidth = 1;
  5447. }
  5448. }
  5449. return this._cachedGetSinglePixelWidth;
  5450. }
  5451. getCanvasPosition(x, y) {
  5452. const transform = this.ctx.mozCurrentTransform;
  5453. return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
  5454. }
  5455. isContentVisible() {
  5456. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  5457. if (!this.markedContentStack[i].visible) {
  5458. return false;
  5459. }
  5460. }
  5461. return true;
  5462. }
  5463. }
  5464. for (const op in _util.OPS) {
  5465. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  5466. }
  5467. return CanvasGraphics;
  5468. }();
  5469. exports.CanvasGraphics = CanvasGraphics;
  5470. /***/ }),
  5471. /* 11 */
  5472. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5473. Object.defineProperty(exports, "__esModule", ({
  5474. value: true
  5475. }));
  5476. exports.getShadingPattern = getShadingPattern;
  5477. exports.TilingPattern = void 0;
  5478. var _util = __w_pdfjs_require__(2);
  5479. let svgElement;
  5480. function createMatrix(matrix) {
  5481. if (typeof DOMMatrix !== "undefined") {
  5482. return new DOMMatrix(matrix);
  5483. }
  5484. if (!svgElement) {
  5485. svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  5486. }
  5487. return svgElement.createSVGMatrix(matrix);
  5488. }
  5489. function applyBoundingBox(ctx, bbox) {
  5490. if (!bbox || typeof Path2D === "undefined") {
  5491. return;
  5492. }
  5493. const width = bbox[2] - bbox[0];
  5494. const height = bbox[3] - bbox[1];
  5495. const region = new Path2D();
  5496. region.rect(bbox[0], bbox[1], width, height);
  5497. ctx.clip(region);
  5498. }
  5499. class BaseShadingPattern {
  5500. constructor() {
  5501. if (this.constructor === BaseShadingPattern) {
  5502. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  5503. }
  5504. }
  5505. getPattern() {
  5506. (0, _util.unreachable)("Abstract method `getPattern` called.");
  5507. }
  5508. }
  5509. class RadialAxialShadingPattern extends BaseShadingPattern {
  5510. constructor(IR) {
  5511. super();
  5512. this._type = IR[1];
  5513. this._bbox = IR[2];
  5514. this._colorStops = IR[3];
  5515. this._p0 = IR[4];
  5516. this._p1 = IR[5];
  5517. this._r0 = IR[6];
  5518. this._r1 = IR[7];
  5519. this._matrix = IR[8];
  5520. }
  5521. getPattern(ctx, owner, shadingFill) {
  5522. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", ctx.canvas.width, ctx.canvas.height, true);
  5523. const tmpCtx = tmpCanvas.context;
  5524. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5525. tmpCtx.beginPath();
  5526. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5527. if (!shadingFill) {
  5528. tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
  5529. if (this._matrix) {
  5530. tmpCtx.transform.apply(tmpCtx, this._matrix);
  5531. }
  5532. } else {
  5533. tmpCtx.setTransform.apply(tmpCtx, ctx.mozCurrentTransform);
  5534. }
  5535. applyBoundingBox(tmpCtx, this._bbox);
  5536. let grad;
  5537. if (this._type === "axial") {
  5538. grad = tmpCtx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  5539. } else if (this._type === "radial") {
  5540. grad = tmpCtx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  5541. }
  5542. for (const colorStop of this._colorStops) {
  5543. grad.addColorStop(colorStop[0], colorStop[1]);
  5544. }
  5545. tmpCtx.fillStyle = grad;
  5546. tmpCtx.fill();
  5547. const pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
  5548. pattern.setTransform(createMatrix(ctx.mozCurrentTransformInverse));
  5549. return pattern;
  5550. }
  5551. }
  5552. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5553. const coords = context.coords,
  5554. colors = context.colors;
  5555. const bytes = data.data,
  5556. rowSize = data.width * 4;
  5557. let tmp;
  5558. if (coords[p1 + 1] > coords[p2 + 1]) {
  5559. tmp = p1;
  5560. p1 = p2;
  5561. p2 = tmp;
  5562. tmp = c1;
  5563. c1 = c2;
  5564. c2 = tmp;
  5565. }
  5566. if (coords[p2 + 1] > coords[p3 + 1]) {
  5567. tmp = p2;
  5568. p2 = p3;
  5569. p3 = tmp;
  5570. tmp = c2;
  5571. c2 = c3;
  5572. c3 = tmp;
  5573. }
  5574. if (coords[p1 + 1] > coords[p2 + 1]) {
  5575. tmp = p1;
  5576. p1 = p2;
  5577. p2 = tmp;
  5578. tmp = c1;
  5579. c1 = c2;
  5580. c2 = tmp;
  5581. }
  5582. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5583. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5584. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5585. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5586. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5587. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5588. if (y1 >= y3) {
  5589. return;
  5590. }
  5591. const c1r = colors[c1],
  5592. c1g = colors[c1 + 1],
  5593. c1b = colors[c1 + 2];
  5594. const c2r = colors[c2],
  5595. c2g = colors[c2 + 1],
  5596. c2b = colors[c2 + 2];
  5597. const c3r = colors[c3],
  5598. c3g = colors[c3 + 1],
  5599. c3b = colors[c3 + 2];
  5600. const minY = Math.round(y1),
  5601. maxY = Math.round(y3);
  5602. let xa, car, cag, cab;
  5603. let xb, cbr, cbg, cbb;
  5604. for (let y = minY; y <= maxY; y++) {
  5605. if (y < y2) {
  5606. let k;
  5607. if (y < y1) {
  5608. k = 0;
  5609. } else if (y1 === y2) {
  5610. k = 1;
  5611. } else {
  5612. k = (y1 - y) / (y1 - y2);
  5613. }
  5614. xa = x1 - (x1 - x2) * k;
  5615. car = c1r - (c1r - c2r) * k;
  5616. cag = c1g - (c1g - c2g) * k;
  5617. cab = c1b - (c1b - c2b) * k;
  5618. } else {
  5619. let k;
  5620. if (y > y3) {
  5621. k = 1;
  5622. } else if (y2 === y3) {
  5623. k = 0;
  5624. } else {
  5625. k = (y2 - y) / (y2 - y3);
  5626. }
  5627. xa = x2 - (x2 - x3) * k;
  5628. car = c2r - (c2r - c3r) * k;
  5629. cag = c2g - (c2g - c3g) * k;
  5630. cab = c2b - (c2b - c3b) * k;
  5631. }
  5632. let k;
  5633. if (y < y1) {
  5634. k = 0;
  5635. } else if (y > y3) {
  5636. k = 1;
  5637. } else {
  5638. k = (y1 - y) / (y1 - y3);
  5639. }
  5640. xb = x1 - (x1 - x3) * k;
  5641. cbr = c1r - (c1r - c3r) * k;
  5642. cbg = c1g - (c1g - c3g) * k;
  5643. cbb = c1b - (c1b - c3b) * k;
  5644. const x1_ = Math.round(Math.min(xa, xb));
  5645. const x2_ = Math.round(Math.max(xa, xb));
  5646. let j = rowSize * y + x1_ * 4;
  5647. for (let x = x1_; x <= x2_; x++) {
  5648. k = (xa - x) / (xa - xb);
  5649. if (k < 0) {
  5650. k = 0;
  5651. } else if (k > 1) {
  5652. k = 1;
  5653. }
  5654. bytes[j++] = car - (car - cbr) * k | 0;
  5655. bytes[j++] = cag - (cag - cbg) * k | 0;
  5656. bytes[j++] = cab - (cab - cbb) * k | 0;
  5657. bytes[j++] = 255;
  5658. }
  5659. }
  5660. }
  5661. function drawFigure(data, figure, context) {
  5662. const ps = figure.coords;
  5663. const cs = figure.colors;
  5664. let i, ii;
  5665. switch (figure.type) {
  5666. case "lattice":
  5667. const verticesPerRow = figure.verticesPerRow;
  5668. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  5669. const cols = verticesPerRow - 1;
  5670. for (i = 0; i < rows; i++) {
  5671. let q = i * verticesPerRow;
  5672. for (let j = 0; j < cols; j++, q++) {
  5673. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5674. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5675. }
  5676. }
  5677. break;
  5678. case "triangles":
  5679. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5680. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  5681. }
  5682. break;
  5683. default:
  5684. throw new Error("illegal figure");
  5685. }
  5686. }
  5687. class MeshShadingPattern extends BaseShadingPattern {
  5688. constructor(IR) {
  5689. super();
  5690. this._coords = IR[2];
  5691. this._colors = IR[3];
  5692. this._figures = IR[4];
  5693. this._bounds = IR[5];
  5694. this._matrix = IR[6];
  5695. this._bbox = IR[7];
  5696. this._background = IR[8];
  5697. }
  5698. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  5699. const EXPECTED_SCALE = 1.1;
  5700. const MAX_PATTERN_SIZE = 3000;
  5701. const BORDER_SIZE = 2;
  5702. const offsetX = Math.floor(this._bounds[0]);
  5703. const offsetY = Math.floor(this._bounds[1]);
  5704. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  5705. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  5706. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5707. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5708. const scaleX = boundsWidth / width;
  5709. const scaleY = boundsHeight / height;
  5710. const context = {
  5711. coords: this._coords,
  5712. colors: this._colors,
  5713. offsetX: -offsetX,
  5714. offsetY: -offsetY,
  5715. scaleX: 1 / scaleX,
  5716. scaleY: 1 / scaleY
  5717. };
  5718. const paddedWidth = width + BORDER_SIZE * 2;
  5719. const paddedHeight = height + BORDER_SIZE * 2;
  5720. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  5721. const tmpCtx = tmpCanvas.context;
  5722. const data = tmpCtx.createImageData(width, height);
  5723. if (backgroundColor) {
  5724. const bytes = data.data;
  5725. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  5726. bytes[i] = backgroundColor[0];
  5727. bytes[i + 1] = backgroundColor[1];
  5728. bytes[i + 2] = backgroundColor[2];
  5729. bytes[i + 3] = 255;
  5730. }
  5731. }
  5732. for (const figure of this._figures) {
  5733. drawFigure(data, figure, context);
  5734. }
  5735. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5736. const canvas = tmpCanvas.canvas;
  5737. return {
  5738. canvas,
  5739. offsetX: offsetX - BORDER_SIZE * scaleX,
  5740. offsetY: offsetY - BORDER_SIZE * scaleY,
  5741. scaleX,
  5742. scaleY
  5743. };
  5744. }
  5745. getPattern(ctx, owner, shadingFill) {
  5746. applyBoundingBox(ctx, this._bbox);
  5747. let scale;
  5748. if (shadingFill) {
  5749. scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5750. } else {
  5751. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  5752. if (this._matrix) {
  5753. const matrixScale = _util.Util.singularValueDecompose2dScale(this._matrix);
  5754. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  5755. }
  5756. }
  5757. const temporaryPatternCanvas = this._createMeshCanvas(scale, shadingFill ? null : this._background, owner.cachedCanvases);
  5758. if (!shadingFill) {
  5759. ctx.setTransform.apply(ctx, owner.baseTransform);
  5760. if (this._matrix) {
  5761. ctx.transform.apply(ctx, this._matrix);
  5762. }
  5763. }
  5764. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  5765. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  5766. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  5767. }
  5768. }
  5769. class DummyShadingPattern extends BaseShadingPattern {
  5770. getPattern() {
  5771. return "hotpink";
  5772. }
  5773. }
  5774. function getShadingPattern(IR) {
  5775. switch (IR[0]) {
  5776. case "RadialAxial":
  5777. return new RadialAxialShadingPattern(IR);
  5778. case "Mesh":
  5779. return new MeshShadingPattern(IR);
  5780. case "Dummy":
  5781. return new DummyShadingPattern();
  5782. }
  5783. throw new Error(`Unknown IR type: ${IR[0]}`);
  5784. }
  5785. const PaintType = {
  5786. COLORED: 1,
  5787. UNCOLORED: 2
  5788. };
  5789. class TilingPattern {
  5790. static get MAX_PATTERN_SIZE() {
  5791. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  5792. }
  5793. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5794. this.operatorList = IR[2];
  5795. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5796. this.bbox = IR[4];
  5797. this.xstep = IR[5];
  5798. this.ystep = IR[6];
  5799. this.paintType = IR[7];
  5800. this.tilingType = IR[8];
  5801. this.color = color;
  5802. this.ctx = ctx;
  5803. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5804. this.baseTransform = baseTransform;
  5805. }
  5806. createPatternCanvas(owner) {
  5807. const operatorList = this.operatorList;
  5808. const bbox = this.bbox;
  5809. const xstep = this.xstep;
  5810. const ystep = this.ystep;
  5811. const paintType = this.paintType;
  5812. const tilingType = this.tilingType;
  5813. const color = this.color;
  5814. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  5815. (0, _util.info)("TilingType: " + tilingType);
  5816. const x0 = bbox[0],
  5817. y0 = bbox[1],
  5818. x1 = bbox[2],
  5819. y1 = bbox[3];
  5820. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  5821. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  5822. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  5823. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  5824. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  5825. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  5826. const tmpCtx = tmpCanvas.context;
  5827. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5828. graphics.groupLevel = owner.groupLevel;
  5829. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  5830. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  5831. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5832. graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
  5833. graphics.executeOperatorList(operatorList);
  5834. graphics.endDrawing();
  5835. return {
  5836. canvas: tmpCanvas.canvas,
  5837. scaleX: dimx.scale,
  5838. scaleY: dimy.scale
  5839. };
  5840. }
  5841. getSizeAndScale(step, realOutputSize, scale) {
  5842. step = Math.abs(step);
  5843. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  5844. let size = Math.ceil(step * scale);
  5845. if (size >= maxSize) {
  5846. size = maxSize;
  5847. } else {
  5848. scale = size / step;
  5849. }
  5850. return {
  5851. scale,
  5852. size
  5853. };
  5854. }
  5855. clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5856. if (Array.isArray(bbox) && bbox.length === 4) {
  5857. const bboxWidth = x1 - x0;
  5858. const bboxHeight = y1 - y0;
  5859. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5860. graphics.clip();
  5861. graphics.endPath();
  5862. }
  5863. }
  5864. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  5865. const context = graphics.ctx,
  5866. current = graphics.current;
  5867. switch (paintType) {
  5868. case PaintType.COLORED:
  5869. const ctx = this.ctx;
  5870. context.fillStyle = ctx.fillStyle;
  5871. context.strokeStyle = ctx.strokeStyle;
  5872. current.fillColor = ctx.fillStyle;
  5873. current.strokeColor = ctx.strokeStyle;
  5874. break;
  5875. case PaintType.UNCOLORED:
  5876. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  5877. context.fillStyle = cssColor;
  5878. context.strokeStyle = cssColor;
  5879. current.fillColor = cssColor;
  5880. current.strokeColor = cssColor;
  5881. break;
  5882. default:
  5883. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  5884. }
  5885. }
  5886. getPattern(ctx, owner, shadingFill) {
  5887. ctx = this.ctx;
  5888. let matrix = ctx.mozCurrentTransformInverse;
  5889. if (!shadingFill) {
  5890. matrix = _util.Util.transform(matrix, owner.baseTransform);
  5891. if (this.matrix) {
  5892. matrix = _util.Util.transform(matrix, this.matrix);
  5893. }
  5894. }
  5895. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  5896. let domMatrix = createMatrix(matrix);
  5897. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  5898. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  5899. pattern.setTransform(domMatrix);
  5900. return pattern;
  5901. }
  5902. }
  5903. exports.TilingPattern = TilingPattern;
  5904. /***/ }),
  5905. /* 12 */
  5906. /***/ ((__unused_webpack_module, exports) => {
  5907. Object.defineProperty(exports, "__esModule", ({
  5908. value: true
  5909. }));
  5910. exports.GlobalWorkerOptions = void 0;
  5911. const GlobalWorkerOptions = Object.create(null);
  5912. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  5913. GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
  5914. GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
  5915. /***/ }),
  5916. /* 13 */
  5917. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5918. Object.defineProperty(exports, "__esModule", ({
  5919. value: true
  5920. }));
  5921. exports.MessageHandler = void 0;
  5922. var _util = __w_pdfjs_require__(2);
  5923. const CallbackKind = {
  5924. UNKNOWN: 0,
  5925. DATA: 1,
  5926. ERROR: 2
  5927. };
  5928. const StreamKind = {
  5929. UNKNOWN: 0,
  5930. CANCEL: 1,
  5931. CANCEL_COMPLETE: 2,
  5932. CLOSE: 3,
  5933. ENQUEUE: 4,
  5934. ERROR: 5,
  5935. PULL: 6,
  5936. PULL_COMPLETE: 7,
  5937. START_COMPLETE: 8
  5938. };
  5939. function wrapReason(reason) {
  5940. if (typeof reason !== "object" || reason === null) {
  5941. return reason;
  5942. }
  5943. switch (reason.name) {
  5944. case "AbortException":
  5945. return new _util.AbortException(reason.message);
  5946. case "MissingPDFException":
  5947. return new _util.MissingPDFException(reason.message);
  5948. case "UnexpectedResponseException":
  5949. return new _util.UnexpectedResponseException(reason.message, reason.status);
  5950. case "UnknownErrorException":
  5951. return new _util.UnknownErrorException(reason.message, reason.details);
  5952. default:
  5953. return new _util.UnknownErrorException(reason.message, reason.toString());
  5954. }
  5955. }
  5956. class MessageHandler {
  5957. constructor(sourceName, targetName, comObj) {
  5958. this.sourceName = sourceName;
  5959. this.targetName = targetName;
  5960. this.comObj = comObj;
  5961. this.callbackId = 1;
  5962. this.streamId = 1;
  5963. this.postMessageTransfers = true;
  5964. this.streamSinks = Object.create(null);
  5965. this.streamControllers = Object.create(null);
  5966. this.callbackCapabilities = Object.create(null);
  5967. this.actionHandler = Object.create(null);
  5968. this._onComObjOnMessage = event => {
  5969. const data = event.data;
  5970. if (data.targetName !== this.sourceName) {
  5971. return;
  5972. }
  5973. if (data.stream) {
  5974. this._processStreamMessage(data);
  5975. return;
  5976. }
  5977. if (data.callback) {
  5978. const callbackId = data.callbackId;
  5979. const capability = this.callbackCapabilities[callbackId];
  5980. if (!capability) {
  5981. throw new Error(`Cannot resolve callback ${callbackId}`);
  5982. }
  5983. delete this.callbackCapabilities[callbackId];
  5984. if (data.callback === CallbackKind.DATA) {
  5985. capability.resolve(data.data);
  5986. } else if (data.callback === CallbackKind.ERROR) {
  5987. capability.reject(wrapReason(data.reason));
  5988. } else {
  5989. throw new Error("Unexpected callback case");
  5990. }
  5991. return;
  5992. }
  5993. const action = this.actionHandler[data.action];
  5994. if (!action) {
  5995. throw new Error(`Unknown action from worker: ${data.action}`);
  5996. }
  5997. if (data.callbackId) {
  5998. const cbSourceName = this.sourceName;
  5999. const cbTargetName = data.sourceName;
  6000. new Promise(function (resolve) {
  6001. resolve(action(data.data));
  6002. }).then(function (result) {
  6003. comObj.postMessage({
  6004. sourceName: cbSourceName,
  6005. targetName: cbTargetName,
  6006. callback: CallbackKind.DATA,
  6007. callbackId: data.callbackId,
  6008. data: result
  6009. });
  6010. }, function (reason) {
  6011. comObj.postMessage({
  6012. sourceName: cbSourceName,
  6013. targetName: cbTargetName,
  6014. callback: CallbackKind.ERROR,
  6015. callbackId: data.callbackId,
  6016. reason: wrapReason(reason)
  6017. });
  6018. });
  6019. return;
  6020. }
  6021. if (data.streamId) {
  6022. this._createStreamSink(data);
  6023. return;
  6024. }
  6025. action(data.data);
  6026. };
  6027. comObj.addEventListener("message", this._onComObjOnMessage);
  6028. }
  6029. on(actionName, handler) {
  6030. const ah = this.actionHandler;
  6031. if (ah[actionName]) {
  6032. throw new Error(`There is already an actionName called "${actionName}"`);
  6033. }
  6034. ah[actionName] = handler;
  6035. }
  6036. send(actionName, data, transfers) {
  6037. this._postMessage({
  6038. sourceName: this.sourceName,
  6039. targetName: this.targetName,
  6040. action: actionName,
  6041. data
  6042. }, transfers);
  6043. }
  6044. sendWithPromise(actionName, data, transfers) {
  6045. const callbackId = this.callbackId++;
  6046. const capability = (0, _util.createPromiseCapability)();
  6047. this.callbackCapabilities[callbackId] = capability;
  6048. try {
  6049. this._postMessage({
  6050. sourceName: this.sourceName,
  6051. targetName: this.targetName,
  6052. action: actionName,
  6053. callbackId,
  6054. data
  6055. }, transfers);
  6056. } catch (ex) {
  6057. capability.reject(ex);
  6058. }
  6059. return capability.promise;
  6060. }
  6061. sendWithStream(actionName, data, queueingStrategy, transfers) {
  6062. const streamId = this.streamId++;
  6063. const sourceName = this.sourceName;
  6064. const targetName = this.targetName;
  6065. const comObj = this.comObj;
  6066. return new ReadableStream({
  6067. start: controller => {
  6068. const startCapability = (0, _util.createPromiseCapability)();
  6069. this.streamControllers[streamId] = {
  6070. controller,
  6071. startCall: startCapability,
  6072. pullCall: null,
  6073. cancelCall: null,
  6074. isClosed: false
  6075. };
  6076. this._postMessage({
  6077. sourceName,
  6078. targetName,
  6079. action: actionName,
  6080. streamId,
  6081. data,
  6082. desiredSize: controller.desiredSize
  6083. }, transfers);
  6084. return startCapability.promise;
  6085. },
  6086. pull: controller => {
  6087. const pullCapability = (0, _util.createPromiseCapability)();
  6088. this.streamControllers[streamId].pullCall = pullCapability;
  6089. comObj.postMessage({
  6090. sourceName,
  6091. targetName,
  6092. stream: StreamKind.PULL,
  6093. streamId,
  6094. desiredSize: controller.desiredSize
  6095. });
  6096. return pullCapability.promise;
  6097. },
  6098. cancel: reason => {
  6099. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  6100. const cancelCapability = (0, _util.createPromiseCapability)();
  6101. this.streamControllers[streamId].cancelCall = cancelCapability;
  6102. this.streamControllers[streamId].isClosed = true;
  6103. comObj.postMessage({
  6104. sourceName,
  6105. targetName,
  6106. stream: StreamKind.CANCEL,
  6107. streamId,
  6108. reason: wrapReason(reason)
  6109. });
  6110. return cancelCapability.promise;
  6111. }
  6112. }, queueingStrategy);
  6113. }
  6114. _createStreamSink(data) {
  6115. const self = this;
  6116. const action = this.actionHandler[data.action];
  6117. const streamId = data.streamId;
  6118. const sourceName = this.sourceName;
  6119. const targetName = data.sourceName;
  6120. const comObj = this.comObj;
  6121. const streamSink = {
  6122. enqueue(chunk, size = 1, transfers) {
  6123. if (this.isCancelled) {
  6124. return;
  6125. }
  6126. const lastDesiredSize = this.desiredSize;
  6127. this.desiredSize -= size;
  6128. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  6129. this.sinkCapability = (0, _util.createPromiseCapability)();
  6130. this.ready = this.sinkCapability.promise;
  6131. }
  6132. self._postMessage({
  6133. sourceName,
  6134. targetName,
  6135. stream: StreamKind.ENQUEUE,
  6136. streamId,
  6137. chunk
  6138. }, transfers);
  6139. },
  6140. close() {
  6141. if (this.isCancelled) {
  6142. return;
  6143. }
  6144. this.isCancelled = true;
  6145. comObj.postMessage({
  6146. sourceName,
  6147. targetName,
  6148. stream: StreamKind.CLOSE,
  6149. streamId
  6150. });
  6151. delete self.streamSinks[streamId];
  6152. },
  6153. error(reason) {
  6154. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  6155. if (this.isCancelled) {
  6156. return;
  6157. }
  6158. this.isCancelled = true;
  6159. comObj.postMessage({
  6160. sourceName,
  6161. targetName,
  6162. stream: StreamKind.ERROR,
  6163. streamId,
  6164. reason: wrapReason(reason)
  6165. });
  6166. },
  6167. sinkCapability: (0, _util.createPromiseCapability)(),
  6168. onPull: null,
  6169. onCancel: null,
  6170. isCancelled: false,
  6171. desiredSize: data.desiredSize,
  6172. ready: null
  6173. };
  6174. streamSink.sinkCapability.resolve();
  6175. streamSink.ready = streamSink.sinkCapability.promise;
  6176. this.streamSinks[streamId] = streamSink;
  6177. new Promise(function (resolve) {
  6178. resolve(action(data.data, streamSink));
  6179. }).then(function () {
  6180. comObj.postMessage({
  6181. sourceName,
  6182. targetName,
  6183. stream: StreamKind.START_COMPLETE,
  6184. streamId,
  6185. success: true
  6186. });
  6187. }, function (reason) {
  6188. comObj.postMessage({
  6189. sourceName,
  6190. targetName,
  6191. stream: StreamKind.START_COMPLETE,
  6192. streamId,
  6193. reason: wrapReason(reason)
  6194. });
  6195. });
  6196. }
  6197. _processStreamMessage(data) {
  6198. const streamId = data.streamId;
  6199. const sourceName = this.sourceName;
  6200. const targetName = data.sourceName;
  6201. const comObj = this.comObj;
  6202. switch (data.stream) {
  6203. case StreamKind.START_COMPLETE:
  6204. if (data.success) {
  6205. this.streamControllers[streamId].startCall.resolve();
  6206. } else {
  6207. this.streamControllers[streamId].startCall.reject(wrapReason(data.reason));
  6208. }
  6209. break;
  6210. case StreamKind.PULL_COMPLETE:
  6211. if (data.success) {
  6212. this.streamControllers[streamId].pullCall.resolve();
  6213. } else {
  6214. this.streamControllers[streamId].pullCall.reject(wrapReason(data.reason));
  6215. }
  6216. break;
  6217. case StreamKind.PULL:
  6218. if (!this.streamSinks[streamId]) {
  6219. comObj.postMessage({
  6220. sourceName,
  6221. targetName,
  6222. stream: StreamKind.PULL_COMPLETE,
  6223. streamId,
  6224. success: true
  6225. });
  6226. break;
  6227. }
  6228. if (this.streamSinks[streamId].desiredSize <= 0 && data.desiredSize > 0) {
  6229. this.streamSinks[streamId].sinkCapability.resolve();
  6230. }
  6231. this.streamSinks[streamId].desiredSize = data.desiredSize;
  6232. const {
  6233. onPull
  6234. } = this.streamSinks[data.streamId];
  6235. new Promise(function (resolve) {
  6236. resolve(onPull && onPull());
  6237. }).then(function () {
  6238. comObj.postMessage({
  6239. sourceName,
  6240. targetName,
  6241. stream: StreamKind.PULL_COMPLETE,
  6242. streamId,
  6243. success: true
  6244. });
  6245. }, function (reason) {
  6246. comObj.postMessage({
  6247. sourceName,
  6248. targetName,
  6249. stream: StreamKind.PULL_COMPLETE,
  6250. streamId,
  6251. reason: wrapReason(reason)
  6252. });
  6253. });
  6254. break;
  6255. case StreamKind.ENQUEUE:
  6256. (0, _util.assert)(this.streamControllers[streamId], "enqueue should have stream controller");
  6257. if (this.streamControllers[streamId].isClosed) {
  6258. break;
  6259. }
  6260. this.streamControllers[streamId].controller.enqueue(data.chunk);
  6261. break;
  6262. case StreamKind.CLOSE:
  6263. (0, _util.assert)(this.streamControllers[streamId], "close should have stream controller");
  6264. if (this.streamControllers[streamId].isClosed) {
  6265. break;
  6266. }
  6267. this.streamControllers[streamId].isClosed = true;
  6268. this.streamControllers[streamId].controller.close();
  6269. this._deleteStreamController(streamId);
  6270. break;
  6271. case StreamKind.ERROR:
  6272. (0, _util.assert)(this.streamControllers[streamId], "error should have stream controller");
  6273. this.streamControllers[streamId].controller.error(wrapReason(data.reason));
  6274. this._deleteStreamController(streamId);
  6275. break;
  6276. case StreamKind.CANCEL_COMPLETE:
  6277. if (data.success) {
  6278. this.streamControllers[streamId].cancelCall.resolve();
  6279. } else {
  6280. this.streamControllers[streamId].cancelCall.reject(wrapReason(data.reason));
  6281. }
  6282. this._deleteStreamController(streamId);
  6283. break;
  6284. case StreamKind.CANCEL:
  6285. if (!this.streamSinks[streamId]) {
  6286. break;
  6287. }
  6288. const {
  6289. onCancel
  6290. } = this.streamSinks[data.streamId];
  6291. new Promise(function (resolve) {
  6292. resolve(onCancel && onCancel(wrapReason(data.reason)));
  6293. }).then(function () {
  6294. comObj.postMessage({
  6295. sourceName,
  6296. targetName,
  6297. stream: StreamKind.CANCEL_COMPLETE,
  6298. streamId,
  6299. success: true
  6300. });
  6301. }, function (reason) {
  6302. comObj.postMessage({
  6303. sourceName,
  6304. targetName,
  6305. stream: StreamKind.CANCEL_COMPLETE,
  6306. streamId,
  6307. reason: wrapReason(reason)
  6308. });
  6309. });
  6310. this.streamSinks[streamId].sinkCapability.reject(wrapReason(data.reason));
  6311. this.streamSinks[streamId].isCancelled = true;
  6312. delete this.streamSinks[streamId];
  6313. break;
  6314. default:
  6315. throw new Error("Unexpected stream case");
  6316. }
  6317. }
  6318. async _deleteStreamController(streamId) {
  6319. await Promise.allSettled([this.streamControllers[streamId].startCall, this.streamControllers[streamId].pullCall, this.streamControllers[streamId].cancelCall].map(function (capability) {
  6320. return capability && capability.promise;
  6321. }));
  6322. delete this.streamControllers[streamId];
  6323. }
  6324. _postMessage(message, transfers) {
  6325. if (transfers && this.postMessageTransfers) {
  6326. this.comObj.postMessage(message, transfers);
  6327. } else {
  6328. this.comObj.postMessage(message);
  6329. }
  6330. }
  6331. destroy() {
  6332. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  6333. }
  6334. }
  6335. exports.MessageHandler = MessageHandler;
  6336. /***/ }),
  6337. /* 14 */
  6338. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6339. Object.defineProperty(exports, "__esModule", ({
  6340. value: true
  6341. }));
  6342. exports.Metadata = void 0;
  6343. var _util = __w_pdfjs_require__(2);
  6344. class Metadata {
  6345. constructor({
  6346. parsedData,
  6347. rawData
  6348. }) {
  6349. this._metadataMap = parsedData;
  6350. this._data = rawData;
  6351. }
  6352. getRaw() {
  6353. return this._data;
  6354. }
  6355. get(name) {
  6356. return this._metadataMap.get(name) ?? null;
  6357. }
  6358. getAll() {
  6359. return (0, _util.objectFromMap)(this._metadataMap);
  6360. }
  6361. has(name) {
  6362. return this._metadataMap.has(name);
  6363. }
  6364. }
  6365. exports.Metadata = Metadata;
  6366. /***/ }),
  6367. /* 15 */
  6368. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6369. Object.defineProperty(exports, "__esModule", ({
  6370. value: true
  6371. }));
  6372. exports.OptionalContentConfig = void 0;
  6373. var _util = __w_pdfjs_require__(2);
  6374. class OptionalContentGroup {
  6375. constructor(name, intent) {
  6376. this.visible = true;
  6377. this.name = name;
  6378. this.intent = intent;
  6379. }
  6380. }
  6381. class OptionalContentConfig {
  6382. constructor(data) {
  6383. this.name = null;
  6384. this.creator = null;
  6385. this._order = null;
  6386. this._groups = new Map();
  6387. if (data === null) {
  6388. return;
  6389. }
  6390. this.name = data.name;
  6391. this.creator = data.creator;
  6392. this._order = data.order;
  6393. for (const group of data.groups) {
  6394. this._groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  6395. }
  6396. if (data.baseState === "OFF") {
  6397. for (const group of this._groups) {
  6398. group.visible = false;
  6399. }
  6400. }
  6401. for (const on of data.on) {
  6402. this._groups.get(on).visible = true;
  6403. }
  6404. for (const off of data.off) {
  6405. this._groups.get(off).visible = false;
  6406. }
  6407. }
  6408. _evaluateVisibilityExpression(array) {
  6409. const length = array.length;
  6410. if (length < 2) {
  6411. return true;
  6412. }
  6413. const operator = array[0];
  6414. for (let i = 1; i < length; i++) {
  6415. const element = array[i];
  6416. let state;
  6417. if (Array.isArray(element)) {
  6418. state = this._evaluateVisibilityExpression(element);
  6419. } else if (this._groups.has(element)) {
  6420. state = this._groups.get(element).visible;
  6421. } else {
  6422. (0, _util.warn)(`Optional content group not found: ${element}`);
  6423. return true;
  6424. }
  6425. switch (operator) {
  6426. case "And":
  6427. if (!state) {
  6428. return false;
  6429. }
  6430. break;
  6431. case "Or":
  6432. if (state) {
  6433. return true;
  6434. }
  6435. break;
  6436. case "Not":
  6437. return !state;
  6438. default:
  6439. return true;
  6440. }
  6441. }
  6442. return operator === "And";
  6443. }
  6444. isVisible(group) {
  6445. if (group.type === "OCG") {
  6446. if (!this._groups.has(group.id)) {
  6447. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  6448. return true;
  6449. }
  6450. return this._groups.get(group.id).visible;
  6451. } else if (group.type === "OCMD") {
  6452. if (group.expression) {
  6453. return this._evaluateVisibilityExpression(group.expression);
  6454. }
  6455. if (!group.policy || group.policy === "AnyOn") {
  6456. for (const id of group.ids) {
  6457. if (!this._groups.has(id)) {
  6458. (0, _util.warn)(`Optional content group not found: ${id}`);
  6459. return true;
  6460. }
  6461. if (this._groups.get(id).visible) {
  6462. return true;
  6463. }
  6464. }
  6465. return false;
  6466. } else if (group.policy === "AllOn") {
  6467. for (const id of group.ids) {
  6468. if (!this._groups.has(id)) {
  6469. (0, _util.warn)(`Optional content group not found: ${id}`);
  6470. return true;
  6471. }
  6472. if (!this._groups.get(id).visible) {
  6473. return false;
  6474. }
  6475. }
  6476. return true;
  6477. } else if (group.policy === "AnyOff") {
  6478. for (const id of group.ids) {
  6479. if (!this._groups.has(id)) {
  6480. (0, _util.warn)(`Optional content group not found: ${id}`);
  6481. return true;
  6482. }
  6483. if (!this._groups.get(id).visible) {
  6484. return true;
  6485. }
  6486. }
  6487. return false;
  6488. } else if (group.policy === "AllOff") {
  6489. for (const id of group.ids) {
  6490. if (!this._groups.has(id)) {
  6491. (0, _util.warn)(`Optional content group not found: ${id}`);
  6492. return true;
  6493. }
  6494. if (this._groups.get(id).visible) {
  6495. return false;
  6496. }
  6497. }
  6498. return true;
  6499. }
  6500. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  6501. return true;
  6502. }
  6503. (0, _util.warn)(`Unknown group type ${group.type}.`);
  6504. return true;
  6505. }
  6506. setVisibility(id, visible = true) {
  6507. if (!this._groups.has(id)) {
  6508. (0, _util.warn)(`Optional content group not found: ${id}`);
  6509. return;
  6510. }
  6511. this._groups.get(id).visible = !!visible;
  6512. }
  6513. getOrder() {
  6514. if (!this._groups.size) {
  6515. return null;
  6516. }
  6517. if (this._order) {
  6518. return this._order.slice();
  6519. }
  6520. return Array.from(this._groups.keys());
  6521. }
  6522. getGroups() {
  6523. return this._groups.size > 0 ? (0, _util.objectFromMap)(this._groups) : null;
  6524. }
  6525. getGroup(id) {
  6526. return this._groups.get(id) || null;
  6527. }
  6528. }
  6529. exports.OptionalContentConfig = OptionalContentConfig;
  6530. /***/ }),
  6531. /* 16 */
  6532. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6533. Object.defineProperty(exports, "__esModule", ({
  6534. value: true
  6535. }));
  6536. exports.PDFDataTransportStream = void 0;
  6537. var _util = __w_pdfjs_require__(2);
  6538. var _display_utils = __w_pdfjs_require__(1);
  6539. class PDFDataTransportStream {
  6540. constructor(params, pdfDataRangeTransport) {
  6541. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  6542. this._queuedChunks = [];
  6543. this._progressiveDone = params.progressiveDone || false;
  6544. this._contentDispositionFilename = params.contentDispositionFilename || null;
  6545. const initialData = params.initialData;
  6546. if (initialData?.length > 0) {
  6547. const buffer = new Uint8Array(initialData).buffer;
  6548. this._queuedChunks.push(buffer);
  6549. }
  6550. this._pdfDataRangeTransport = pdfDataRangeTransport;
  6551. this._isStreamingSupported = !params.disableStream;
  6552. this._isRangeSupported = !params.disableRange;
  6553. this._contentLength = params.length;
  6554. this._fullRequestReader = null;
  6555. this._rangeReaders = [];
  6556. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  6557. this._onReceiveData({
  6558. begin,
  6559. chunk
  6560. });
  6561. });
  6562. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  6563. this._onProgress({
  6564. loaded,
  6565. total
  6566. });
  6567. });
  6568. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  6569. this._onReceiveData({
  6570. chunk
  6571. });
  6572. });
  6573. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  6574. this._onProgressiveDone();
  6575. });
  6576. this._pdfDataRangeTransport.transportReady();
  6577. }
  6578. _onReceiveData(args) {
  6579. const buffer = new Uint8Array(args.chunk).buffer;
  6580. if (args.begin === undefined) {
  6581. if (this._fullRequestReader) {
  6582. this._fullRequestReader._enqueue(buffer);
  6583. } else {
  6584. this._queuedChunks.push(buffer);
  6585. }
  6586. } else {
  6587. const found = this._rangeReaders.some(function (rangeReader) {
  6588. if (rangeReader._begin !== args.begin) {
  6589. return false;
  6590. }
  6591. rangeReader._enqueue(buffer);
  6592. return true;
  6593. });
  6594. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  6595. }
  6596. }
  6597. get _progressiveDataLength() {
  6598. return this._fullRequestReader?._loaded ?? 0;
  6599. }
  6600. _onProgress(evt) {
  6601. if (evt.total === undefined) {
  6602. const firstReader = this._rangeReaders[0];
  6603. if (firstReader?.onProgress) {
  6604. firstReader.onProgress({
  6605. loaded: evt.loaded
  6606. });
  6607. }
  6608. } else {
  6609. const fullReader = this._fullRequestReader;
  6610. if (fullReader?.onProgress) {
  6611. fullReader.onProgress({
  6612. loaded: evt.loaded,
  6613. total: evt.total
  6614. });
  6615. }
  6616. }
  6617. }
  6618. _onProgressiveDone() {
  6619. if (this._fullRequestReader) {
  6620. this._fullRequestReader.progressiveDone();
  6621. }
  6622. this._progressiveDone = true;
  6623. }
  6624. _removeRangeReader(reader) {
  6625. const i = this._rangeReaders.indexOf(reader);
  6626. if (i >= 0) {
  6627. this._rangeReaders.splice(i, 1);
  6628. }
  6629. }
  6630. getFullReader() {
  6631. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  6632. const queuedChunks = this._queuedChunks;
  6633. this._queuedChunks = null;
  6634. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  6635. }
  6636. getRangeReader(begin, end) {
  6637. if (end <= this._progressiveDataLength) {
  6638. return null;
  6639. }
  6640. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  6641. this._pdfDataRangeTransport.requestDataRange(begin, end);
  6642. this._rangeReaders.push(reader);
  6643. return reader;
  6644. }
  6645. cancelAllRequests(reason) {
  6646. if (this._fullRequestReader) {
  6647. this._fullRequestReader.cancel(reason);
  6648. }
  6649. for (const reader of this._rangeReaders.slice(0)) {
  6650. reader.cancel(reason);
  6651. }
  6652. this._pdfDataRangeTransport.abort();
  6653. }
  6654. }
  6655. exports.PDFDataTransportStream = PDFDataTransportStream;
  6656. class PDFDataTransportStreamReader {
  6657. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  6658. this._stream = stream;
  6659. this._done = progressiveDone || false;
  6660. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  6661. this._queuedChunks = queuedChunks || [];
  6662. this._loaded = 0;
  6663. for (const chunk of this._queuedChunks) {
  6664. this._loaded += chunk.byteLength;
  6665. }
  6666. this._requests = [];
  6667. this._headersReady = Promise.resolve();
  6668. stream._fullRequestReader = this;
  6669. this.onProgress = null;
  6670. }
  6671. _enqueue(chunk) {
  6672. if (this._done) {
  6673. return;
  6674. }
  6675. if (this._requests.length > 0) {
  6676. const requestCapability = this._requests.shift();
  6677. requestCapability.resolve({
  6678. value: chunk,
  6679. done: false
  6680. });
  6681. } else {
  6682. this._queuedChunks.push(chunk);
  6683. }
  6684. this._loaded += chunk.byteLength;
  6685. }
  6686. get headersReady() {
  6687. return this._headersReady;
  6688. }
  6689. get filename() {
  6690. return this._filename;
  6691. }
  6692. get isRangeSupported() {
  6693. return this._stream._isRangeSupported;
  6694. }
  6695. get isStreamingSupported() {
  6696. return this._stream._isStreamingSupported;
  6697. }
  6698. get contentLength() {
  6699. return this._stream._contentLength;
  6700. }
  6701. async read() {
  6702. if (this._queuedChunks.length > 0) {
  6703. const chunk = this._queuedChunks.shift();
  6704. return {
  6705. value: chunk,
  6706. done: false
  6707. };
  6708. }
  6709. if (this._done) {
  6710. return {
  6711. value: undefined,
  6712. done: true
  6713. };
  6714. }
  6715. const requestCapability = (0, _util.createPromiseCapability)();
  6716. this._requests.push(requestCapability);
  6717. return requestCapability.promise;
  6718. }
  6719. cancel(reason) {
  6720. this._done = true;
  6721. for (const requestCapability of this._requests) {
  6722. requestCapability.resolve({
  6723. value: undefined,
  6724. done: true
  6725. });
  6726. }
  6727. this._requests.length = 0;
  6728. }
  6729. progressiveDone() {
  6730. if (this._done) {
  6731. return;
  6732. }
  6733. this._done = true;
  6734. }
  6735. }
  6736. class PDFDataTransportStreamRangeReader {
  6737. constructor(stream, begin, end) {
  6738. this._stream = stream;
  6739. this._begin = begin;
  6740. this._end = end;
  6741. this._queuedChunk = null;
  6742. this._requests = [];
  6743. this._done = false;
  6744. this.onProgress = null;
  6745. }
  6746. _enqueue(chunk) {
  6747. if (this._done) {
  6748. return;
  6749. }
  6750. if (this._requests.length === 0) {
  6751. this._queuedChunk = chunk;
  6752. } else {
  6753. const requestsCapability = this._requests.shift();
  6754. requestsCapability.resolve({
  6755. value: chunk,
  6756. done: false
  6757. });
  6758. for (const requestCapability of this._requests) {
  6759. requestCapability.resolve({
  6760. value: undefined,
  6761. done: true
  6762. });
  6763. }
  6764. this._requests.length = 0;
  6765. }
  6766. this._done = true;
  6767. this._stream._removeRangeReader(this);
  6768. }
  6769. get isStreamingSupported() {
  6770. return false;
  6771. }
  6772. async read() {
  6773. if (this._queuedChunk) {
  6774. const chunk = this._queuedChunk;
  6775. this._queuedChunk = null;
  6776. return {
  6777. value: chunk,
  6778. done: false
  6779. };
  6780. }
  6781. if (this._done) {
  6782. return {
  6783. value: undefined,
  6784. done: true
  6785. };
  6786. }
  6787. const requestCapability = (0, _util.createPromiseCapability)();
  6788. this._requests.push(requestCapability);
  6789. return requestCapability.promise;
  6790. }
  6791. cancel(reason) {
  6792. this._done = true;
  6793. for (const requestCapability of this._requests) {
  6794. requestCapability.resolve({
  6795. value: undefined,
  6796. done: true
  6797. });
  6798. }
  6799. this._requests.length = 0;
  6800. this._stream._removeRangeReader(this);
  6801. }
  6802. }
  6803. /***/ }),
  6804. /* 17 */
  6805. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6806. Object.defineProperty(exports, "__esModule", ({
  6807. value: true
  6808. }));
  6809. exports.AnnotationLayer = void 0;
  6810. var _display_utils = __w_pdfjs_require__(1);
  6811. var _util = __w_pdfjs_require__(2);
  6812. var _annotation_storage = __w_pdfjs_require__(8);
  6813. var _scripting_utils = __w_pdfjs_require__(18);
  6814. class AnnotationElementFactory {
  6815. static create(parameters) {
  6816. const subtype = parameters.data.annotationType;
  6817. switch (subtype) {
  6818. case _util.AnnotationType.LINK:
  6819. return new LinkAnnotationElement(parameters);
  6820. case _util.AnnotationType.TEXT:
  6821. return new TextAnnotationElement(parameters);
  6822. case _util.AnnotationType.WIDGET:
  6823. const fieldType = parameters.data.fieldType;
  6824. switch (fieldType) {
  6825. case "Tx":
  6826. return new TextWidgetAnnotationElement(parameters);
  6827. case "Btn":
  6828. if (parameters.data.radioButton) {
  6829. return new RadioButtonWidgetAnnotationElement(parameters);
  6830. } else if (parameters.data.checkBox) {
  6831. return new CheckboxWidgetAnnotationElement(parameters);
  6832. }
  6833. return new PushButtonWidgetAnnotationElement(parameters);
  6834. case "Ch":
  6835. return new ChoiceWidgetAnnotationElement(parameters);
  6836. }
  6837. return new WidgetAnnotationElement(parameters);
  6838. case _util.AnnotationType.POPUP:
  6839. return new PopupAnnotationElement(parameters);
  6840. case _util.AnnotationType.FREETEXT:
  6841. return new FreeTextAnnotationElement(parameters);
  6842. case _util.AnnotationType.LINE:
  6843. return new LineAnnotationElement(parameters);
  6844. case _util.AnnotationType.SQUARE:
  6845. return new SquareAnnotationElement(parameters);
  6846. case _util.AnnotationType.CIRCLE:
  6847. return new CircleAnnotationElement(parameters);
  6848. case _util.AnnotationType.POLYLINE:
  6849. return new PolylineAnnotationElement(parameters);
  6850. case _util.AnnotationType.CARET:
  6851. return new CaretAnnotationElement(parameters);
  6852. case _util.AnnotationType.INK:
  6853. return new InkAnnotationElement(parameters);
  6854. case _util.AnnotationType.POLYGON:
  6855. return new PolygonAnnotationElement(parameters);
  6856. case _util.AnnotationType.HIGHLIGHT:
  6857. return new HighlightAnnotationElement(parameters);
  6858. case _util.AnnotationType.UNDERLINE:
  6859. return new UnderlineAnnotationElement(parameters);
  6860. case _util.AnnotationType.SQUIGGLY:
  6861. return new SquigglyAnnotationElement(parameters);
  6862. case _util.AnnotationType.STRIKEOUT:
  6863. return new StrikeOutAnnotationElement(parameters);
  6864. case _util.AnnotationType.STAMP:
  6865. return new StampAnnotationElement(parameters);
  6866. case _util.AnnotationType.FILEATTACHMENT:
  6867. return new FileAttachmentAnnotationElement(parameters);
  6868. default:
  6869. return new AnnotationElement(parameters);
  6870. }
  6871. }
  6872. }
  6873. class AnnotationElement {
  6874. constructor(parameters, {
  6875. isRenderable = false,
  6876. ignoreBorder = false,
  6877. createQuadrilaterals = false
  6878. } = {}) {
  6879. this.isRenderable = isRenderable;
  6880. this.data = parameters.data;
  6881. this.layer = parameters.layer;
  6882. this.page = parameters.page;
  6883. this.viewport = parameters.viewport;
  6884. this.linkService = parameters.linkService;
  6885. this.downloadManager = parameters.downloadManager;
  6886. this.imageResourcesPath = parameters.imageResourcesPath;
  6887. this.renderInteractiveForms = parameters.renderInteractiveForms;
  6888. this.svgFactory = parameters.svgFactory;
  6889. this.annotationStorage = parameters.annotationStorage;
  6890. this.enableScripting = parameters.enableScripting;
  6891. this.hasJSActions = parameters.hasJSActions;
  6892. this._mouseState = parameters.mouseState;
  6893. if (isRenderable) {
  6894. this.container = this._createContainer(ignoreBorder);
  6895. }
  6896. if (createQuadrilaterals) {
  6897. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  6898. }
  6899. }
  6900. _createContainer(ignoreBorder = false) {
  6901. const data = this.data,
  6902. page = this.page,
  6903. viewport = this.viewport;
  6904. const container = document.createElement("section");
  6905. let width = data.rect[2] - data.rect[0];
  6906. let height = data.rect[3] - data.rect[1];
  6907. container.setAttribute("data-annotation-id", data.id);
  6908. 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]]);
  6909. container.style.transform = `matrix(${viewport.transform.join(",")})`;
  6910. container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
  6911. if (!ignoreBorder && data.borderStyle.width > 0) {
  6912. container.style.borderWidth = `${data.borderStyle.width}px`;
  6913. if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
  6914. width = width - 2 * data.borderStyle.width;
  6915. height = height - 2 * data.borderStyle.width;
  6916. }
  6917. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  6918. const verticalRadius = data.borderStyle.verticalCornerRadius;
  6919. if (horizontalRadius > 0 || verticalRadius > 0) {
  6920. const radius = `${horizontalRadius}px / ${verticalRadius}px`;
  6921. container.style.borderRadius = radius;
  6922. }
  6923. switch (data.borderStyle.style) {
  6924. case _util.AnnotationBorderStyleType.SOLID:
  6925. container.style.borderStyle = "solid";
  6926. break;
  6927. case _util.AnnotationBorderStyleType.DASHED:
  6928. container.style.borderStyle = "dashed";
  6929. break;
  6930. case _util.AnnotationBorderStyleType.BEVELED:
  6931. (0, _util.warn)("Unimplemented border style: beveled");
  6932. break;
  6933. case _util.AnnotationBorderStyleType.INSET:
  6934. (0, _util.warn)("Unimplemented border style: inset");
  6935. break;
  6936. case _util.AnnotationBorderStyleType.UNDERLINE:
  6937. container.style.borderBottomStyle = "solid";
  6938. break;
  6939. default:
  6940. break;
  6941. }
  6942. if (data.color) {
  6943. container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  6944. } else {
  6945. container.style.borderWidth = 0;
  6946. }
  6947. }
  6948. container.style.left = `${rect[0]}px`;
  6949. container.style.top = `${rect[1]}px`;
  6950. container.style.width = `${width}px`;
  6951. container.style.height = `${height}px`;
  6952. return container;
  6953. }
  6954. _createQuadrilaterals(ignoreBorder = false) {
  6955. if (!this.data.quadPoints) {
  6956. return null;
  6957. }
  6958. const quadrilaterals = [];
  6959. const savedRect = this.data.rect;
  6960. for (const quadPoint of this.data.quadPoints) {
  6961. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  6962. quadrilaterals.push(this._createContainer(ignoreBorder));
  6963. }
  6964. this.data.rect = savedRect;
  6965. return quadrilaterals;
  6966. }
  6967. _createPopup(trigger, data) {
  6968. let container = this.container;
  6969. if (this.quadrilaterals) {
  6970. trigger = trigger || this.quadrilaterals;
  6971. container = this.quadrilaterals[0];
  6972. }
  6973. if (!trigger) {
  6974. trigger = document.createElement("div");
  6975. trigger.style.height = container.style.height;
  6976. trigger.style.width = container.style.width;
  6977. container.appendChild(trigger);
  6978. }
  6979. const popupElement = new PopupElement({
  6980. container,
  6981. trigger,
  6982. color: data.color,
  6983. title: data.title,
  6984. modificationDate: data.modificationDate,
  6985. contents: data.contents,
  6986. hideWrapper: true
  6987. });
  6988. const popup = popupElement.render();
  6989. popup.style.left = container.style.width;
  6990. container.appendChild(popup);
  6991. }
  6992. _renderQuadrilaterals(className) {
  6993. for (const quadrilateral of this.quadrilaterals) {
  6994. quadrilateral.className = className;
  6995. }
  6996. return this.quadrilaterals;
  6997. }
  6998. render() {
  6999. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  7000. }
  7001. }
  7002. class LinkAnnotationElement extends AnnotationElement {
  7003. constructor(parameters) {
  7004. 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"]));
  7005. super(parameters, {
  7006. isRenderable,
  7007. createQuadrilaterals: true
  7008. });
  7009. }
  7010. render() {
  7011. const {
  7012. data,
  7013. linkService
  7014. } = this;
  7015. const link = document.createElement("a");
  7016. if (data.url) {
  7017. (0, _display_utils.addLinkAttributes)(link, {
  7018. url: data.url,
  7019. target: data.newWindow ? _display_utils.LinkTarget.BLANK : linkService.externalLinkTarget,
  7020. rel: linkService.externalLinkRel,
  7021. enabled: linkService.externalLinkEnabled
  7022. });
  7023. } else if (data.action) {
  7024. this._bindNamedAction(link, data.action);
  7025. } else if (data.dest) {
  7026. this._bindLink(link, data.dest);
  7027. } else if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  7028. this._bindJSAction(link, data);
  7029. } else {
  7030. this._bindLink(link, "");
  7031. }
  7032. if (this.quadrilaterals) {
  7033. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  7034. const linkElement = index === 0 ? link : link.cloneNode();
  7035. quadrilateral.appendChild(linkElement);
  7036. return quadrilateral;
  7037. });
  7038. }
  7039. this.container.className = "linkAnnotation";
  7040. this.container.appendChild(link);
  7041. return this.container;
  7042. }
  7043. _bindLink(link, destination) {
  7044. link.href = this.linkService.getDestinationHash(destination);
  7045. link.onclick = () => {
  7046. if (destination) {
  7047. this.linkService.goToDestination(destination);
  7048. }
  7049. return false;
  7050. };
  7051. if (destination || destination === "") {
  7052. link.className = "internalLink";
  7053. }
  7054. }
  7055. _bindNamedAction(link, action) {
  7056. link.href = this.linkService.getAnchorUrl("");
  7057. link.onclick = () => {
  7058. this.linkService.executeNamedAction(action);
  7059. return false;
  7060. };
  7061. link.className = "internalLink";
  7062. }
  7063. _bindJSAction(link, data) {
  7064. link.href = this.linkService.getAnchorUrl("");
  7065. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  7066. for (const name of Object.keys(data.actions)) {
  7067. const jsName = map.get(name);
  7068. if (!jsName) {
  7069. continue;
  7070. }
  7071. link[jsName] = () => {
  7072. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7073. source: this,
  7074. detail: {
  7075. id: data.id,
  7076. name
  7077. }
  7078. });
  7079. return false;
  7080. };
  7081. }
  7082. link.className = "internalLink";
  7083. }
  7084. }
  7085. class TextAnnotationElement extends AnnotationElement {
  7086. constructor(parameters) {
  7087. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  7088. super(parameters, {
  7089. isRenderable
  7090. });
  7091. }
  7092. render() {
  7093. this.container.className = "textAnnotation";
  7094. const image = document.createElement("img");
  7095. image.style.height = this.container.style.height;
  7096. image.style.width = this.container.style.width;
  7097. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  7098. image.alt = "[{{type}} Annotation]";
  7099. image.dataset.l10nId = "text_annotation_type";
  7100. image.dataset.l10nArgs = JSON.stringify({
  7101. type: this.data.name
  7102. });
  7103. if (!this.data.hasPopup) {
  7104. this._createPopup(image, this.data);
  7105. }
  7106. this.container.appendChild(image);
  7107. return this.container;
  7108. }
  7109. }
  7110. class WidgetAnnotationElement extends AnnotationElement {
  7111. render() {
  7112. if (this.data.alternativeText) {
  7113. this.container.title = this.data.alternativeText;
  7114. }
  7115. return this.container;
  7116. }
  7117. _getKeyModifier(event) {
  7118. return navigator.platform.includes("Win") && event.ctrlKey || navigator.platform.includes("Mac") && event.metaKey;
  7119. }
  7120. _setEventListener(element, baseName, eventName, valueGetter) {
  7121. if (baseName.includes("mouse")) {
  7122. element.addEventListener(baseName, event => {
  7123. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7124. source: this,
  7125. detail: {
  7126. id: this.data.id,
  7127. name: eventName,
  7128. value: valueGetter(event),
  7129. shift: event.shiftKey,
  7130. modifier: this._getKeyModifier(event)
  7131. }
  7132. });
  7133. });
  7134. } else {
  7135. element.addEventListener(baseName, event => {
  7136. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7137. source: this,
  7138. detail: {
  7139. id: this.data.id,
  7140. name: eventName,
  7141. value: event.target.checked
  7142. }
  7143. });
  7144. });
  7145. }
  7146. }
  7147. _setEventListeners(element, names, getter) {
  7148. for (const [baseName, eventName] of names) {
  7149. if (eventName === "Action" || this.data.actions?.[eventName]) {
  7150. this._setEventListener(element, baseName, eventName, getter);
  7151. }
  7152. }
  7153. }
  7154. _dispatchEventFromSandbox(actions, jsEvent) {
  7155. const setColor = (jsName, styleName, event) => {
  7156. const color = event.detail[jsName];
  7157. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  7158. };
  7159. const commonActions = {
  7160. display: event => {
  7161. const hidden = event.detail.display % 2 === 1;
  7162. event.target.style.visibility = hidden ? "hidden" : "visible";
  7163. this.annotationStorage.setValue(this.data.id, {
  7164. hidden,
  7165. print: event.detail.display === 0 || event.detail.display === 3
  7166. });
  7167. },
  7168. print: event => {
  7169. this.annotationStorage.setValue(this.data.id, {
  7170. print: event.detail.print
  7171. });
  7172. },
  7173. hidden: event => {
  7174. event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
  7175. this.annotationStorage.setValue(this.data.id, {
  7176. hidden: event.detail.hidden
  7177. });
  7178. },
  7179. focus: event => {
  7180. setTimeout(() => event.target.focus({
  7181. preventScroll: false
  7182. }), 0);
  7183. },
  7184. userName: event => {
  7185. event.target.title = event.detail.userName;
  7186. },
  7187. readonly: event => {
  7188. if (event.detail.readonly) {
  7189. event.target.setAttribute("readonly", "");
  7190. } else {
  7191. event.target.removeAttribute("readonly");
  7192. }
  7193. },
  7194. required: event => {
  7195. if (event.detail.required) {
  7196. event.target.setAttribute("required", "");
  7197. } else {
  7198. event.target.removeAttribute("required");
  7199. }
  7200. },
  7201. bgColor: event => {
  7202. setColor("bgColor", "backgroundColor", event);
  7203. },
  7204. fillColor: event => {
  7205. setColor("fillColor", "backgroundColor", event);
  7206. },
  7207. fgColor: event => {
  7208. setColor("fgColor", "color", event);
  7209. },
  7210. textColor: event => {
  7211. setColor("textColor", "color", event);
  7212. },
  7213. borderColor: event => {
  7214. setColor("borderColor", "borderColor", event);
  7215. },
  7216. strokeColor: event => {
  7217. setColor("strokeColor", "borderColor", event);
  7218. }
  7219. };
  7220. for (const name of Object.keys(jsEvent.detail)) {
  7221. const action = actions[name] || commonActions[name];
  7222. if (action) {
  7223. action(jsEvent);
  7224. }
  7225. }
  7226. }
  7227. }
  7228. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  7229. constructor(parameters) {
  7230. const isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  7231. super(parameters, {
  7232. isRenderable
  7233. });
  7234. }
  7235. setPropertyOnSiblings(base, key, value, keyInStorage) {
  7236. const storage = this.annotationStorage;
  7237. for (const element of document.getElementsByName(base.name)) {
  7238. if (element !== base) {
  7239. element[key] = value;
  7240. const data = Object.create(null);
  7241. data[keyInStorage] = value;
  7242. storage.setValue(element.getAttribute("id"), data);
  7243. }
  7244. }
  7245. }
  7246. render() {
  7247. const storage = this.annotationStorage;
  7248. const id = this.data.id;
  7249. this.container.className = "textWidgetAnnotation";
  7250. let element = null;
  7251. if (this.renderInteractiveForms) {
  7252. const storedData = storage.getValue(id, {
  7253. value: this.data.fieldValue,
  7254. valueAsString: this.data.fieldValue
  7255. });
  7256. const textContent = storedData.valueAsString || storedData.value || "";
  7257. const elementData = {
  7258. userValue: null,
  7259. formattedValue: null,
  7260. beforeInputSelectionRange: null,
  7261. beforeInputValue: null
  7262. };
  7263. if (this.data.multiLine) {
  7264. element = document.createElement("textarea");
  7265. element.textContent = textContent;
  7266. } else {
  7267. element = document.createElement("input");
  7268. element.type = "text";
  7269. element.setAttribute("value", textContent);
  7270. }
  7271. elementData.userValue = textContent;
  7272. element.setAttribute("id", id);
  7273. element.addEventListener("input", event => {
  7274. storage.setValue(id, {
  7275. value: event.target.value
  7276. });
  7277. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  7278. });
  7279. let blurListener = event => {
  7280. if (elementData.formattedValue) {
  7281. event.target.value = elementData.formattedValue;
  7282. }
  7283. event.target.scrollLeft = 0;
  7284. elementData.beforeInputSelectionRange = null;
  7285. };
  7286. if (this.enableScripting && this.hasJSActions) {
  7287. element.addEventListener("focus", event => {
  7288. if (elementData.userValue) {
  7289. event.target.value = elementData.userValue;
  7290. }
  7291. });
  7292. element.addEventListener("updatefromsandbox", jsEvent => {
  7293. const actions = {
  7294. value(event) {
  7295. elementData.userValue = event.detail.value || "";
  7296. storage.setValue(id, {
  7297. value: elementData.userValue.toString()
  7298. });
  7299. if (!elementData.formattedValue) {
  7300. event.target.value = elementData.userValue;
  7301. }
  7302. },
  7303. valueAsString(event) {
  7304. elementData.formattedValue = event.detail.valueAsString || "";
  7305. if (event.target !== document.activeElement) {
  7306. event.target.value = elementData.formattedValue;
  7307. }
  7308. storage.setValue(id, {
  7309. formattedValue: elementData.formattedValue
  7310. });
  7311. },
  7312. selRange(event) {
  7313. const [selStart, selEnd] = event.detail.selRange;
  7314. if (selStart >= 0 && selEnd < event.target.value.length) {
  7315. event.target.setSelectionRange(selStart, selEnd);
  7316. }
  7317. }
  7318. };
  7319. this._dispatchEventFromSandbox(actions, jsEvent);
  7320. });
  7321. element.addEventListener("keydown", event => {
  7322. elementData.beforeInputValue = event.target.value;
  7323. let commitKey = -1;
  7324. if (event.key === "Escape") {
  7325. commitKey = 0;
  7326. } else if (event.key === "Enter") {
  7327. commitKey = 2;
  7328. } else if (event.key === "Tab") {
  7329. commitKey = 3;
  7330. }
  7331. if (commitKey === -1) {
  7332. return;
  7333. }
  7334. elementData.userValue = event.target.value;
  7335. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7336. source: this,
  7337. detail: {
  7338. id,
  7339. name: "Keystroke",
  7340. value: event.target.value,
  7341. willCommit: true,
  7342. commitKey,
  7343. selStart: event.target.selectionStart,
  7344. selEnd: event.target.selectionEnd
  7345. }
  7346. });
  7347. });
  7348. const _blurListener = blurListener;
  7349. blurListener = null;
  7350. element.addEventListener("blur", event => {
  7351. if (this._mouseState.isDown) {
  7352. elementData.userValue = event.target.value;
  7353. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7354. source: this,
  7355. detail: {
  7356. id,
  7357. name: "Keystroke",
  7358. value: event.target.value,
  7359. willCommit: true,
  7360. commitKey: 1,
  7361. selStart: event.target.selectionStart,
  7362. selEnd: event.target.selectionEnd
  7363. }
  7364. });
  7365. }
  7366. _blurListener(event);
  7367. });
  7368. element.addEventListener("mousedown", event => {
  7369. elementData.beforeInputValue = event.target.value;
  7370. elementData.beforeInputSelectionRange = null;
  7371. });
  7372. element.addEventListener("keyup", event => {
  7373. if (event.target.selectionStart === event.target.selectionEnd) {
  7374. elementData.beforeInputSelectionRange = null;
  7375. }
  7376. });
  7377. element.addEventListener("select", event => {
  7378. elementData.beforeInputSelectionRange = [event.target.selectionStart, event.target.selectionEnd];
  7379. });
  7380. if (this.data.actions?.Keystroke) {
  7381. element.addEventListener("input", event => {
  7382. let selStart = -1;
  7383. let selEnd = -1;
  7384. if (elementData.beforeInputSelectionRange) {
  7385. [selStart, selEnd] = elementData.beforeInputSelectionRange;
  7386. }
  7387. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7388. source: this,
  7389. detail: {
  7390. id,
  7391. name: "Keystroke",
  7392. value: elementData.beforeInputValue,
  7393. change: event.data,
  7394. willCommit: false,
  7395. selStart,
  7396. selEnd
  7397. }
  7398. });
  7399. });
  7400. }
  7401. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  7402. }
  7403. if (blurListener) {
  7404. element.addEventListener("blur", blurListener);
  7405. }
  7406. element.disabled = this.data.readOnly;
  7407. element.name = this.data.fieldName;
  7408. if (this.data.maxLen !== null) {
  7409. element.maxLength = this.data.maxLen;
  7410. }
  7411. if (this.data.comb) {
  7412. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  7413. const combWidth = fieldWidth / this.data.maxLen;
  7414. element.classList.add("comb");
  7415. element.style.letterSpacing = `calc(${combWidth}px - 1ch)`;
  7416. }
  7417. } else {
  7418. element = document.createElement("div");
  7419. element.textContent = this.data.fieldValue;
  7420. element.style.verticalAlign = "middle";
  7421. element.style.display = "table-cell";
  7422. }
  7423. this._setTextStyle(element);
  7424. this.container.appendChild(element);
  7425. return this.container;
  7426. }
  7427. _setTextStyle(element) {
  7428. const TEXT_ALIGNMENT = ["left", "center", "right"];
  7429. const {
  7430. fontSize,
  7431. fontColor
  7432. } = this.data.defaultAppearanceData;
  7433. const style = element.style;
  7434. if (fontSize) {
  7435. style.fontSize = `${fontSize}px`;
  7436. }
  7437. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  7438. if (this.data.textAlignment !== null) {
  7439. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  7440. }
  7441. }
  7442. }
  7443. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  7444. constructor(parameters) {
  7445. super(parameters, {
  7446. isRenderable: parameters.renderInteractiveForms
  7447. });
  7448. }
  7449. render() {
  7450. const storage = this.annotationStorage;
  7451. const data = this.data;
  7452. const id = data.id;
  7453. let value = storage.getValue(id, {
  7454. value: data.fieldValue && (data.exportValue && data.exportValue === data.fieldValue || !data.exportValue && data.fieldValue !== "Off")
  7455. }).value;
  7456. if (typeof value === "string") {
  7457. value = value !== "Off";
  7458. storage.setValue(id, {
  7459. value
  7460. });
  7461. }
  7462. this.container.className = "buttonWidgetAnnotation checkBox";
  7463. const element = document.createElement("input");
  7464. element.disabled = data.readOnly;
  7465. element.type = "checkbox";
  7466. element.name = this.data.fieldName;
  7467. if (value) {
  7468. element.setAttribute("checked", true);
  7469. }
  7470. element.setAttribute("id", id);
  7471. element.addEventListener("change", function (event) {
  7472. const name = event.target.name;
  7473. for (const checkbox of document.getElementsByName(name)) {
  7474. if (checkbox !== event.target) {
  7475. checkbox.checked = false;
  7476. storage.setValue(checkbox.parentNode.getAttribute("data-annotation-id"), {
  7477. value: false
  7478. });
  7479. }
  7480. }
  7481. storage.setValue(id, {
  7482. value: event.target.checked
  7483. });
  7484. });
  7485. if (this.enableScripting && this.hasJSActions) {
  7486. element.addEventListener("updatefromsandbox", jsEvent => {
  7487. const actions = {
  7488. value(event) {
  7489. event.target.checked = event.detail.value !== "Off";
  7490. storage.setValue(id, {
  7491. value: event.target.checked
  7492. });
  7493. }
  7494. };
  7495. this._dispatchEventFromSandbox(actions, jsEvent);
  7496. });
  7497. 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);
  7498. }
  7499. this.container.appendChild(element);
  7500. return this.container;
  7501. }
  7502. }
  7503. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  7504. constructor(parameters) {
  7505. super(parameters, {
  7506. isRenderable: parameters.renderInteractiveForms
  7507. });
  7508. }
  7509. render() {
  7510. this.container.className = "buttonWidgetAnnotation radioButton";
  7511. const storage = this.annotationStorage;
  7512. const data = this.data;
  7513. const id = data.id;
  7514. let value = storage.getValue(id, {
  7515. value: data.fieldValue === data.buttonValue
  7516. }).value;
  7517. if (typeof value === "string") {
  7518. value = value !== data.buttonValue;
  7519. storage.setValue(id, {
  7520. value
  7521. });
  7522. }
  7523. const element = document.createElement("input");
  7524. element.disabled = data.readOnly;
  7525. element.type = "radio";
  7526. element.name = data.fieldName;
  7527. if (value) {
  7528. element.setAttribute("checked", true);
  7529. }
  7530. element.setAttribute("id", id);
  7531. element.addEventListener("change", function (event) {
  7532. const {
  7533. target
  7534. } = event;
  7535. for (const radio of document.getElementsByName(target.name)) {
  7536. if (radio !== target) {
  7537. storage.setValue(radio.getAttribute("id"), {
  7538. value: false
  7539. });
  7540. }
  7541. }
  7542. storage.setValue(id, {
  7543. value: target.checked
  7544. });
  7545. });
  7546. if (this.enableScripting && this.hasJSActions) {
  7547. const pdfButtonValue = data.buttonValue;
  7548. element.addEventListener("updatefromsandbox", jsEvent => {
  7549. const actions = {
  7550. value(event) {
  7551. const checked = pdfButtonValue === event.detail.value;
  7552. for (const radio of document.getElementsByName(event.target.name)) {
  7553. const radioId = radio.getAttribute("id");
  7554. radio.checked = radioId === id && checked;
  7555. storage.setValue(radioId, {
  7556. value: radio.checked
  7557. });
  7558. }
  7559. }
  7560. };
  7561. this._dispatchEventFromSandbox(actions, jsEvent);
  7562. });
  7563. 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);
  7564. }
  7565. this.container.appendChild(element);
  7566. return this.container;
  7567. }
  7568. }
  7569. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  7570. render() {
  7571. const container = super.render();
  7572. container.className = "buttonWidgetAnnotation pushButton";
  7573. if (this.data.alternativeText) {
  7574. container.title = this.data.alternativeText;
  7575. }
  7576. return container;
  7577. }
  7578. }
  7579. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  7580. constructor(parameters) {
  7581. super(parameters, {
  7582. isRenderable: parameters.renderInteractiveForms
  7583. });
  7584. }
  7585. render() {
  7586. this.container.className = "choiceWidgetAnnotation";
  7587. const storage = this.annotationStorage;
  7588. const id = this.data.id;
  7589. storage.getValue(id, {
  7590. value: this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : undefined
  7591. });
  7592. const selectElement = document.createElement("select");
  7593. selectElement.disabled = this.data.readOnly;
  7594. selectElement.name = this.data.fieldName;
  7595. selectElement.setAttribute("id", id);
  7596. if (!this.data.combo) {
  7597. selectElement.size = this.data.options.length;
  7598. if (this.data.multiSelect) {
  7599. selectElement.multiple = true;
  7600. }
  7601. }
  7602. for (const option of this.data.options) {
  7603. const optionElement = document.createElement("option");
  7604. optionElement.textContent = option.displayValue;
  7605. optionElement.value = option.exportValue;
  7606. if (this.data.fieldValue.includes(option.exportValue)) {
  7607. optionElement.setAttribute("selected", true);
  7608. }
  7609. selectElement.appendChild(optionElement);
  7610. }
  7611. const getValue = (event, isExport) => {
  7612. const name = isExport ? "value" : "textContent";
  7613. const options = event.target.options;
  7614. if (!event.target.multiple) {
  7615. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  7616. }
  7617. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  7618. };
  7619. const getItems = event => {
  7620. const options = event.target.options;
  7621. return Array.prototype.map.call(options, option => {
  7622. return {
  7623. displayValue: option.textContent,
  7624. exportValue: option.value
  7625. };
  7626. });
  7627. };
  7628. if (this.enableScripting && this.hasJSActions) {
  7629. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  7630. const actions = {
  7631. value(event) {
  7632. const options = selectElement.options;
  7633. const value = event.detail.value;
  7634. const values = new Set(Array.isArray(value) ? value : [value]);
  7635. Array.prototype.forEach.call(options, option => {
  7636. option.selected = values.has(option.value);
  7637. });
  7638. storage.setValue(id, {
  7639. value: getValue(event, true)
  7640. });
  7641. },
  7642. multipleSelection(event) {
  7643. selectElement.multiple = true;
  7644. },
  7645. remove(event) {
  7646. const options = selectElement.options;
  7647. const index = event.detail.remove;
  7648. options[index].selected = false;
  7649. selectElement.remove(index);
  7650. if (options.length > 0) {
  7651. const i = Array.prototype.findIndex.call(options, option => option.selected);
  7652. if (i === -1) {
  7653. options[0].selected = true;
  7654. }
  7655. }
  7656. storage.setValue(id, {
  7657. value: getValue(event, true),
  7658. items: getItems(event)
  7659. });
  7660. },
  7661. clear(event) {
  7662. while (selectElement.length !== 0) {
  7663. selectElement.remove(0);
  7664. }
  7665. storage.setValue(id, {
  7666. value: null,
  7667. items: []
  7668. });
  7669. },
  7670. insert(event) {
  7671. const {
  7672. index,
  7673. displayValue,
  7674. exportValue
  7675. } = event.detail.insert;
  7676. const optionElement = document.createElement("option");
  7677. optionElement.textContent = displayValue;
  7678. optionElement.value = exportValue;
  7679. selectElement.insertBefore(optionElement, selectElement.children[index]);
  7680. storage.setValue(id, {
  7681. value: getValue(event, true),
  7682. items: getItems(event)
  7683. });
  7684. },
  7685. items(event) {
  7686. const {
  7687. items
  7688. } = event.detail;
  7689. while (selectElement.length !== 0) {
  7690. selectElement.remove(0);
  7691. }
  7692. for (const item of items) {
  7693. const {
  7694. displayValue,
  7695. exportValue
  7696. } = item;
  7697. const optionElement = document.createElement("option");
  7698. optionElement.textContent = displayValue;
  7699. optionElement.value = exportValue;
  7700. selectElement.appendChild(optionElement);
  7701. }
  7702. if (selectElement.options.length > 0) {
  7703. selectElement.options[0].selected = true;
  7704. }
  7705. storage.setValue(id, {
  7706. value: getValue(event, true),
  7707. items: getItems(event)
  7708. });
  7709. },
  7710. indices(event) {
  7711. const indices = new Set(event.detail.indices);
  7712. const options = event.target.options;
  7713. Array.prototype.forEach.call(options, (option, i) => {
  7714. option.selected = indices.has(i);
  7715. });
  7716. storage.setValue(id, {
  7717. value: getValue(event, true)
  7718. });
  7719. },
  7720. editable(event) {
  7721. event.target.disabled = !event.detail.editable;
  7722. }
  7723. };
  7724. this._dispatchEventFromSandbox(actions, jsEvent);
  7725. });
  7726. selectElement.addEventListener("input", event => {
  7727. const exportValue = getValue(event, true);
  7728. const value = getValue(event, false);
  7729. storage.setValue(id, {
  7730. value: exportValue
  7731. });
  7732. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  7733. source: this,
  7734. detail: {
  7735. id,
  7736. name: "Keystroke",
  7737. value,
  7738. changeEx: exportValue,
  7739. willCommit: true,
  7740. commitKey: 1,
  7741. keyDown: false
  7742. }
  7743. });
  7744. });
  7745. 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);
  7746. } else {
  7747. selectElement.addEventListener("input", function (event) {
  7748. storage.setValue(id, {
  7749. value: getValue(event)
  7750. });
  7751. });
  7752. }
  7753. this.container.appendChild(selectElement);
  7754. return this.container;
  7755. }
  7756. }
  7757. class PopupAnnotationElement extends AnnotationElement {
  7758. constructor(parameters) {
  7759. const isRenderable = !!(parameters.data.title || parameters.data.contents);
  7760. super(parameters, {
  7761. isRenderable
  7762. });
  7763. }
  7764. render() {
  7765. const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"];
  7766. this.container.className = "popupAnnotation";
  7767. if (IGNORE_TYPES.includes(this.data.parentType)) {
  7768. return this.container;
  7769. }
  7770. const selector = `[data-annotation-id="${this.data.parentId}"]`;
  7771. const parentElements = this.layer.querySelectorAll(selector);
  7772. if (parentElements.length === 0) {
  7773. return this.container;
  7774. }
  7775. const popup = new PopupElement({
  7776. container: this.container,
  7777. trigger: Array.from(parentElements),
  7778. color: this.data.color,
  7779. title: this.data.title,
  7780. modificationDate: this.data.modificationDate,
  7781. contents: this.data.contents
  7782. });
  7783. const page = this.page;
  7784. 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]]);
  7785. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  7786. const popupTop = rect[1];
  7787. this.container.style.transformOrigin = `${-popupLeft}px ${-popupTop}px`;
  7788. this.container.style.left = `${popupLeft}px`;
  7789. this.container.style.top = `${popupTop}px`;
  7790. this.container.appendChild(popup.render());
  7791. return this.container;
  7792. }
  7793. }
  7794. class PopupElement {
  7795. constructor(parameters) {
  7796. this.container = parameters.container;
  7797. this.trigger = parameters.trigger;
  7798. this.color = parameters.color;
  7799. this.title = parameters.title;
  7800. this.modificationDate = parameters.modificationDate;
  7801. this.contents = parameters.contents;
  7802. this.hideWrapper = parameters.hideWrapper || false;
  7803. this.pinned = false;
  7804. }
  7805. render() {
  7806. const BACKGROUND_ENLIGHT = 0.7;
  7807. const wrapper = document.createElement("div");
  7808. wrapper.className = "popupWrapper";
  7809. this.hideElement = this.hideWrapper ? wrapper : this.container;
  7810. this.hideElement.hidden = true;
  7811. const popup = document.createElement("div");
  7812. popup.className = "popup";
  7813. const color = this.color;
  7814. if (color) {
  7815. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  7816. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  7817. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  7818. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  7819. }
  7820. const title = document.createElement("h1");
  7821. title.textContent = this.title;
  7822. popup.appendChild(title);
  7823. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  7824. if (dateObject) {
  7825. const modificationDate = document.createElement("span");
  7826. modificationDate.textContent = "{{date}}, {{time}}";
  7827. modificationDate.dataset.l10nId = "annotation_date_string";
  7828. modificationDate.dataset.l10nArgs = JSON.stringify({
  7829. date: dateObject.toLocaleDateString(),
  7830. time: dateObject.toLocaleTimeString()
  7831. });
  7832. popup.appendChild(modificationDate);
  7833. }
  7834. const contents = this._formatContents(this.contents);
  7835. popup.appendChild(contents);
  7836. if (!Array.isArray(this.trigger)) {
  7837. this.trigger = [this.trigger];
  7838. }
  7839. for (const element of this.trigger) {
  7840. element.addEventListener("click", this._toggle.bind(this));
  7841. element.addEventListener("mouseover", this._show.bind(this, false));
  7842. element.addEventListener("mouseout", this._hide.bind(this, false));
  7843. }
  7844. popup.addEventListener("click", this._hide.bind(this, true));
  7845. wrapper.appendChild(popup);
  7846. return wrapper;
  7847. }
  7848. _formatContents(contents) {
  7849. const p = document.createElement("p");
  7850. const lines = contents.split(/(?:\r\n?|\n)/);
  7851. for (let i = 0, ii = lines.length; i < ii; ++i) {
  7852. const line = lines[i];
  7853. p.appendChild(document.createTextNode(line));
  7854. if (i < ii - 1) {
  7855. p.appendChild(document.createElement("br"));
  7856. }
  7857. }
  7858. return p;
  7859. }
  7860. _toggle() {
  7861. if (this.pinned) {
  7862. this._hide(true);
  7863. } else {
  7864. this._show(true);
  7865. }
  7866. }
  7867. _show(pin = false) {
  7868. if (pin) {
  7869. this.pinned = true;
  7870. }
  7871. if (this.hideElement.hidden) {
  7872. this.hideElement.hidden = false;
  7873. this.container.style.zIndex += 1;
  7874. }
  7875. }
  7876. _hide(unpin = true) {
  7877. if (unpin) {
  7878. this.pinned = false;
  7879. }
  7880. if (!this.hideElement.hidden && !this.pinned) {
  7881. this.hideElement.hidden = true;
  7882. this.container.style.zIndex -= 1;
  7883. }
  7884. }
  7885. }
  7886. class FreeTextAnnotationElement extends AnnotationElement {
  7887. constructor(parameters) {
  7888. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  7889. super(parameters, {
  7890. isRenderable,
  7891. ignoreBorder: true
  7892. });
  7893. }
  7894. render() {
  7895. this.container.className = "freeTextAnnotation";
  7896. if (!this.data.hasPopup) {
  7897. this._createPopup(null, this.data);
  7898. }
  7899. return this.container;
  7900. }
  7901. }
  7902. class LineAnnotationElement extends AnnotationElement {
  7903. constructor(parameters) {
  7904. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  7905. super(parameters, {
  7906. isRenderable,
  7907. ignoreBorder: true
  7908. });
  7909. }
  7910. render() {
  7911. this.container.className = "lineAnnotation";
  7912. const data = this.data;
  7913. const width = data.rect[2] - data.rect[0];
  7914. const height = data.rect[3] - data.rect[1];
  7915. const svg = this.svgFactory.create(width, height);
  7916. const line = this.svgFactory.createElement("svg:line");
  7917. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  7918. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  7919. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  7920. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  7921. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  7922. line.setAttribute("stroke", "transparent");
  7923. svg.appendChild(line);
  7924. this.container.append(svg);
  7925. this._createPopup(line, data);
  7926. return this.container;
  7927. }
  7928. }
  7929. class SquareAnnotationElement extends AnnotationElement {
  7930. constructor(parameters) {
  7931. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  7932. super(parameters, {
  7933. isRenderable,
  7934. ignoreBorder: true
  7935. });
  7936. }
  7937. render() {
  7938. this.container.className = "squareAnnotation";
  7939. const data = this.data;
  7940. const width = data.rect[2] - data.rect[0];
  7941. const height = data.rect[3] - data.rect[1];
  7942. const svg = this.svgFactory.create(width, height);
  7943. const borderWidth = data.borderStyle.width;
  7944. const square = this.svgFactory.createElement("svg:rect");
  7945. square.setAttribute("x", borderWidth / 2);
  7946. square.setAttribute("y", borderWidth / 2);
  7947. square.setAttribute("width", width - borderWidth);
  7948. square.setAttribute("height", height - borderWidth);
  7949. square.setAttribute("stroke-width", borderWidth || 1);
  7950. square.setAttribute("stroke", "transparent");
  7951. square.setAttribute("fill", "none");
  7952. svg.appendChild(square);
  7953. this.container.append(svg);
  7954. this._createPopup(square, data);
  7955. return this.container;
  7956. }
  7957. }
  7958. class CircleAnnotationElement extends AnnotationElement {
  7959. constructor(parameters) {
  7960. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  7961. super(parameters, {
  7962. isRenderable,
  7963. ignoreBorder: true
  7964. });
  7965. }
  7966. render() {
  7967. this.container.className = "circleAnnotation";
  7968. const data = this.data;
  7969. const width = data.rect[2] - data.rect[0];
  7970. const height = data.rect[3] - data.rect[1];
  7971. const svg = this.svgFactory.create(width, height);
  7972. const borderWidth = data.borderStyle.width;
  7973. const circle = this.svgFactory.createElement("svg:ellipse");
  7974. circle.setAttribute("cx", width / 2);
  7975. circle.setAttribute("cy", height / 2);
  7976. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  7977. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  7978. circle.setAttribute("stroke-width", borderWidth || 1);
  7979. circle.setAttribute("stroke", "transparent");
  7980. circle.setAttribute("fill", "none");
  7981. svg.appendChild(circle);
  7982. this.container.append(svg);
  7983. this._createPopup(circle, data);
  7984. return this.container;
  7985. }
  7986. }
  7987. class PolylineAnnotationElement extends AnnotationElement {
  7988. constructor(parameters) {
  7989. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  7990. super(parameters, {
  7991. isRenderable,
  7992. ignoreBorder: true
  7993. });
  7994. this.containerClassName = "polylineAnnotation";
  7995. this.svgElementName = "svg:polyline";
  7996. }
  7997. render() {
  7998. this.container.className = this.containerClassName;
  7999. const data = this.data;
  8000. const width = data.rect[2] - data.rect[0];
  8001. const height = data.rect[3] - data.rect[1];
  8002. const svg = this.svgFactory.create(width, height);
  8003. let points = [];
  8004. for (const coordinate of data.vertices) {
  8005. const x = coordinate.x - data.rect[0];
  8006. const y = data.rect[3] - coordinate.y;
  8007. points.push(x + "," + y);
  8008. }
  8009. points = points.join(" ");
  8010. const polyline = this.svgFactory.createElement(this.svgElementName);
  8011. polyline.setAttribute("points", points);
  8012. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  8013. polyline.setAttribute("stroke", "transparent");
  8014. polyline.setAttribute("fill", "none");
  8015. svg.appendChild(polyline);
  8016. this.container.append(svg);
  8017. this._createPopup(polyline, data);
  8018. return this.container;
  8019. }
  8020. }
  8021. class PolygonAnnotationElement extends PolylineAnnotationElement {
  8022. constructor(parameters) {
  8023. super(parameters);
  8024. this.containerClassName = "polygonAnnotation";
  8025. this.svgElementName = "svg:polygon";
  8026. }
  8027. }
  8028. class CaretAnnotationElement extends AnnotationElement {
  8029. constructor(parameters) {
  8030. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8031. super(parameters, {
  8032. isRenderable,
  8033. ignoreBorder: true
  8034. });
  8035. }
  8036. render() {
  8037. this.container.className = "caretAnnotation";
  8038. if (!this.data.hasPopup) {
  8039. this._createPopup(null, this.data);
  8040. }
  8041. return this.container;
  8042. }
  8043. }
  8044. class InkAnnotationElement extends AnnotationElement {
  8045. constructor(parameters) {
  8046. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8047. super(parameters, {
  8048. isRenderable,
  8049. ignoreBorder: true
  8050. });
  8051. this.containerClassName = "inkAnnotation";
  8052. this.svgElementName = "svg:polyline";
  8053. }
  8054. render() {
  8055. this.container.className = this.containerClassName;
  8056. const data = this.data;
  8057. const width = data.rect[2] - data.rect[0];
  8058. const height = data.rect[3] - data.rect[1];
  8059. const svg = this.svgFactory.create(width, height);
  8060. for (const inkList of data.inkLists) {
  8061. let points = [];
  8062. for (const coordinate of inkList) {
  8063. const x = coordinate.x - data.rect[0];
  8064. const y = data.rect[3] - coordinate.y;
  8065. points.push(`${x},${y}`);
  8066. }
  8067. points = points.join(" ");
  8068. const polyline = this.svgFactory.createElement(this.svgElementName);
  8069. polyline.setAttribute("points", points);
  8070. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  8071. polyline.setAttribute("stroke", "transparent");
  8072. polyline.setAttribute("fill", "none");
  8073. this._createPopup(polyline, data);
  8074. svg.appendChild(polyline);
  8075. }
  8076. this.container.append(svg);
  8077. return this.container;
  8078. }
  8079. }
  8080. class HighlightAnnotationElement extends AnnotationElement {
  8081. constructor(parameters) {
  8082. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8083. super(parameters, {
  8084. isRenderable,
  8085. ignoreBorder: true,
  8086. createQuadrilaterals: true
  8087. });
  8088. }
  8089. render() {
  8090. if (!this.data.hasPopup) {
  8091. this._createPopup(null, this.data);
  8092. }
  8093. if (this.quadrilaterals) {
  8094. return this._renderQuadrilaterals("highlightAnnotation");
  8095. }
  8096. this.container.className = "highlightAnnotation";
  8097. return this.container;
  8098. }
  8099. }
  8100. class UnderlineAnnotationElement extends AnnotationElement {
  8101. constructor(parameters) {
  8102. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8103. super(parameters, {
  8104. isRenderable,
  8105. ignoreBorder: true,
  8106. createQuadrilaterals: true
  8107. });
  8108. }
  8109. render() {
  8110. if (!this.data.hasPopup) {
  8111. this._createPopup(null, this.data);
  8112. }
  8113. if (this.quadrilaterals) {
  8114. return this._renderQuadrilaterals("underlineAnnotation");
  8115. }
  8116. this.container.className = "underlineAnnotation";
  8117. return this.container;
  8118. }
  8119. }
  8120. class SquigglyAnnotationElement extends AnnotationElement {
  8121. constructor(parameters) {
  8122. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8123. super(parameters, {
  8124. isRenderable,
  8125. ignoreBorder: true,
  8126. createQuadrilaterals: true
  8127. });
  8128. }
  8129. render() {
  8130. if (!this.data.hasPopup) {
  8131. this._createPopup(null, this.data);
  8132. }
  8133. if (this.quadrilaterals) {
  8134. return this._renderQuadrilaterals("squigglyAnnotation");
  8135. }
  8136. this.container.className = "squigglyAnnotation";
  8137. return this.container;
  8138. }
  8139. }
  8140. class StrikeOutAnnotationElement extends AnnotationElement {
  8141. constructor(parameters) {
  8142. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8143. super(parameters, {
  8144. isRenderable,
  8145. ignoreBorder: true,
  8146. createQuadrilaterals: true
  8147. });
  8148. }
  8149. render() {
  8150. if (!this.data.hasPopup) {
  8151. this._createPopup(null, this.data);
  8152. }
  8153. if (this.quadrilaterals) {
  8154. return this._renderQuadrilaterals("strikeoutAnnotation");
  8155. }
  8156. this.container.className = "strikeoutAnnotation";
  8157. return this.container;
  8158. }
  8159. }
  8160. class StampAnnotationElement extends AnnotationElement {
  8161. constructor(parameters) {
  8162. const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  8163. super(parameters, {
  8164. isRenderable,
  8165. ignoreBorder: true
  8166. });
  8167. }
  8168. render() {
  8169. this.container.className = "stampAnnotation";
  8170. if (!this.data.hasPopup) {
  8171. this._createPopup(null, this.data);
  8172. }
  8173. return this.container;
  8174. }
  8175. }
  8176. class FileAttachmentAnnotationElement extends AnnotationElement {
  8177. constructor(parameters) {
  8178. super(parameters, {
  8179. isRenderable: true
  8180. });
  8181. const {
  8182. filename,
  8183. content
  8184. } = this.data.file;
  8185. this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
  8186. this.content = content;
  8187. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  8188. source: this,
  8189. id: (0, _util.stringToPDFString)(filename),
  8190. filename,
  8191. content
  8192. });
  8193. }
  8194. render() {
  8195. this.container.className = "fileAttachmentAnnotation";
  8196. const trigger = document.createElement("div");
  8197. trigger.style.height = this.container.style.height;
  8198. trigger.style.width = this.container.style.width;
  8199. trigger.addEventListener("dblclick", this._download.bind(this));
  8200. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  8201. this._createPopup(trigger, this.data);
  8202. }
  8203. this.container.appendChild(trigger);
  8204. return this.container;
  8205. }
  8206. _download() {
  8207. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  8208. }
  8209. }
  8210. class AnnotationLayer {
  8211. static render(parameters) {
  8212. const sortedAnnotations = [],
  8213. popupAnnotations = [];
  8214. for (const data of parameters.annotations) {
  8215. if (!data) {
  8216. continue;
  8217. }
  8218. if (data.annotationType === _util.AnnotationType.POPUP) {
  8219. popupAnnotations.push(data);
  8220. continue;
  8221. }
  8222. sortedAnnotations.push(data);
  8223. }
  8224. if (popupAnnotations.length) {
  8225. sortedAnnotations.push(...popupAnnotations);
  8226. }
  8227. for (const data of sortedAnnotations) {
  8228. const element = AnnotationElementFactory.create({
  8229. data,
  8230. layer: parameters.div,
  8231. page: parameters.page,
  8232. viewport: parameters.viewport,
  8233. linkService: parameters.linkService,
  8234. downloadManager: parameters.downloadManager,
  8235. imageResourcesPath: parameters.imageResourcesPath || "",
  8236. renderInteractiveForms: parameters.renderInteractiveForms !== false,
  8237. svgFactory: new _display_utils.DOMSVGFactory(),
  8238. annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
  8239. enableScripting: parameters.enableScripting,
  8240. hasJSActions: parameters.hasJSActions,
  8241. mouseState: parameters.mouseState || {
  8242. isDown: false
  8243. }
  8244. });
  8245. if (element.isRenderable) {
  8246. const rendered = element.render();
  8247. if (data.hidden) {
  8248. rendered.style.visibility = "hidden";
  8249. }
  8250. if (Array.isArray(rendered)) {
  8251. for (const renderedElement of rendered) {
  8252. parameters.div.appendChild(renderedElement);
  8253. }
  8254. } else {
  8255. if (element instanceof PopupAnnotationElement) {
  8256. parameters.div.prepend(rendered);
  8257. } else {
  8258. parameters.div.appendChild(rendered);
  8259. }
  8260. }
  8261. }
  8262. }
  8263. }
  8264. static update(parameters) {
  8265. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  8266. for (const data of parameters.annotations) {
  8267. const elements = parameters.div.querySelectorAll(`[data-annotation-id="${data.id}"]`);
  8268. if (elements) {
  8269. for (const element of elements) {
  8270. element.style.transform = transform;
  8271. }
  8272. }
  8273. }
  8274. parameters.div.hidden = false;
  8275. }
  8276. }
  8277. exports.AnnotationLayer = AnnotationLayer;
  8278. /***/ }),
  8279. /* 18 */
  8280. /***/ ((__unused_webpack_module, exports) => {
  8281. Object.defineProperty(exports, "__esModule", ({
  8282. value: true
  8283. }));
  8284. exports.ColorConverters = void 0;
  8285. function makeColorComp(n) {
  8286. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  8287. }
  8288. class ColorConverters {
  8289. static CMYK_G([c, y, m, k]) {
  8290. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  8291. }
  8292. static G_CMYK([g]) {
  8293. return ["CMYK", 0, 0, 0, 1 - g];
  8294. }
  8295. static G_RGB([g]) {
  8296. return ["RGB", g, g, g];
  8297. }
  8298. static G_HTML([g]) {
  8299. const G = makeColorComp(g);
  8300. return `#${G}${G}${G}`;
  8301. }
  8302. static RGB_G([r, g, b]) {
  8303. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  8304. }
  8305. static RGB_HTML([r, g, b]) {
  8306. const R = makeColorComp(r);
  8307. const G = makeColorComp(g);
  8308. const B = makeColorComp(b);
  8309. return `#${R}${G}${B}`;
  8310. }
  8311. static T_HTML() {
  8312. return "#00000000";
  8313. }
  8314. static CMYK_RGB([c, y, m, k]) {
  8315. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  8316. }
  8317. static CMYK_HTML(components) {
  8318. return this.RGB_HTML(this.CMYK_RGB(components));
  8319. }
  8320. static RGB_CMYK([r, g, b]) {
  8321. const c = 1 - r;
  8322. const m = 1 - g;
  8323. const y = 1 - b;
  8324. const k = Math.min(c, m, y);
  8325. return ["CMYK", c, m, y, k];
  8326. }
  8327. }
  8328. exports.ColorConverters = ColorConverters;
  8329. /***/ }),
  8330. /* 19 */
  8331. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8332. Object.defineProperty(exports, "__esModule", ({
  8333. value: true
  8334. }));
  8335. exports.renderTextLayer = renderTextLayer;
  8336. var _util = __w_pdfjs_require__(2);
  8337. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  8338. const DEFAULT_FONT_SIZE = 30;
  8339. const DEFAULT_FONT_ASCENT = 0.8;
  8340. const ascentCache = new Map();
  8341. const AllWhitespaceRegexp = /^\s+$/g;
  8342. function getAscent(fontFamily, ctx) {
  8343. const cachedAscent = ascentCache.get(fontFamily);
  8344. if (cachedAscent) {
  8345. return cachedAscent;
  8346. }
  8347. ctx.save();
  8348. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  8349. const metrics = ctx.measureText("");
  8350. let ascent = metrics.fontBoundingBoxAscent;
  8351. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  8352. if (ascent) {
  8353. ctx.restore();
  8354. const ratio = ascent / (ascent + descent);
  8355. ascentCache.set(fontFamily, ratio);
  8356. return ratio;
  8357. }
  8358. ctx.strokeStyle = "red";
  8359. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8360. ctx.strokeText("g", 0, 0);
  8361. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8362. descent = 0;
  8363. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  8364. if (pixels[i] > 0) {
  8365. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  8366. break;
  8367. }
  8368. }
  8369. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8370. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  8371. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8372. ascent = 0;
  8373. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  8374. if (pixels[i] > 0) {
  8375. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  8376. break;
  8377. }
  8378. }
  8379. ctx.restore();
  8380. if (ascent) {
  8381. const ratio = ascent / (ascent + descent);
  8382. ascentCache.set(fontFamily, ratio);
  8383. return ratio;
  8384. }
  8385. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  8386. return DEFAULT_FONT_ASCENT;
  8387. }
  8388. function appendText(task, geom, styles, ctx) {
  8389. const textDiv = document.createElement("span");
  8390. const textDivProperties = {
  8391. angle: 0,
  8392. canvasWidth: 0,
  8393. hasText: geom.str !== "",
  8394. hasEOL: geom.hasEOL,
  8395. originalTransform: null,
  8396. paddingBottom: 0,
  8397. paddingLeft: 0,
  8398. paddingRight: 0,
  8399. paddingTop: 0,
  8400. scale: 1
  8401. };
  8402. task._textDivs.push(textDiv);
  8403. const tx = _util.Util.transform(task._viewport.transform, geom.transform);
  8404. let angle = Math.atan2(tx[1], tx[0]);
  8405. const style = styles[geom.fontName];
  8406. if (style.vertical) {
  8407. angle += Math.PI / 2;
  8408. }
  8409. const fontHeight = Math.hypot(tx[2], tx[3]);
  8410. const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
  8411. let left, top;
  8412. if (angle === 0) {
  8413. left = tx[4];
  8414. top = tx[5] - fontAscent;
  8415. } else {
  8416. left = tx[4] + fontAscent * Math.sin(angle);
  8417. top = tx[5] - fontAscent * Math.cos(angle);
  8418. }
  8419. textDiv.style.left = `${left}px`;
  8420. textDiv.style.top = `${top}px`;
  8421. textDiv.style.fontSize = `${fontHeight}px`;
  8422. textDiv.style.fontFamily = style.fontFamily;
  8423. textDiv.setAttribute("role", "presentation");
  8424. textDiv.textContent = geom.str;
  8425. textDiv.dir = geom.dir;
  8426. if (task._fontInspectorEnabled) {
  8427. textDiv.dataset.fontName = geom.fontName;
  8428. }
  8429. if (angle !== 0) {
  8430. textDivProperties.angle = angle * (180 / Math.PI);
  8431. }
  8432. let shouldScaleText = false;
  8433. if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) {
  8434. shouldScaleText = true;
  8435. } else if (geom.transform[0] !== geom.transform[3]) {
  8436. const absScaleX = Math.abs(geom.transform[0]),
  8437. absScaleY = Math.abs(geom.transform[3]);
  8438. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  8439. shouldScaleText = true;
  8440. }
  8441. }
  8442. if (shouldScaleText) {
  8443. if (style.vertical) {
  8444. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  8445. } else {
  8446. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  8447. }
  8448. }
  8449. task._textDivProperties.set(textDiv, textDivProperties);
  8450. if (task._textContentStream) {
  8451. task._layoutText(textDiv);
  8452. }
  8453. if (task._enhanceTextSelection && textDivProperties.hasText) {
  8454. let angleCos = 1,
  8455. angleSin = 0;
  8456. if (angle !== 0) {
  8457. angleCos = Math.cos(angle);
  8458. angleSin = Math.sin(angle);
  8459. }
  8460. const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  8461. const divHeight = fontHeight;
  8462. let m, b;
  8463. if (angle !== 0) {
  8464. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  8465. b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  8466. } else {
  8467. b = [left, top, left + divWidth, top + divHeight];
  8468. }
  8469. task._bounds.push({
  8470. left: b[0],
  8471. top: b[1],
  8472. right: b[2],
  8473. bottom: b[3],
  8474. div: textDiv,
  8475. size: [divWidth, divHeight],
  8476. m
  8477. });
  8478. }
  8479. }
  8480. function render(task) {
  8481. if (task._canceled) {
  8482. return;
  8483. }
  8484. const textDivs = task._textDivs;
  8485. const capability = task._capability;
  8486. const textDivsLength = textDivs.length;
  8487. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  8488. task._renderingDone = true;
  8489. capability.resolve();
  8490. return;
  8491. }
  8492. if (!task._textContentStream) {
  8493. for (let i = 0; i < textDivsLength; i++) {
  8494. task._layoutText(textDivs[i]);
  8495. }
  8496. }
  8497. task._renderingDone = true;
  8498. capability.resolve();
  8499. }
  8500. function findPositiveMin(ts, offset, count) {
  8501. let result = 0;
  8502. for (let i = 0; i < count; i++) {
  8503. const t = ts[offset++];
  8504. if (t > 0) {
  8505. result = result ? Math.min(t, result) : t;
  8506. }
  8507. }
  8508. return result;
  8509. }
  8510. function expand(task) {
  8511. const bounds = task._bounds;
  8512. const viewport = task._viewport;
  8513. const expanded = expandBounds(viewport.width, viewport.height, bounds);
  8514. for (let i = 0; i < expanded.length; i++) {
  8515. const div = bounds[i].div;
  8516. const divProperties = task._textDivProperties.get(div);
  8517. if (divProperties.angle === 0) {
  8518. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  8519. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  8520. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  8521. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  8522. task._textDivProperties.set(div, divProperties);
  8523. continue;
  8524. }
  8525. const e = expanded[i],
  8526. b = bounds[i];
  8527. const m = b.m,
  8528. c = m[0],
  8529. s = m[1];
  8530. const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  8531. const ts = new Float64Array(64);
  8532. for (let j = 0, jj = points.length; j < jj; j++) {
  8533. const t = _util.Util.applyTransform(points[j], m);
  8534. ts[j + 0] = c && (e.left - t[0]) / c;
  8535. ts[j + 4] = s && (e.top - t[1]) / s;
  8536. ts[j + 8] = c && (e.right - t[0]) / c;
  8537. ts[j + 12] = s && (e.bottom - t[1]) / s;
  8538. ts[j + 16] = s && (e.left - t[0]) / -s;
  8539. ts[j + 20] = c && (e.top - t[1]) / c;
  8540. ts[j + 24] = s && (e.right - t[0]) / -s;
  8541. ts[j + 28] = c && (e.bottom - t[1]) / c;
  8542. ts[j + 32] = c && (e.left - t[0]) / -c;
  8543. ts[j + 36] = s && (e.top - t[1]) / -s;
  8544. ts[j + 40] = c && (e.right - t[0]) / -c;
  8545. ts[j + 44] = s && (e.bottom - t[1]) / -s;
  8546. ts[j + 48] = s && (e.left - t[0]) / s;
  8547. ts[j + 52] = c && (e.top - t[1]) / -c;
  8548. ts[j + 56] = s && (e.right - t[0]) / s;
  8549. ts[j + 60] = c && (e.bottom - t[1]) / -c;
  8550. }
  8551. const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  8552. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  8553. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  8554. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  8555. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  8556. task._textDivProperties.set(div, divProperties);
  8557. }
  8558. }
  8559. function expandBounds(width, height, boxes) {
  8560. const bounds = boxes.map(function (box, i) {
  8561. return {
  8562. x1: box.left,
  8563. y1: box.top,
  8564. x2: box.right,
  8565. y2: box.bottom,
  8566. index: i,
  8567. x1New: undefined,
  8568. x2New: undefined
  8569. };
  8570. });
  8571. expandBoundsLTR(width, bounds);
  8572. const expanded = new Array(boxes.length);
  8573. for (const b of bounds) {
  8574. const i = b.index;
  8575. expanded[i] = {
  8576. left: b.x1New,
  8577. top: 0,
  8578. right: b.x2New,
  8579. bottom: 0
  8580. };
  8581. }
  8582. boxes.map(function (box, i) {
  8583. const e = expanded[i],
  8584. b = bounds[i];
  8585. b.x1 = box.top;
  8586. b.y1 = width - e.right;
  8587. b.x2 = box.bottom;
  8588. b.y2 = width - e.left;
  8589. b.index = i;
  8590. b.x1New = undefined;
  8591. b.x2New = undefined;
  8592. });
  8593. expandBoundsLTR(height, bounds);
  8594. for (const b of bounds) {
  8595. const i = b.index;
  8596. expanded[i].top = b.x1New;
  8597. expanded[i].bottom = b.x2New;
  8598. }
  8599. return expanded;
  8600. }
  8601. function expandBoundsLTR(width, bounds) {
  8602. bounds.sort(function (a, b) {
  8603. return a.x1 - b.x1 || a.index - b.index;
  8604. });
  8605. const fakeBoundary = {
  8606. x1: -Infinity,
  8607. y1: -Infinity,
  8608. x2: 0,
  8609. y2: Infinity,
  8610. index: -1,
  8611. x1New: 0,
  8612. x2New: 0
  8613. };
  8614. const horizon = [{
  8615. start: -Infinity,
  8616. end: Infinity,
  8617. boundary: fakeBoundary
  8618. }];
  8619. for (const boundary of bounds) {
  8620. let i = 0;
  8621. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  8622. i++;
  8623. }
  8624. let j = horizon.length - 1;
  8625. while (j >= 0 && horizon[j].start >= boundary.y2) {
  8626. j--;
  8627. }
  8628. let horizonPart, affectedBoundary;
  8629. let q,
  8630. k,
  8631. maxXNew = -Infinity;
  8632. for (q = i; q <= j; q++) {
  8633. horizonPart = horizon[q];
  8634. affectedBoundary = horizonPart.boundary;
  8635. let xNew;
  8636. if (affectedBoundary.x2 > boundary.x1) {
  8637. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  8638. } else if (affectedBoundary.x2New === undefined) {
  8639. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  8640. } else {
  8641. xNew = affectedBoundary.x2New;
  8642. }
  8643. if (xNew > maxXNew) {
  8644. maxXNew = xNew;
  8645. }
  8646. }
  8647. boundary.x1New = maxXNew;
  8648. for (q = i; q <= j; q++) {
  8649. horizonPart = horizon[q];
  8650. affectedBoundary = horizonPart.boundary;
  8651. if (affectedBoundary.x2New === undefined) {
  8652. if (affectedBoundary.x2 > boundary.x1) {
  8653. if (affectedBoundary.index > boundary.index) {
  8654. affectedBoundary.x2New = affectedBoundary.x2;
  8655. }
  8656. } else {
  8657. affectedBoundary.x2New = maxXNew;
  8658. }
  8659. } else if (affectedBoundary.x2New > maxXNew) {
  8660. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  8661. }
  8662. }
  8663. const changedHorizon = [];
  8664. let lastBoundary = null;
  8665. for (q = i; q <= j; q++) {
  8666. horizonPart = horizon[q];
  8667. affectedBoundary = horizonPart.boundary;
  8668. const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  8669. if (lastBoundary === useBoundary) {
  8670. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  8671. } else {
  8672. changedHorizon.push({
  8673. start: horizonPart.start,
  8674. end: horizonPart.end,
  8675. boundary: useBoundary
  8676. });
  8677. lastBoundary = useBoundary;
  8678. }
  8679. }
  8680. if (horizon[i].start < boundary.y1) {
  8681. changedHorizon[0].start = boundary.y1;
  8682. changedHorizon.unshift({
  8683. start: horizon[i].start,
  8684. end: boundary.y1,
  8685. boundary: horizon[i].boundary
  8686. });
  8687. }
  8688. if (boundary.y2 < horizon[j].end) {
  8689. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  8690. changedHorizon.push({
  8691. start: boundary.y2,
  8692. end: horizon[j].end,
  8693. boundary: horizon[j].boundary
  8694. });
  8695. }
  8696. for (q = i; q <= j; q++) {
  8697. horizonPart = horizon[q];
  8698. affectedBoundary = horizonPart.boundary;
  8699. if (affectedBoundary.x2New !== undefined) {
  8700. continue;
  8701. }
  8702. let used = false;
  8703. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  8704. used = horizon[k].boundary === affectedBoundary;
  8705. }
  8706. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  8707. used = horizon[k].boundary === affectedBoundary;
  8708. }
  8709. for (k = 0; !used && k < changedHorizon.length; k++) {
  8710. used = changedHorizon[k].boundary === affectedBoundary;
  8711. }
  8712. if (!used) {
  8713. affectedBoundary.x2New = maxXNew;
  8714. }
  8715. }
  8716. Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
  8717. }
  8718. for (const horizonPart of horizon) {
  8719. const affectedBoundary = horizonPart.boundary;
  8720. if (affectedBoundary.x2New === undefined) {
  8721. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  8722. }
  8723. }
  8724. }
  8725. class TextLayerRenderTask {
  8726. constructor({
  8727. textContent,
  8728. textContentStream,
  8729. container,
  8730. viewport,
  8731. textDivs,
  8732. textContentItemsStr,
  8733. enhanceTextSelection
  8734. }) {
  8735. this._textContent = textContent;
  8736. this._textContentStream = textContentStream;
  8737. this._container = container;
  8738. this._document = container.ownerDocument;
  8739. this._viewport = viewport;
  8740. this._textDivs = textDivs || [];
  8741. this._textContentItemsStr = textContentItemsStr || [];
  8742. this._enhanceTextSelection = !!enhanceTextSelection;
  8743. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  8744. this._reader = null;
  8745. this._layoutTextLastFontSize = null;
  8746. this._layoutTextLastFontFamily = null;
  8747. this._layoutTextCtx = null;
  8748. this._textDivProperties = new WeakMap();
  8749. this._renderingDone = false;
  8750. this._canceled = false;
  8751. this._capability = (0, _util.createPromiseCapability)();
  8752. this._renderTimer = null;
  8753. this._bounds = [];
  8754. this._capability.promise.finally(() => {
  8755. if (this._layoutTextCtx) {
  8756. this._layoutTextCtx.canvas.width = 0;
  8757. this._layoutTextCtx.canvas.height = 0;
  8758. this._layoutTextCtx = null;
  8759. }
  8760. }).catch(() => {});
  8761. }
  8762. get promise() {
  8763. return this._capability.promise;
  8764. }
  8765. cancel() {
  8766. this._canceled = true;
  8767. if (this._reader) {
  8768. this._reader.cancel(new _util.AbortException("TextLayer task cancelled."));
  8769. this._reader = null;
  8770. }
  8771. if (this._renderTimer !== null) {
  8772. clearTimeout(this._renderTimer);
  8773. this._renderTimer = null;
  8774. }
  8775. this._capability.reject(new Error("TextLayer task cancelled."));
  8776. }
  8777. _processItems(items, styleCache) {
  8778. for (let i = 0, len = items.length; i < len; i++) {
  8779. if (items[i].str === undefined) {
  8780. if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") {
  8781. const parent = this._container;
  8782. this._container = document.createElement("span");
  8783. this._container.classList.add("markedContent");
  8784. if (items[i].id !== null) {
  8785. this._container.setAttribute("id", `${items[i].id}`);
  8786. }
  8787. parent.appendChild(this._container);
  8788. } else if (items[i].type === "endMarkedContent") {
  8789. this._container = this._container.parentNode;
  8790. }
  8791. continue;
  8792. }
  8793. this._textContentItemsStr.push(items[i].str);
  8794. appendText(this, items[i], styleCache, this._layoutTextCtx);
  8795. }
  8796. }
  8797. _layoutText(textDiv) {
  8798. const textDivProperties = this._textDivProperties.get(textDiv);
  8799. let transform = "";
  8800. if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
  8801. const {
  8802. fontSize,
  8803. fontFamily
  8804. } = textDiv.style;
  8805. if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
  8806. this._layoutTextCtx.font = `${fontSize} ${fontFamily}`;
  8807. this._layoutTextLastFontSize = fontSize;
  8808. this._layoutTextLastFontFamily = fontFamily;
  8809. }
  8810. const {
  8811. width
  8812. } = this._layoutTextCtx.measureText(textDiv.textContent);
  8813. if (width > 0) {
  8814. textDivProperties.scale = textDivProperties.canvasWidth / width;
  8815. transform = `scaleX(${textDivProperties.scale})`;
  8816. }
  8817. }
  8818. if (textDivProperties.angle !== 0) {
  8819. transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
  8820. }
  8821. if (transform.length > 0) {
  8822. if (this._enhanceTextSelection) {
  8823. textDivProperties.originalTransform = transform;
  8824. }
  8825. textDiv.style.transform = transform;
  8826. }
  8827. if (textDivProperties.hasText) {
  8828. this._container.appendChild(textDiv);
  8829. }
  8830. if (textDivProperties.hasEOL) {
  8831. const br = document.createElement("br");
  8832. br.setAttribute("role", "presentation");
  8833. this._container.appendChild(br);
  8834. }
  8835. }
  8836. _render(timeout = 0) {
  8837. const capability = (0, _util.createPromiseCapability)();
  8838. let styleCache = Object.create(null);
  8839. const canvas = this._document.createElement("canvas");
  8840. canvas.height = canvas.width = DEFAULT_FONT_SIZE;
  8841. canvas.mozOpaque = true;
  8842. this._layoutTextCtx = canvas.getContext("2d", {
  8843. alpha: false
  8844. });
  8845. if (this._textContent) {
  8846. const textItems = this._textContent.items;
  8847. const textStyles = this._textContent.styles;
  8848. this._processItems(textItems, textStyles);
  8849. capability.resolve();
  8850. } else if (this._textContentStream) {
  8851. const pump = () => {
  8852. this._reader.read().then(({
  8853. value,
  8854. done
  8855. }) => {
  8856. if (done) {
  8857. capability.resolve();
  8858. return;
  8859. }
  8860. Object.assign(styleCache, value.styles);
  8861. this._processItems(value.items, styleCache);
  8862. pump();
  8863. }, capability.reject);
  8864. };
  8865. this._reader = this._textContentStream.getReader();
  8866. pump();
  8867. } else {
  8868. throw new Error('Neither "textContent" nor "textContentStream"' + " parameters specified.");
  8869. }
  8870. capability.promise.then(() => {
  8871. styleCache = null;
  8872. if (!timeout) {
  8873. render(this);
  8874. } else {
  8875. this._renderTimer = setTimeout(() => {
  8876. render(this);
  8877. this._renderTimer = null;
  8878. }, timeout);
  8879. }
  8880. }, this._capability.reject);
  8881. }
  8882. expandTextDivs(expandDivs = false) {
  8883. if (!this._enhanceTextSelection || !this._renderingDone) {
  8884. return;
  8885. }
  8886. if (this._bounds !== null) {
  8887. expand(this);
  8888. this._bounds = null;
  8889. }
  8890. const transformBuf = [],
  8891. paddingBuf = [];
  8892. for (let i = 0, ii = this._textDivs.length; i < ii; i++) {
  8893. const div = this._textDivs[i];
  8894. const divProps = this._textDivProperties.get(div);
  8895. if (!divProps.hasText) {
  8896. continue;
  8897. }
  8898. if (expandDivs) {
  8899. transformBuf.length = 0;
  8900. paddingBuf.length = 0;
  8901. if (divProps.originalTransform) {
  8902. transformBuf.push(divProps.originalTransform);
  8903. }
  8904. if (divProps.paddingTop > 0) {
  8905. paddingBuf.push(`${divProps.paddingTop}px`);
  8906. transformBuf.push(`translateY(${-divProps.paddingTop}px)`);
  8907. } else {
  8908. paddingBuf.push(0);
  8909. }
  8910. if (divProps.paddingRight > 0) {
  8911. paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`);
  8912. } else {
  8913. paddingBuf.push(0);
  8914. }
  8915. if (divProps.paddingBottom > 0) {
  8916. paddingBuf.push(`${divProps.paddingBottom}px`);
  8917. } else {
  8918. paddingBuf.push(0);
  8919. }
  8920. if (divProps.paddingLeft > 0) {
  8921. paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`);
  8922. transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`);
  8923. } else {
  8924. paddingBuf.push(0);
  8925. }
  8926. div.style.padding = paddingBuf.join(" ");
  8927. if (transformBuf.length) {
  8928. div.style.transform = transformBuf.join(" ");
  8929. }
  8930. } else {
  8931. div.style.padding = null;
  8932. div.style.transform = divProps.originalTransform;
  8933. }
  8934. }
  8935. }
  8936. }
  8937. function renderTextLayer(renderParameters) {
  8938. const task = new TextLayerRenderTask({
  8939. textContent: renderParameters.textContent,
  8940. textContentStream: renderParameters.textContentStream,
  8941. container: renderParameters.container,
  8942. viewport: renderParameters.viewport,
  8943. textDivs: renderParameters.textDivs,
  8944. textContentItemsStr: renderParameters.textContentItemsStr,
  8945. enhanceTextSelection: renderParameters.enhanceTextSelection
  8946. });
  8947. task._render(renderParameters.timeout);
  8948. return task;
  8949. }
  8950. /***/ }),
  8951. /* 20 */
  8952. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8953. Object.defineProperty(exports, "__esModule", ({
  8954. value: true
  8955. }));
  8956. exports.SVGGraphics = void 0;
  8957. var _util = __w_pdfjs_require__(2);
  8958. var _display_utils = __w_pdfjs_require__(1);
  8959. var _is_node = __w_pdfjs_require__(4);
  8960. let SVGGraphics = class {
  8961. constructor() {
  8962. (0, _util.unreachable)("Not implemented: SVGGraphics");
  8963. }
  8964. };
  8965. exports.SVGGraphics = SVGGraphics;
  8966. {
  8967. const SVG_DEFAULTS = {
  8968. fontStyle: "normal",
  8969. fontWeight: "normal",
  8970. fillColor: "#000000"
  8971. };
  8972. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  8973. const XLINK_NS = "http://www.w3.org/1999/xlink";
  8974. const LINE_CAP_STYLES = ["butt", "round", "square"];
  8975. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  8976. const convertImgDataToPng = function () {
  8977. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  8978. const CHUNK_WRAPPER_SIZE = 12;
  8979. const crcTable = new Int32Array(256);
  8980. for (let i = 0; i < 256; i++) {
  8981. let c = i;
  8982. for (let h = 0; h < 8; h++) {
  8983. if (c & 1) {
  8984. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  8985. } else {
  8986. c = c >> 1 & 0x7fffffff;
  8987. }
  8988. }
  8989. crcTable[i] = c;
  8990. }
  8991. function crc32(data, start, end) {
  8992. let crc = -1;
  8993. for (let i = start; i < end; i++) {
  8994. const a = (crc ^ data[i]) & 0xff;
  8995. const b = crcTable[a];
  8996. crc = crc >>> 8 ^ b;
  8997. }
  8998. return crc ^ -1;
  8999. }
  9000. function writePngChunk(type, body, data, offset) {
  9001. let p = offset;
  9002. const len = body.length;
  9003. data[p] = len >> 24 & 0xff;
  9004. data[p + 1] = len >> 16 & 0xff;
  9005. data[p + 2] = len >> 8 & 0xff;
  9006. data[p + 3] = len & 0xff;
  9007. p += 4;
  9008. data[p] = type.charCodeAt(0) & 0xff;
  9009. data[p + 1] = type.charCodeAt(1) & 0xff;
  9010. data[p + 2] = type.charCodeAt(2) & 0xff;
  9011. data[p + 3] = type.charCodeAt(3) & 0xff;
  9012. p += 4;
  9013. data.set(body, p);
  9014. p += body.length;
  9015. const crc = crc32(data, offset + 4, p);
  9016. data[p] = crc >> 24 & 0xff;
  9017. data[p + 1] = crc >> 16 & 0xff;
  9018. data[p + 2] = crc >> 8 & 0xff;
  9019. data[p + 3] = crc & 0xff;
  9020. }
  9021. function adler32(data, start, end) {
  9022. let a = 1;
  9023. let b = 0;
  9024. for (let i = start; i < end; ++i) {
  9025. a = (a + (data[i] & 0xff)) % 65521;
  9026. b = (b + a) % 65521;
  9027. }
  9028. return b << 16 | a;
  9029. }
  9030. function deflateSync(literals) {
  9031. if (!_is_node.isNodeJS) {
  9032. return deflateSyncUncompressed(literals);
  9033. }
  9034. try {
  9035. let input;
  9036. if (parseInt(process.versions.node) >= 8) {
  9037. input = literals;
  9038. } else {
  9039. input = Buffer.from(literals);
  9040. }
  9041. const output = require("zlib").deflateSync(input, {
  9042. level: 9
  9043. });
  9044. return output instanceof Uint8Array ? output : new Uint8Array(output);
  9045. } catch (e) {
  9046. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  9047. }
  9048. return deflateSyncUncompressed(literals);
  9049. }
  9050. function deflateSyncUncompressed(literals) {
  9051. let len = literals.length;
  9052. const maxBlockLength = 0xffff;
  9053. const deflateBlocks = Math.ceil(len / maxBlockLength);
  9054. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  9055. let pi = 0;
  9056. idat[pi++] = 0x78;
  9057. idat[pi++] = 0x9c;
  9058. let pos = 0;
  9059. while (len > maxBlockLength) {
  9060. idat[pi++] = 0x00;
  9061. idat[pi++] = 0xff;
  9062. idat[pi++] = 0xff;
  9063. idat[pi++] = 0x00;
  9064. idat[pi++] = 0x00;
  9065. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  9066. pi += maxBlockLength;
  9067. pos += maxBlockLength;
  9068. len -= maxBlockLength;
  9069. }
  9070. idat[pi++] = 0x01;
  9071. idat[pi++] = len & 0xff;
  9072. idat[pi++] = len >> 8 & 0xff;
  9073. idat[pi++] = ~len & 0xffff & 0xff;
  9074. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  9075. idat.set(literals.subarray(pos), pi);
  9076. pi += literals.length - pos;
  9077. const adler = adler32(literals, 0, literals.length);
  9078. idat[pi++] = adler >> 24 & 0xff;
  9079. idat[pi++] = adler >> 16 & 0xff;
  9080. idat[pi++] = adler >> 8 & 0xff;
  9081. idat[pi++] = adler & 0xff;
  9082. return idat;
  9083. }
  9084. function encode(imgData, kind, forceDataSchema, isMask) {
  9085. const width = imgData.width;
  9086. const height = imgData.height;
  9087. let bitDepth, colorType, lineSize;
  9088. const bytes = imgData.data;
  9089. switch (kind) {
  9090. case _util.ImageKind.GRAYSCALE_1BPP:
  9091. colorType = 0;
  9092. bitDepth = 1;
  9093. lineSize = width + 7 >> 3;
  9094. break;
  9095. case _util.ImageKind.RGB_24BPP:
  9096. colorType = 2;
  9097. bitDepth = 8;
  9098. lineSize = width * 3;
  9099. break;
  9100. case _util.ImageKind.RGBA_32BPP:
  9101. colorType = 6;
  9102. bitDepth = 8;
  9103. lineSize = width * 4;
  9104. break;
  9105. default:
  9106. throw new Error("invalid format");
  9107. }
  9108. const literals = new Uint8Array((1 + lineSize) * height);
  9109. let offsetLiterals = 0,
  9110. offsetBytes = 0;
  9111. for (let y = 0; y < height; ++y) {
  9112. literals[offsetLiterals++] = 0;
  9113. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  9114. offsetBytes += lineSize;
  9115. offsetLiterals += lineSize;
  9116. }
  9117. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  9118. offsetLiterals = 0;
  9119. for (let y = 0; y < height; y++) {
  9120. offsetLiterals++;
  9121. for (let i = 0; i < lineSize; i++) {
  9122. literals[offsetLiterals++] ^= 0xff;
  9123. }
  9124. }
  9125. }
  9126. 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]);
  9127. const idat = deflateSync(literals);
  9128. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  9129. const data = new Uint8Array(pngLength);
  9130. let offset = 0;
  9131. data.set(PNG_HEADER, offset);
  9132. offset += PNG_HEADER.length;
  9133. writePngChunk("IHDR", ihdr, data, offset);
  9134. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  9135. writePngChunk("IDATA", idat, data, offset);
  9136. offset += CHUNK_WRAPPER_SIZE + idat.length;
  9137. writePngChunk("IEND", new Uint8Array(0), data, offset);
  9138. return (0, _util.createObjectURL)(data, "image/png", forceDataSchema);
  9139. }
  9140. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  9141. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  9142. return encode(imgData, kind, forceDataSchema, isMask);
  9143. };
  9144. }();
  9145. class SVGExtraState {
  9146. constructor() {
  9147. this.fontSizeScale = 1;
  9148. this.fontWeight = SVG_DEFAULTS.fontWeight;
  9149. this.fontSize = 0;
  9150. this.textMatrix = _util.IDENTITY_MATRIX;
  9151. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  9152. this.leading = 0;
  9153. this.textRenderingMode = _util.TextRenderingMode.FILL;
  9154. this.textMatrixScale = 1;
  9155. this.x = 0;
  9156. this.y = 0;
  9157. this.lineX = 0;
  9158. this.lineY = 0;
  9159. this.charSpacing = 0;
  9160. this.wordSpacing = 0;
  9161. this.textHScale = 1;
  9162. this.textRise = 0;
  9163. this.fillColor = SVG_DEFAULTS.fillColor;
  9164. this.strokeColor = "#000000";
  9165. this.fillAlpha = 1;
  9166. this.strokeAlpha = 1;
  9167. this.lineWidth = 1;
  9168. this.lineJoin = "";
  9169. this.lineCap = "";
  9170. this.miterLimit = 0;
  9171. this.dashArray = [];
  9172. this.dashPhase = 0;
  9173. this.dependencies = [];
  9174. this.activeClipUrl = null;
  9175. this.clipGroup = null;
  9176. this.maskId = "";
  9177. }
  9178. clone() {
  9179. return Object.create(this);
  9180. }
  9181. setCurrentPoint(x, y) {
  9182. this.x = x;
  9183. this.y = y;
  9184. }
  9185. }
  9186. function opListToTree(opList) {
  9187. let opTree = [];
  9188. const tmp = [];
  9189. for (const opListElement of opList) {
  9190. if (opListElement.fn === "save") {
  9191. opTree.push({
  9192. fnId: 92,
  9193. fn: "group",
  9194. items: []
  9195. });
  9196. tmp.push(opTree);
  9197. opTree = opTree[opTree.length - 1].items;
  9198. continue;
  9199. }
  9200. if (opListElement.fn === "restore") {
  9201. opTree = tmp.pop();
  9202. } else {
  9203. opTree.push(opListElement);
  9204. }
  9205. }
  9206. return opTree;
  9207. }
  9208. function pf(value) {
  9209. if (Number.isInteger(value)) {
  9210. return value.toString();
  9211. }
  9212. const s = value.toFixed(10);
  9213. let i = s.length - 1;
  9214. if (s[i] !== "0") {
  9215. return s;
  9216. }
  9217. do {
  9218. i--;
  9219. } while (s[i] === "0");
  9220. return s.substring(0, s[i] === "." ? i : i + 1);
  9221. }
  9222. function pm(m) {
  9223. if (m[4] === 0 && m[5] === 0) {
  9224. if (m[1] === 0 && m[2] === 0) {
  9225. if (m[0] === 1 && m[3] === 1) {
  9226. return "";
  9227. }
  9228. return `scale(${pf(m[0])} ${pf(m[3])})`;
  9229. }
  9230. if (m[0] === m[3] && m[1] === -m[2]) {
  9231. const a = Math.acos(m[0]) * 180 / Math.PI;
  9232. return `rotate(${pf(a)})`;
  9233. }
  9234. } else {
  9235. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  9236. return `translate(${pf(m[4])} ${pf(m[5])})`;
  9237. }
  9238. }
  9239. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  9240. }
  9241. let clipCount = 0;
  9242. let maskCount = 0;
  9243. let shadingCount = 0;
  9244. exports.SVGGraphics = SVGGraphics = class {
  9245. constructor(commonObjs, objs, forceDataSchema = false) {
  9246. this.svgFactory = new _display_utils.DOMSVGFactory();
  9247. this.current = new SVGExtraState();
  9248. this.transformMatrix = _util.IDENTITY_MATRIX;
  9249. this.transformStack = [];
  9250. this.extraStack = [];
  9251. this.commonObjs = commonObjs;
  9252. this.objs = objs;
  9253. this.pendingClip = null;
  9254. this.pendingEOFill = false;
  9255. this.embedFonts = false;
  9256. this.embeddedFonts = Object.create(null);
  9257. this.cssStyle = null;
  9258. this.forceDataSchema = !!forceDataSchema;
  9259. this._operatorIdMapping = [];
  9260. for (const op in _util.OPS) {
  9261. this._operatorIdMapping[_util.OPS[op]] = op;
  9262. }
  9263. }
  9264. save() {
  9265. this.transformStack.push(this.transformMatrix);
  9266. const old = this.current;
  9267. this.extraStack.push(old);
  9268. this.current = old.clone();
  9269. }
  9270. restore() {
  9271. this.transformMatrix = this.transformStack.pop();
  9272. this.current = this.extraStack.pop();
  9273. this.pendingClip = null;
  9274. this.tgrp = null;
  9275. }
  9276. group(items) {
  9277. this.save();
  9278. this.executeOpTree(items);
  9279. this.restore();
  9280. }
  9281. loadDependencies(operatorList) {
  9282. const fnArray = operatorList.fnArray;
  9283. const argsArray = operatorList.argsArray;
  9284. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  9285. if (fnArray[i] !== _util.OPS.dependency) {
  9286. continue;
  9287. }
  9288. for (const obj of argsArray[i]) {
  9289. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  9290. const promise = new Promise(resolve => {
  9291. objsPool.get(obj, resolve);
  9292. });
  9293. this.current.dependencies.push(promise);
  9294. }
  9295. }
  9296. return Promise.all(this.current.dependencies);
  9297. }
  9298. transform(a, b, c, d, e, f) {
  9299. const transformMatrix = [a, b, c, d, e, f];
  9300. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  9301. this.tgrp = null;
  9302. }
  9303. getSVG(operatorList, viewport) {
  9304. this.viewport = viewport;
  9305. const svgElement = this._initialize(viewport);
  9306. return this.loadDependencies(operatorList).then(() => {
  9307. this.transformMatrix = _util.IDENTITY_MATRIX;
  9308. this.executeOpTree(this.convertOpList(operatorList));
  9309. return svgElement;
  9310. });
  9311. }
  9312. convertOpList(operatorList) {
  9313. const operatorIdMapping = this._operatorIdMapping;
  9314. const argsArray = operatorList.argsArray;
  9315. const fnArray = operatorList.fnArray;
  9316. const opList = [];
  9317. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  9318. const fnId = fnArray[i];
  9319. opList.push({
  9320. fnId,
  9321. fn: operatorIdMapping[fnId],
  9322. args: argsArray[i]
  9323. });
  9324. }
  9325. return opListToTree(opList);
  9326. }
  9327. executeOpTree(opTree) {
  9328. for (const opTreeElement of opTree) {
  9329. const fn = opTreeElement.fn;
  9330. const fnId = opTreeElement.fnId;
  9331. const args = opTreeElement.args;
  9332. switch (fnId | 0) {
  9333. case _util.OPS.beginText:
  9334. this.beginText();
  9335. break;
  9336. case _util.OPS.dependency:
  9337. break;
  9338. case _util.OPS.setLeading:
  9339. this.setLeading(args);
  9340. break;
  9341. case _util.OPS.setLeadingMoveText:
  9342. this.setLeadingMoveText(args[0], args[1]);
  9343. break;
  9344. case _util.OPS.setFont:
  9345. this.setFont(args);
  9346. break;
  9347. case _util.OPS.showText:
  9348. this.showText(args[0]);
  9349. break;
  9350. case _util.OPS.showSpacedText:
  9351. this.showText(args[0]);
  9352. break;
  9353. case _util.OPS.endText:
  9354. this.endText();
  9355. break;
  9356. case _util.OPS.moveText:
  9357. this.moveText(args[0], args[1]);
  9358. break;
  9359. case _util.OPS.setCharSpacing:
  9360. this.setCharSpacing(args[0]);
  9361. break;
  9362. case _util.OPS.setWordSpacing:
  9363. this.setWordSpacing(args[0]);
  9364. break;
  9365. case _util.OPS.setHScale:
  9366. this.setHScale(args[0]);
  9367. break;
  9368. case _util.OPS.setTextMatrix:
  9369. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  9370. break;
  9371. case _util.OPS.setTextRise:
  9372. this.setTextRise(args[0]);
  9373. break;
  9374. case _util.OPS.setTextRenderingMode:
  9375. this.setTextRenderingMode(args[0]);
  9376. break;
  9377. case _util.OPS.setLineWidth:
  9378. this.setLineWidth(args[0]);
  9379. break;
  9380. case _util.OPS.setLineJoin:
  9381. this.setLineJoin(args[0]);
  9382. break;
  9383. case _util.OPS.setLineCap:
  9384. this.setLineCap(args[0]);
  9385. break;
  9386. case _util.OPS.setMiterLimit:
  9387. this.setMiterLimit(args[0]);
  9388. break;
  9389. case _util.OPS.setFillRGBColor:
  9390. this.setFillRGBColor(args[0], args[1], args[2]);
  9391. break;
  9392. case _util.OPS.setStrokeRGBColor:
  9393. this.setStrokeRGBColor(args[0], args[1], args[2]);
  9394. break;
  9395. case _util.OPS.setStrokeColorN:
  9396. this.setStrokeColorN(args);
  9397. break;
  9398. case _util.OPS.setFillColorN:
  9399. this.setFillColorN(args);
  9400. break;
  9401. case _util.OPS.shadingFill:
  9402. this.shadingFill(args[0]);
  9403. break;
  9404. case _util.OPS.setDash:
  9405. this.setDash(args[0], args[1]);
  9406. break;
  9407. case _util.OPS.setRenderingIntent:
  9408. this.setRenderingIntent(args[0]);
  9409. break;
  9410. case _util.OPS.setFlatness:
  9411. this.setFlatness(args[0]);
  9412. break;
  9413. case _util.OPS.setGState:
  9414. this.setGState(args[0]);
  9415. break;
  9416. case _util.OPS.fill:
  9417. this.fill();
  9418. break;
  9419. case _util.OPS.eoFill:
  9420. this.eoFill();
  9421. break;
  9422. case _util.OPS.stroke:
  9423. this.stroke();
  9424. break;
  9425. case _util.OPS.fillStroke:
  9426. this.fillStroke();
  9427. break;
  9428. case _util.OPS.eoFillStroke:
  9429. this.eoFillStroke();
  9430. break;
  9431. case _util.OPS.clip:
  9432. this.clip("nonzero");
  9433. break;
  9434. case _util.OPS.eoClip:
  9435. this.clip("evenodd");
  9436. break;
  9437. case _util.OPS.paintSolidColorImageMask:
  9438. this.paintSolidColorImageMask();
  9439. break;
  9440. case _util.OPS.paintImageXObject:
  9441. this.paintImageXObject(args[0]);
  9442. break;
  9443. case _util.OPS.paintInlineImageXObject:
  9444. this.paintInlineImageXObject(args[0]);
  9445. break;
  9446. case _util.OPS.paintImageMaskXObject:
  9447. this.paintImageMaskXObject(args[0]);
  9448. break;
  9449. case _util.OPS.paintFormXObjectBegin:
  9450. this.paintFormXObjectBegin(args[0], args[1]);
  9451. break;
  9452. case _util.OPS.paintFormXObjectEnd:
  9453. this.paintFormXObjectEnd();
  9454. break;
  9455. case _util.OPS.closePath:
  9456. this.closePath();
  9457. break;
  9458. case _util.OPS.closeStroke:
  9459. this.closeStroke();
  9460. break;
  9461. case _util.OPS.closeFillStroke:
  9462. this.closeFillStroke();
  9463. break;
  9464. case _util.OPS.closeEOFillStroke:
  9465. this.closeEOFillStroke();
  9466. break;
  9467. case _util.OPS.nextLine:
  9468. this.nextLine();
  9469. break;
  9470. case _util.OPS.transform:
  9471. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  9472. break;
  9473. case _util.OPS.constructPath:
  9474. this.constructPath(args[0], args[1]);
  9475. break;
  9476. case _util.OPS.endPath:
  9477. this.endPath();
  9478. break;
  9479. case 92:
  9480. this.group(opTreeElement.items);
  9481. break;
  9482. default:
  9483. (0, _util.warn)(`Unimplemented operator ${fn}`);
  9484. break;
  9485. }
  9486. }
  9487. }
  9488. setWordSpacing(wordSpacing) {
  9489. this.current.wordSpacing = wordSpacing;
  9490. }
  9491. setCharSpacing(charSpacing) {
  9492. this.current.charSpacing = charSpacing;
  9493. }
  9494. nextLine() {
  9495. this.moveText(0, this.current.leading);
  9496. }
  9497. setTextMatrix(a, b, c, d, e, f) {
  9498. const current = this.current;
  9499. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  9500. current.textMatrixScale = Math.hypot(a, b);
  9501. current.x = current.lineX = 0;
  9502. current.y = current.lineY = 0;
  9503. current.xcoords = [];
  9504. current.ycoords = [];
  9505. current.tspan = this.svgFactory.createElement("svg:tspan");
  9506. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  9507. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  9508. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9509. current.txtElement = this.svgFactory.createElement("svg:text");
  9510. current.txtElement.appendChild(current.tspan);
  9511. }
  9512. beginText() {
  9513. const current = this.current;
  9514. current.x = current.lineX = 0;
  9515. current.y = current.lineY = 0;
  9516. current.textMatrix = _util.IDENTITY_MATRIX;
  9517. current.lineMatrix = _util.IDENTITY_MATRIX;
  9518. current.textMatrixScale = 1;
  9519. current.tspan = this.svgFactory.createElement("svg:tspan");
  9520. current.txtElement = this.svgFactory.createElement("svg:text");
  9521. current.txtgrp = this.svgFactory.createElement("svg:g");
  9522. current.xcoords = [];
  9523. current.ycoords = [];
  9524. }
  9525. moveText(x, y) {
  9526. const current = this.current;
  9527. current.x = current.lineX += x;
  9528. current.y = current.lineY += y;
  9529. current.xcoords = [];
  9530. current.ycoords = [];
  9531. current.tspan = this.svgFactory.createElement("svg:tspan");
  9532. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  9533. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  9534. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9535. }
  9536. showText(glyphs) {
  9537. const current = this.current;
  9538. const font = current.font;
  9539. const fontSize = current.fontSize;
  9540. if (fontSize === 0) {
  9541. return;
  9542. }
  9543. const fontSizeScale = current.fontSizeScale;
  9544. const charSpacing = current.charSpacing;
  9545. const wordSpacing = current.wordSpacing;
  9546. const fontDirection = current.fontDirection;
  9547. const textHScale = current.textHScale * fontDirection;
  9548. const vertical = font.vertical;
  9549. const spacingDir = vertical ? 1 : -1;
  9550. const defaultVMetrics = font.defaultVMetrics;
  9551. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  9552. let x = 0;
  9553. for (const glyph of glyphs) {
  9554. if (glyph === null) {
  9555. x += fontDirection * wordSpacing;
  9556. continue;
  9557. } else if ((0, _util.isNum)(glyph)) {
  9558. x += spacingDir * glyph * fontSize / 1000;
  9559. continue;
  9560. }
  9561. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  9562. const character = glyph.fontChar;
  9563. let scaledX, scaledY;
  9564. let width = glyph.width;
  9565. if (vertical) {
  9566. let vx;
  9567. const vmetric = glyph.vmetric || defaultVMetrics;
  9568. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  9569. vx = -vx * widthAdvanceScale;
  9570. const vy = vmetric[2] * widthAdvanceScale;
  9571. width = vmetric ? -vmetric[0] : width;
  9572. scaledX = vx / fontSizeScale;
  9573. scaledY = (x + vy) / fontSizeScale;
  9574. } else {
  9575. scaledX = x / fontSizeScale;
  9576. scaledY = 0;
  9577. }
  9578. if (glyph.isInFont || font.missingFile) {
  9579. current.xcoords.push(current.x + scaledX);
  9580. if (vertical) {
  9581. current.ycoords.push(-current.y + scaledY);
  9582. }
  9583. current.tspan.textContent += character;
  9584. } else {}
  9585. let charWidth;
  9586. if (vertical) {
  9587. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  9588. } else {
  9589. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  9590. }
  9591. x += charWidth;
  9592. }
  9593. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  9594. if (vertical) {
  9595. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  9596. } else {
  9597. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9598. }
  9599. if (vertical) {
  9600. current.y -= x;
  9601. } else {
  9602. current.x += x * textHScale;
  9603. }
  9604. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  9605. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  9606. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  9607. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  9608. }
  9609. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  9610. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  9611. }
  9612. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  9613. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  9614. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  9615. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  9616. }
  9617. if (current.fillAlpha < 1) {
  9618. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  9619. }
  9620. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  9621. current.tspan.setAttributeNS(null, "fill", "transparent");
  9622. } else {
  9623. current.tspan.setAttributeNS(null, "fill", "none");
  9624. }
  9625. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  9626. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  9627. this._setStrokeAttributes(current.tspan, lineWidthScale);
  9628. }
  9629. let textMatrix = current.textMatrix;
  9630. if (current.textRise !== 0) {
  9631. textMatrix = textMatrix.slice();
  9632. textMatrix[5] += current.textRise;
  9633. }
  9634. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  9635. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  9636. current.txtElement.appendChild(current.tspan);
  9637. current.txtgrp.appendChild(current.txtElement);
  9638. this._ensureTransformGroup().appendChild(current.txtElement);
  9639. }
  9640. setLeadingMoveText(x, y) {
  9641. this.setLeading(-y);
  9642. this.moveText(x, y);
  9643. }
  9644. addFontStyle(fontObj) {
  9645. if (!fontObj.data) {
  9646. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  9647. }
  9648. if (!this.cssStyle) {
  9649. this.cssStyle = this.svgFactory.createElement("svg:style");
  9650. this.cssStyle.setAttributeNS(null, "type", "text/css");
  9651. this.defs.appendChild(this.cssStyle);
  9652. }
  9653. const url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  9654. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  9655. }
  9656. setFont(details) {
  9657. const current = this.current;
  9658. const fontObj = this.commonObjs.get(details[0]);
  9659. let size = details[1];
  9660. current.font = fontObj;
  9661. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  9662. this.addFontStyle(fontObj);
  9663. this.embeddedFonts[fontObj.loadedName] = fontObj;
  9664. }
  9665. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  9666. let bold = "normal";
  9667. if (fontObj.black) {
  9668. bold = "900";
  9669. } else if (fontObj.bold) {
  9670. bold = "bold";
  9671. }
  9672. const italic = fontObj.italic ? "italic" : "normal";
  9673. if (size < 0) {
  9674. size = -size;
  9675. current.fontDirection = -1;
  9676. } else {
  9677. current.fontDirection = 1;
  9678. }
  9679. current.fontSize = size;
  9680. current.fontFamily = fontObj.loadedName;
  9681. current.fontWeight = bold;
  9682. current.fontStyle = italic;
  9683. current.tspan = this.svgFactory.createElement("svg:tspan");
  9684. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  9685. current.xcoords = [];
  9686. current.ycoords = [];
  9687. }
  9688. endText() {
  9689. const current = this.current;
  9690. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  9691. current.element = current.txtElement;
  9692. this.clip("nonzero");
  9693. this.endPath();
  9694. }
  9695. }
  9696. setLineWidth(width) {
  9697. if (width > 0) {
  9698. this.current.lineWidth = width;
  9699. }
  9700. }
  9701. setLineCap(style) {
  9702. this.current.lineCap = LINE_CAP_STYLES[style];
  9703. }
  9704. setLineJoin(style) {
  9705. this.current.lineJoin = LINE_JOIN_STYLES[style];
  9706. }
  9707. setMiterLimit(limit) {
  9708. this.current.miterLimit = limit;
  9709. }
  9710. setStrokeAlpha(strokeAlpha) {
  9711. this.current.strokeAlpha = strokeAlpha;
  9712. }
  9713. setStrokeRGBColor(r, g, b) {
  9714. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  9715. }
  9716. setFillAlpha(fillAlpha) {
  9717. this.current.fillAlpha = fillAlpha;
  9718. }
  9719. setFillRGBColor(r, g, b) {
  9720. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  9721. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  9722. this.current.xcoords = [];
  9723. this.current.ycoords = [];
  9724. }
  9725. setStrokeColorN(args) {
  9726. this.current.strokeColor = this._makeColorN_Pattern(args);
  9727. }
  9728. setFillColorN(args) {
  9729. this.current.fillColor = this._makeColorN_Pattern(args);
  9730. }
  9731. shadingFill(args) {
  9732. const width = this.viewport.width;
  9733. const height = this.viewport.height;
  9734. const inv = _util.Util.inverseTransform(this.transformMatrix);
  9735. const bl = _util.Util.applyTransform([0, 0], inv);
  9736. const br = _util.Util.applyTransform([0, height], inv);
  9737. const ul = _util.Util.applyTransform([width, 0], inv);
  9738. const ur = _util.Util.applyTransform([width, height], inv);
  9739. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  9740. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  9741. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  9742. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  9743. const rect = this.svgFactory.createElement("svg:rect");
  9744. rect.setAttributeNS(null, "x", x0);
  9745. rect.setAttributeNS(null, "y", y0);
  9746. rect.setAttributeNS(null, "width", x1 - x0);
  9747. rect.setAttributeNS(null, "height", y1 - y0);
  9748. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  9749. if (this.current.fillAlpha < 1) {
  9750. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  9751. }
  9752. this._ensureTransformGroup().appendChild(rect);
  9753. }
  9754. _makeColorN_Pattern(args) {
  9755. if (args[0] === "TilingPattern") {
  9756. return this._makeTilingPattern(args);
  9757. }
  9758. return this._makeShadingPattern(args);
  9759. }
  9760. _makeTilingPattern(args) {
  9761. const color = args[1];
  9762. const operatorList = args[2];
  9763. const matrix = args[3] || _util.IDENTITY_MATRIX;
  9764. const [x0, y0, x1, y1] = args[4];
  9765. const xstep = args[5];
  9766. const ystep = args[6];
  9767. const paintType = args[7];
  9768. const tilingId = `shading${shadingCount++}`;
  9769. const [tx0, ty0] = _util.Util.applyTransform([x0, y0], matrix);
  9770. const [tx1, ty1] = _util.Util.applyTransform([x1, y1], matrix);
  9771. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  9772. const txstep = xstep * xscale;
  9773. const tystep = ystep * yscale;
  9774. const tiling = this.svgFactory.createElement("svg:pattern");
  9775. tiling.setAttributeNS(null, "id", tilingId);
  9776. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  9777. tiling.setAttributeNS(null, "width", txstep);
  9778. tiling.setAttributeNS(null, "height", tystep);
  9779. tiling.setAttributeNS(null, "x", `${tx0}`);
  9780. tiling.setAttributeNS(null, "y", `${ty0}`);
  9781. const svg = this.svg;
  9782. const transformMatrix = this.transformMatrix;
  9783. const fillColor = this.current.fillColor;
  9784. const strokeColor = this.current.strokeColor;
  9785. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  9786. this.svg = bbox;
  9787. this.transformMatrix = matrix;
  9788. if (paintType === 2) {
  9789. const cssColor = _util.Util.makeHexColor(...color);
  9790. this.current.fillColor = cssColor;
  9791. this.current.strokeColor = cssColor;
  9792. }
  9793. this.executeOpTree(this.convertOpList(operatorList));
  9794. this.svg = svg;
  9795. this.transformMatrix = transformMatrix;
  9796. this.current.fillColor = fillColor;
  9797. this.current.strokeColor = strokeColor;
  9798. tiling.appendChild(bbox.childNodes[0]);
  9799. this.defs.appendChild(tiling);
  9800. return `url(#${tilingId})`;
  9801. }
  9802. _makeShadingPattern(args) {
  9803. switch (args[0]) {
  9804. case "RadialAxial":
  9805. const shadingId = `shading${shadingCount++}`;
  9806. const colorStops = args[3];
  9807. let gradient;
  9808. switch (args[1]) {
  9809. case "axial":
  9810. const point0 = args[4];
  9811. const point1 = args[5];
  9812. gradient = this.svgFactory.createElement("svg:linearGradient");
  9813. gradient.setAttributeNS(null, "id", shadingId);
  9814. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  9815. gradient.setAttributeNS(null, "x1", point0[0]);
  9816. gradient.setAttributeNS(null, "y1", point0[1]);
  9817. gradient.setAttributeNS(null, "x2", point1[0]);
  9818. gradient.setAttributeNS(null, "y2", point1[1]);
  9819. break;
  9820. case "radial":
  9821. const focalPoint = args[4];
  9822. const circlePoint = args[5];
  9823. const focalRadius = args[6];
  9824. const circleRadius = args[7];
  9825. gradient = this.svgFactory.createElement("svg:radialGradient");
  9826. gradient.setAttributeNS(null, "id", shadingId);
  9827. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  9828. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  9829. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  9830. gradient.setAttributeNS(null, "r", circleRadius);
  9831. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  9832. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  9833. gradient.setAttributeNS(null, "fr", focalRadius);
  9834. break;
  9835. default:
  9836. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  9837. }
  9838. for (const colorStop of colorStops) {
  9839. const stop = this.svgFactory.createElement("svg:stop");
  9840. stop.setAttributeNS(null, "offset", colorStop[0]);
  9841. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  9842. gradient.appendChild(stop);
  9843. }
  9844. this.defs.appendChild(gradient);
  9845. return `url(#${shadingId})`;
  9846. case "Mesh":
  9847. (0, _util.warn)("Unimplemented pattern Mesh");
  9848. return null;
  9849. case "Dummy":
  9850. return "hotpink";
  9851. default:
  9852. throw new Error(`Unknown IR type: ${args[0]}`);
  9853. }
  9854. }
  9855. setDash(dashArray, dashPhase) {
  9856. this.current.dashArray = dashArray;
  9857. this.current.dashPhase = dashPhase;
  9858. }
  9859. constructPath(ops, args) {
  9860. const current = this.current;
  9861. let x = current.x,
  9862. y = current.y;
  9863. let d = [];
  9864. let j = 0;
  9865. for (const op of ops) {
  9866. switch (op | 0) {
  9867. case _util.OPS.rectangle:
  9868. x = args[j++];
  9869. y = args[j++];
  9870. const width = args[j++];
  9871. const height = args[j++];
  9872. const xw = x + width;
  9873. const yh = y + height;
  9874. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  9875. break;
  9876. case _util.OPS.moveTo:
  9877. x = args[j++];
  9878. y = args[j++];
  9879. d.push("M", pf(x), pf(y));
  9880. break;
  9881. case _util.OPS.lineTo:
  9882. x = args[j++];
  9883. y = args[j++];
  9884. d.push("L", pf(x), pf(y));
  9885. break;
  9886. case _util.OPS.curveTo:
  9887. x = args[j + 4];
  9888. y = args[j + 5];
  9889. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  9890. j += 6;
  9891. break;
  9892. case _util.OPS.curveTo2:
  9893. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  9894. x = args[j + 2];
  9895. y = args[j + 3];
  9896. j += 4;
  9897. break;
  9898. case _util.OPS.curveTo3:
  9899. x = args[j + 2];
  9900. y = args[j + 3];
  9901. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  9902. j += 4;
  9903. break;
  9904. case _util.OPS.closePath:
  9905. d.push("Z");
  9906. break;
  9907. }
  9908. }
  9909. d = d.join(" ");
  9910. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  9911. d = current.path.getAttributeNS(null, "d") + d;
  9912. } else {
  9913. current.path = this.svgFactory.createElement("svg:path");
  9914. this._ensureTransformGroup().appendChild(current.path);
  9915. }
  9916. current.path.setAttributeNS(null, "d", d);
  9917. current.path.setAttributeNS(null, "fill", "none");
  9918. current.element = current.path;
  9919. current.setCurrentPoint(x, y);
  9920. }
  9921. endPath() {
  9922. const current = this.current;
  9923. current.path = null;
  9924. if (!this.pendingClip) {
  9925. return;
  9926. }
  9927. if (!current.element) {
  9928. this.pendingClip = null;
  9929. return;
  9930. }
  9931. const clipId = `clippath${clipCount++}`;
  9932. const clipPath = this.svgFactory.createElement("svg:clipPath");
  9933. clipPath.setAttributeNS(null, "id", clipId);
  9934. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  9935. const clipElement = current.element.cloneNode(true);
  9936. if (this.pendingClip === "evenodd") {
  9937. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  9938. } else {
  9939. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  9940. }
  9941. this.pendingClip = null;
  9942. clipPath.appendChild(clipElement);
  9943. this.defs.appendChild(clipPath);
  9944. if (current.activeClipUrl) {
  9945. current.clipGroup = null;
  9946. for (const prev of this.extraStack) {
  9947. prev.clipGroup = null;
  9948. }
  9949. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  9950. }
  9951. current.activeClipUrl = `url(#${clipId})`;
  9952. this.tgrp = null;
  9953. }
  9954. clip(type) {
  9955. this.pendingClip = type;
  9956. }
  9957. closePath() {
  9958. const current = this.current;
  9959. if (current.path) {
  9960. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  9961. current.path.setAttributeNS(null, "d", d);
  9962. }
  9963. }
  9964. setLeading(leading) {
  9965. this.current.leading = -leading;
  9966. }
  9967. setTextRise(textRise) {
  9968. this.current.textRise = textRise;
  9969. }
  9970. setTextRenderingMode(textRenderingMode) {
  9971. this.current.textRenderingMode = textRenderingMode;
  9972. }
  9973. setHScale(scale) {
  9974. this.current.textHScale = scale / 100;
  9975. }
  9976. setRenderingIntent(intent) {}
  9977. setFlatness(flatness) {}
  9978. setGState(states) {
  9979. for (const [key, value] of states) {
  9980. switch (key) {
  9981. case "LW":
  9982. this.setLineWidth(value);
  9983. break;
  9984. case "LC":
  9985. this.setLineCap(value);
  9986. break;
  9987. case "LJ":
  9988. this.setLineJoin(value);
  9989. break;
  9990. case "ML":
  9991. this.setMiterLimit(value);
  9992. break;
  9993. case "D":
  9994. this.setDash(value[0], value[1]);
  9995. break;
  9996. case "RI":
  9997. this.setRenderingIntent(value);
  9998. break;
  9999. case "FL":
  10000. this.setFlatness(value);
  10001. break;
  10002. case "Font":
  10003. this.setFont(value);
  10004. break;
  10005. case "CA":
  10006. this.setStrokeAlpha(value);
  10007. break;
  10008. case "ca":
  10009. this.setFillAlpha(value);
  10010. break;
  10011. default:
  10012. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  10013. break;
  10014. }
  10015. }
  10016. }
  10017. fill() {
  10018. const current = this.current;
  10019. if (current.element) {
  10020. current.element.setAttributeNS(null, "fill", current.fillColor);
  10021. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  10022. this.endPath();
  10023. }
  10024. }
  10025. stroke() {
  10026. const current = this.current;
  10027. if (current.element) {
  10028. this._setStrokeAttributes(current.element);
  10029. current.element.setAttributeNS(null, "fill", "none");
  10030. this.endPath();
  10031. }
  10032. }
  10033. _setStrokeAttributes(element, lineWidthScale = 1) {
  10034. const current = this.current;
  10035. let dashArray = current.dashArray;
  10036. if (lineWidthScale !== 1 && dashArray.length > 0) {
  10037. dashArray = dashArray.map(function (value) {
  10038. return lineWidthScale * value;
  10039. });
  10040. }
  10041. element.setAttributeNS(null, "stroke", current.strokeColor);
  10042. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  10043. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  10044. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  10045. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  10046. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  10047. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  10048. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  10049. }
  10050. eoFill() {
  10051. if (this.current.element) {
  10052. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  10053. }
  10054. this.fill();
  10055. }
  10056. fillStroke() {
  10057. this.stroke();
  10058. this.fill();
  10059. }
  10060. eoFillStroke() {
  10061. if (this.current.element) {
  10062. this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
  10063. }
  10064. this.fillStroke();
  10065. }
  10066. closeStroke() {
  10067. this.closePath();
  10068. this.stroke();
  10069. }
  10070. closeFillStroke() {
  10071. this.closePath();
  10072. this.fillStroke();
  10073. }
  10074. closeEOFillStroke() {
  10075. this.closePath();
  10076. this.eoFillStroke();
  10077. }
  10078. paintSolidColorImageMask() {
  10079. const rect = this.svgFactory.createElement("svg:rect");
  10080. rect.setAttributeNS(null, "x", "0");
  10081. rect.setAttributeNS(null, "y", "0");
  10082. rect.setAttributeNS(null, "width", "1px");
  10083. rect.setAttributeNS(null, "height", "1px");
  10084. rect.setAttributeNS(null, "fill", this.current.fillColor);
  10085. this._ensureTransformGroup().appendChild(rect);
  10086. }
  10087. paintImageXObject(objId) {
  10088. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  10089. if (!imgData) {
  10090. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  10091. return;
  10092. }
  10093. this.paintInlineImageXObject(imgData);
  10094. }
  10095. paintInlineImageXObject(imgData, mask) {
  10096. const width = imgData.width;
  10097. const height = imgData.height;
  10098. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  10099. const cliprect = this.svgFactory.createElement("svg:rect");
  10100. cliprect.setAttributeNS(null, "x", "0");
  10101. cliprect.setAttributeNS(null, "y", "0");
  10102. cliprect.setAttributeNS(null, "width", pf(width));
  10103. cliprect.setAttributeNS(null, "height", pf(height));
  10104. this.current.element = cliprect;
  10105. this.clip("nonzero");
  10106. const imgEl = this.svgFactory.createElement("svg:image");
  10107. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  10108. imgEl.setAttributeNS(null, "x", "0");
  10109. imgEl.setAttributeNS(null, "y", pf(-height));
  10110. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  10111. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  10112. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  10113. if (mask) {
  10114. mask.appendChild(imgEl);
  10115. } else {
  10116. this._ensureTransformGroup().appendChild(imgEl);
  10117. }
  10118. }
  10119. paintImageMaskXObject(imgData) {
  10120. const current = this.current;
  10121. const width = imgData.width;
  10122. const height = imgData.height;
  10123. const fillColor = current.fillColor;
  10124. current.maskId = `mask${maskCount++}`;
  10125. const mask = this.svgFactory.createElement("svg:mask");
  10126. mask.setAttributeNS(null, "id", current.maskId);
  10127. const rect = this.svgFactory.createElement("svg:rect");
  10128. rect.setAttributeNS(null, "x", "0");
  10129. rect.setAttributeNS(null, "y", "0");
  10130. rect.setAttributeNS(null, "width", pf(width));
  10131. rect.setAttributeNS(null, "height", pf(height));
  10132. rect.setAttributeNS(null, "fill", fillColor);
  10133. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  10134. this.defs.appendChild(mask);
  10135. this._ensureTransformGroup().appendChild(rect);
  10136. this.paintInlineImageXObject(imgData, mask);
  10137. }
  10138. paintFormXObjectBegin(matrix, bbox) {
  10139. if (Array.isArray(matrix) && matrix.length === 6) {
  10140. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  10141. }
  10142. if (bbox) {
  10143. const width = bbox[2] - bbox[0];
  10144. const height = bbox[3] - bbox[1];
  10145. const cliprect = this.svgFactory.createElement("svg:rect");
  10146. cliprect.setAttributeNS(null, "x", bbox[0]);
  10147. cliprect.setAttributeNS(null, "y", bbox[1]);
  10148. cliprect.setAttributeNS(null, "width", pf(width));
  10149. cliprect.setAttributeNS(null, "height", pf(height));
  10150. this.current.element = cliprect;
  10151. this.clip("nonzero");
  10152. this.endPath();
  10153. }
  10154. }
  10155. paintFormXObjectEnd() {}
  10156. _initialize(viewport) {
  10157. const svg = this.svgFactory.create(viewport.width, viewport.height);
  10158. const definitions = this.svgFactory.createElement("svg:defs");
  10159. svg.appendChild(definitions);
  10160. this.defs = definitions;
  10161. const rootGroup = this.svgFactory.createElement("svg:g");
  10162. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  10163. svg.appendChild(rootGroup);
  10164. this.svg = rootGroup;
  10165. return svg;
  10166. }
  10167. _ensureClipGroup() {
  10168. if (!this.current.clipGroup) {
  10169. const clipGroup = this.svgFactory.createElement("svg:g");
  10170. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  10171. this.svg.appendChild(clipGroup);
  10172. this.current.clipGroup = clipGroup;
  10173. }
  10174. return this.current.clipGroup;
  10175. }
  10176. _ensureTransformGroup() {
  10177. if (!this.tgrp) {
  10178. this.tgrp = this.svgFactory.createElement("svg:g");
  10179. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  10180. if (this.current.activeClipUrl) {
  10181. this._ensureClipGroup().appendChild(this.tgrp);
  10182. } else {
  10183. this.svg.appendChild(this.tgrp);
  10184. }
  10185. }
  10186. return this.tgrp;
  10187. }
  10188. };
  10189. }
  10190. /***/ }),
  10191. /* 21 */
  10192. /***/ ((__unused_webpack_module, exports) => {
  10193. Object.defineProperty(exports, "__esModule", ({
  10194. value: true
  10195. }));
  10196. exports.XfaLayer = void 0;
  10197. class XfaLayer {
  10198. static setupStorage(html, fieldId, element, storage) {
  10199. const storedData = storage.getValue(fieldId, {
  10200. value: null
  10201. });
  10202. switch (element.name) {
  10203. case "textarea":
  10204. html.textContent = storedData.value !== null ? storedData.value : "";
  10205. html.addEventListener("input", event => {
  10206. storage.setValue(fieldId, {
  10207. value: event.target.value
  10208. });
  10209. });
  10210. break;
  10211. case "input":
  10212. if (storedData.value !== null) {
  10213. html.setAttribute("value", storedData.value);
  10214. }
  10215. if (element.attributes.type === "radio") {
  10216. html.addEventListener("change", event => {
  10217. const {
  10218. target
  10219. } = event;
  10220. for (const radio of document.getElementsByName(target.name)) {
  10221. if (radio !== target) {
  10222. const id = radio.id;
  10223. storage.setValue(id.split("-")[0], {
  10224. value: false
  10225. });
  10226. }
  10227. }
  10228. storage.setValue(fieldId, {
  10229. value: target.checked
  10230. });
  10231. });
  10232. } else {
  10233. html.addEventListener("input", event => {
  10234. storage.setValue(fieldId, {
  10235. value: event.target.value
  10236. });
  10237. });
  10238. }
  10239. break;
  10240. case "select":
  10241. if (storedData.value !== null) {
  10242. for (const option of element.children) {
  10243. if (option.attributes.value === storedData.value) {
  10244. option.attributes.selected = true;
  10245. }
  10246. }
  10247. }
  10248. html.addEventListener("input", event => {
  10249. const options = event.target.options;
  10250. const value = options.selectedIndex === -1 ? null : options[options.selectedIndex].value;
  10251. storage.setValue(fieldId, {
  10252. value
  10253. });
  10254. });
  10255. break;
  10256. }
  10257. }
  10258. static setAttributes(html, element, storage) {
  10259. const {
  10260. attributes
  10261. } = element;
  10262. for (const [key, value] of Object.entries(attributes)) {
  10263. if (value === null || value === undefined || key === "fieldId") {
  10264. continue;
  10265. }
  10266. if (key !== "style") {
  10267. if (key === "textContent") {
  10268. html.textContent = value;
  10269. } else {
  10270. html.setAttribute(key, value);
  10271. }
  10272. } else {
  10273. Object.assign(html.style, value);
  10274. }
  10275. }
  10276. if (storage && attributes.fieldId !== undefined) {
  10277. this.setupStorage(html, attributes.fieldId, element, storage);
  10278. }
  10279. }
  10280. static render(parameters) {
  10281. const storage = parameters.annotationStorage;
  10282. const root = parameters.xfa;
  10283. const rootHtml = document.createElement(root.name);
  10284. if (root.attributes) {
  10285. this.setAttributes(rootHtml, root);
  10286. }
  10287. const stack = [[root, -1, rootHtml]];
  10288. const rootDiv = parameters.div;
  10289. rootDiv.appendChild(rootHtml);
  10290. const coeffs = parameters.viewport.transform.join(",");
  10291. rootDiv.style.transform = `matrix(${coeffs})`;
  10292. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  10293. while (stack.length > 0) {
  10294. const [parent, i, html] = stack[stack.length - 1];
  10295. if (i + 1 === parent.children.length) {
  10296. stack.pop();
  10297. continue;
  10298. }
  10299. const child = parent.children[++stack[stack.length - 1][1]];
  10300. if (child === null) {
  10301. continue;
  10302. }
  10303. const {
  10304. name
  10305. } = child;
  10306. if (name === "#text") {
  10307. html.appendChild(document.createTextNode(child.value));
  10308. continue;
  10309. }
  10310. const childHtml = document.createElement(name);
  10311. html.appendChild(childHtml);
  10312. if (child.attributes) {
  10313. this.setAttributes(childHtml, child, storage);
  10314. }
  10315. if (child.children && child.children.length > 0) {
  10316. stack.push([child, -1, childHtml]);
  10317. } else if (child.value) {
  10318. childHtml.appendChild(document.createTextNode(child.value));
  10319. }
  10320. }
  10321. }
  10322. static update(parameters) {
  10323. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  10324. parameters.div.style.transform = transform;
  10325. parameters.div.hidden = false;
  10326. }
  10327. }
  10328. exports.XfaLayer = XfaLayer;
  10329. /***/ }),
  10330. /* 22 */
  10331. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10332. Object.defineProperty(exports, "__esModule", ({
  10333. value: true
  10334. }));
  10335. exports.PDFNodeStream = void 0;
  10336. var _util = __w_pdfjs_require__(2);
  10337. var _network_utils = __w_pdfjs_require__(23);
  10338. ;
  10339. const fs = require("fs");
  10340. const http = require("http");
  10341. const https = require("https");
  10342. const url = require("url");
  10343. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  10344. function parseUrl(sourceUrl) {
  10345. const parsedUrl = url.parse(sourceUrl);
  10346. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  10347. return parsedUrl;
  10348. }
  10349. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  10350. return url.parse(`file:///${sourceUrl}`);
  10351. }
  10352. if (!parsedUrl.host) {
  10353. parsedUrl.protocol = "file:";
  10354. }
  10355. return parsedUrl;
  10356. }
  10357. class PDFNodeStream {
  10358. constructor(source) {
  10359. this.source = source;
  10360. this.url = parseUrl(source.url);
  10361. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  10362. this.isFsUrl = this.url.protocol === "file:";
  10363. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  10364. this._fullRequestReader = null;
  10365. this._rangeRequestReaders = [];
  10366. }
  10367. get _progressiveDataLength() {
  10368. return this._fullRequestReader?._loaded ?? 0;
  10369. }
  10370. getFullReader() {
  10371. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  10372. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  10373. return this._fullRequestReader;
  10374. }
  10375. getRangeReader(start, end) {
  10376. if (end <= this._progressiveDataLength) {
  10377. return null;
  10378. }
  10379. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  10380. this._rangeRequestReaders.push(rangeReader);
  10381. return rangeReader;
  10382. }
  10383. cancelAllRequests(reason) {
  10384. if (this._fullRequestReader) {
  10385. this._fullRequestReader.cancel(reason);
  10386. }
  10387. for (const reader of this._rangeRequestReaders.slice(0)) {
  10388. reader.cancel(reason);
  10389. }
  10390. }
  10391. }
  10392. exports.PDFNodeStream = PDFNodeStream;
  10393. class BaseFullReader {
  10394. constructor(stream) {
  10395. this._url = stream.url;
  10396. this._done = false;
  10397. this._storedError = null;
  10398. this.onProgress = null;
  10399. const source = stream.source;
  10400. this._contentLength = source.length;
  10401. this._loaded = 0;
  10402. this._filename = null;
  10403. this._disableRange = source.disableRange || false;
  10404. this._rangeChunkSize = source.rangeChunkSize;
  10405. if (!this._rangeChunkSize && !this._disableRange) {
  10406. this._disableRange = true;
  10407. }
  10408. this._isStreamingSupported = !source.disableStream;
  10409. this._isRangeSupported = !source.disableRange;
  10410. this._readableStream = null;
  10411. this._readCapability = (0, _util.createPromiseCapability)();
  10412. this._headersCapability = (0, _util.createPromiseCapability)();
  10413. }
  10414. get headersReady() {
  10415. return this._headersCapability.promise;
  10416. }
  10417. get filename() {
  10418. return this._filename;
  10419. }
  10420. get contentLength() {
  10421. return this._contentLength;
  10422. }
  10423. get isRangeSupported() {
  10424. return this._isRangeSupported;
  10425. }
  10426. get isStreamingSupported() {
  10427. return this._isStreamingSupported;
  10428. }
  10429. async read() {
  10430. await this._readCapability.promise;
  10431. if (this._done) {
  10432. return {
  10433. value: undefined,
  10434. done: true
  10435. };
  10436. }
  10437. if (this._storedError) {
  10438. throw this._storedError;
  10439. }
  10440. const chunk = this._readableStream.read();
  10441. if (chunk === null) {
  10442. this._readCapability = (0, _util.createPromiseCapability)();
  10443. return this.read();
  10444. }
  10445. this._loaded += chunk.length;
  10446. if (this.onProgress) {
  10447. this.onProgress({
  10448. loaded: this._loaded,
  10449. total: this._contentLength
  10450. });
  10451. }
  10452. const buffer = new Uint8Array(chunk).buffer;
  10453. return {
  10454. value: buffer,
  10455. done: false
  10456. };
  10457. }
  10458. cancel(reason) {
  10459. if (!this._readableStream) {
  10460. this._error(reason);
  10461. return;
  10462. }
  10463. this._readableStream.destroy(reason);
  10464. }
  10465. _error(reason) {
  10466. this._storedError = reason;
  10467. this._readCapability.resolve();
  10468. }
  10469. _setReadableStream(readableStream) {
  10470. this._readableStream = readableStream;
  10471. readableStream.on("readable", () => {
  10472. this._readCapability.resolve();
  10473. });
  10474. readableStream.on("end", () => {
  10475. readableStream.destroy();
  10476. this._done = true;
  10477. this._readCapability.resolve();
  10478. });
  10479. readableStream.on("error", reason => {
  10480. this._error(reason);
  10481. });
  10482. if (!this._isStreamingSupported && this._isRangeSupported) {
  10483. this._error(new _util.AbortException("streaming is disabled"));
  10484. }
  10485. if (this._storedError) {
  10486. this._readableStream.destroy(this._storedError);
  10487. }
  10488. }
  10489. }
  10490. class BaseRangeReader {
  10491. constructor(stream) {
  10492. this._url = stream.url;
  10493. this._done = false;
  10494. this._storedError = null;
  10495. this.onProgress = null;
  10496. this._loaded = 0;
  10497. this._readableStream = null;
  10498. this._readCapability = (0, _util.createPromiseCapability)();
  10499. const source = stream.source;
  10500. this._isStreamingSupported = !source.disableStream;
  10501. }
  10502. get isStreamingSupported() {
  10503. return this._isStreamingSupported;
  10504. }
  10505. async read() {
  10506. await this._readCapability.promise;
  10507. if (this._done) {
  10508. return {
  10509. value: undefined,
  10510. done: true
  10511. };
  10512. }
  10513. if (this._storedError) {
  10514. throw this._storedError;
  10515. }
  10516. const chunk = this._readableStream.read();
  10517. if (chunk === null) {
  10518. this._readCapability = (0, _util.createPromiseCapability)();
  10519. return this.read();
  10520. }
  10521. this._loaded += chunk.length;
  10522. if (this.onProgress) {
  10523. this.onProgress({
  10524. loaded: this._loaded
  10525. });
  10526. }
  10527. const buffer = new Uint8Array(chunk).buffer;
  10528. return {
  10529. value: buffer,
  10530. done: false
  10531. };
  10532. }
  10533. cancel(reason) {
  10534. if (!this._readableStream) {
  10535. this._error(reason);
  10536. return;
  10537. }
  10538. this._readableStream.destroy(reason);
  10539. }
  10540. _error(reason) {
  10541. this._storedError = reason;
  10542. this._readCapability.resolve();
  10543. }
  10544. _setReadableStream(readableStream) {
  10545. this._readableStream = readableStream;
  10546. readableStream.on("readable", () => {
  10547. this._readCapability.resolve();
  10548. });
  10549. readableStream.on("end", () => {
  10550. readableStream.destroy();
  10551. this._done = true;
  10552. this._readCapability.resolve();
  10553. });
  10554. readableStream.on("error", reason => {
  10555. this._error(reason);
  10556. });
  10557. if (this._storedError) {
  10558. this._readableStream.destroy(this._storedError);
  10559. }
  10560. }
  10561. }
  10562. function createRequestOptions(parsedUrl, headers) {
  10563. return {
  10564. protocol: parsedUrl.protocol,
  10565. auth: parsedUrl.auth,
  10566. host: parsedUrl.hostname,
  10567. port: parsedUrl.port,
  10568. path: parsedUrl.path,
  10569. method: "GET",
  10570. headers
  10571. };
  10572. }
  10573. class PDFNodeStreamFullReader extends BaseFullReader {
  10574. constructor(stream) {
  10575. super(stream);
  10576. const handleResponse = response => {
  10577. if (response.statusCode === 404) {
  10578. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  10579. this._storedError = error;
  10580. this._headersCapability.reject(error);
  10581. return;
  10582. }
  10583. this._headersCapability.resolve();
  10584. this._setReadableStream(response);
  10585. const getResponseHeader = name => {
  10586. return this._readableStream.headers[name.toLowerCase()];
  10587. };
  10588. const {
  10589. allowRangeRequests,
  10590. suggestedLength
  10591. } = (0, _network_utils.validateRangeRequestCapabilities)({
  10592. getResponseHeader,
  10593. isHttp: stream.isHttp,
  10594. rangeChunkSize: this._rangeChunkSize,
  10595. disableRange: this._disableRange
  10596. });
  10597. this._isRangeSupported = allowRangeRequests;
  10598. this._contentLength = suggestedLength || this._contentLength;
  10599. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  10600. };
  10601. this._request = null;
  10602. if (this._url.protocol === "http:") {
  10603. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  10604. } else {
  10605. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  10606. }
  10607. this._request.on("error", reason => {
  10608. this._storedError = reason;
  10609. this._headersCapability.reject(reason);
  10610. });
  10611. this._request.end();
  10612. }
  10613. }
  10614. class PDFNodeStreamRangeReader extends BaseRangeReader {
  10615. constructor(stream, start, end) {
  10616. super(stream);
  10617. this._httpHeaders = {};
  10618. for (const property in stream.httpHeaders) {
  10619. const value = stream.httpHeaders[property];
  10620. if (typeof value === "undefined") {
  10621. continue;
  10622. }
  10623. this._httpHeaders[property] = value;
  10624. }
  10625. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  10626. const handleResponse = response => {
  10627. if (response.statusCode === 404) {
  10628. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  10629. this._storedError = error;
  10630. return;
  10631. }
  10632. this._setReadableStream(response);
  10633. };
  10634. this._request = null;
  10635. if (this._url.protocol === "http:") {
  10636. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  10637. } else {
  10638. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  10639. }
  10640. this._request.on("error", reason => {
  10641. this._storedError = reason;
  10642. });
  10643. this._request.end();
  10644. }
  10645. }
  10646. class PDFNodeStreamFsFullReader extends BaseFullReader {
  10647. constructor(stream) {
  10648. super(stream);
  10649. let path = decodeURIComponent(this._url.path);
  10650. if (fileUriRegex.test(this._url.href)) {
  10651. path = path.replace(/^\//, "");
  10652. }
  10653. fs.lstat(path, (error, stat) => {
  10654. if (error) {
  10655. if (error.code === "ENOENT") {
  10656. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  10657. }
  10658. this._storedError = error;
  10659. this._headersCapability.reject(error);
  10660. return;
  10661. }
  10662. this._contentLength = stat.size;
  10663. this._setReadableStream(fs.createReadStream(path));
  10664. this._headersCapability.resolve();
  10665. });
  10666. }
  10667. }
  10668. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  10669. constructor(stream, start, end) {
  10670. super(stream);
  10671. let path = decodeURIComponent(this._url.path);
  10672. if (fileUriRegex.test(this._url.href)) {
  10673. path = path.replace(/^\//, "");
  10674. }
  10675. this._setReadableStream(fs.createReadStream(path, {
  10676. start,
  10677. end: end - 1
  10678. }));
  10679. }
  10680. }
  10681. /***/ }),
  10682. /* 23 */
  10683. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10684. Object.defineProperty(exports, "__esModule", ({
  10685. value: true
  10686. }));
  10687. exports.createResponseStatusError = createResponseStatusError;
  10688. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  10689. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  10690. exports.validateResponseStatus = validateResponseStatus;
  10691. var _util = __w_pdfjs_require__(2);
  10692. var _content_disposition = __w_pdfjs_require__(24);
  10693. var _display_utils = __w_pdfjs_require__(1);
  10694. function validateRangeRequestCapabilities({
  10695. getResponseHeader,
  10696. isHttp,
  10697. rangeChunkSize,
  10698. disableRange
  10699. }) {
  10700. (0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero");
  10701. const returnValues = {
  10702. allowRangeRequests: false,
  10703. suggestedLength: undefined
  10704. };
  10705. const length = parseInt(getResponseHeader("Content-Length"), 10);
  10706. if (!Number.isInteger(length)) {
  10707. return returnValues;
  10708. }
  10709. returnValues.suggestedLength = length;
  10710. if (length <= 2 * rangeChunkSize) {
  10711. return returnValues;
  10712. }
  10713. if (disableRange || !isHttp) {
  10714. return returnValues;
  10715. }
  10716. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  10717. return returnValues;
  10718. }
  10719. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  10720. if (contentEncoding !== "identity") {
  10721. return returnValues;
  10722. }
  10723. returnValues.allowRangeRequests = true;
  10724. return returnValues;
  10725. }
  10726. function extractFilenameFromHeader(getResponseHeader) {
  10727. const contentDisposition = getResponseHeader("Content-Disposition");
  10728. if (contentDisposition) {
  10729. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  10730. if (filename.includes("%")) {
  10731. try {
  10732. filename = decodeURIComponent(filename);
  10733. } catch (ex) {}
  10734. }
  10735. if ((0, _display_utils.isPdfFile)(filename)) {
  10736. return filename;
  10737. }
  10738. }
  10739. return null;
  10740. }
  10741. function createResponseStatusError(status, url) {
  10742. if (status === 404 || status === 0 && url.startsWith("file:")) {
  10743. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  10744. }
  10745. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  10746. }
  10747. function validateResponseStatus(status) {
  10748. return status === 200 || status === 206;
  10749. }
  10750. /***/ }),
  10751. /* 24 */
  10752. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10753. Object.defineProperty(exports, "__esModule", ({
  10754. value: true
  10755. }));
  10756. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  10757. var _util = __w_pdfjs_require__(2);
  10758. function getFilenameFromContentDispositionHeader(contentDisposition) {
  10759. let needsEncodingFixup = true;
  10760. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  10761. if (tmp) {
  10762. tmp = tmp[1];
  10763. let filename = rfc2616unquote(tmp);
  10764. filename = unescape(filename);
  10765. filename = rfc5987decode(filename);
  10766. filename = rfc2047decode(filename);
  10767. return fixupEncoding(filename);
  10768. }
  10769. tmp = rfc2231getparam(contentDisposition);
  10770. if (tmp) {
  10771. const filename = rfc2047decode(tmp);
  10772. return fixupEncoding(filename);
  10773. }
  10774. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  10775. if (tmp) {
  10776. tmp = tmp[1];
  10777. let filename = rfc2616unquote(tmp);
  10778. filename = rfc2047decode(filename);
  10779. return fixupEncoding(filename);
  10780. }
  10781. function toParamRegExp(attributePattern, flags) {
  10782. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  10783. }
  10784. function textdecode(encoding, value) {
  10785. if (encoding) {
  10786. if (!/^[\x00-\xFF]+$/.test(value)) {
  10787. return value;
  10788. }
  10789. try {
  10790. const decoder = new TextDecoder(encoding, {
  10791. fatal: true
  10792. });
  10793. const buffer = (0, _util.stringToBytes)(value);
  10794. value = decoder.decode(buffer);
  10795. needsEncodingFixup = false;
  10796. } catch (e) {
  10797. if (/^utf-?8$/i.test(encoding)) {
  10798. try {
  10799. value = decodeURIComponent(escape(value));
  10800. needsEncodingFixup = false;
  10801. } catch (err) {}
  10802. }
  10803. }
  10804. }
  10805. return value;
  10806. }
  10807. function fixupEncoding(value) {
  10808. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  10809. value = textdecode("utf-8", value);
  10810. if (needsEncodingFixup) {
  10811. value = textdecode("iso-8859-1", value);
  10812. }
  10813. }
  10814. return value;
  10815. }
  10816. function rfc2231getparam(contentDispositionStr) {
  10817. const matches = [];
  10818. let match;
  10819. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  10820. while ((match = iter.exec(contentDispositionStr)) !== null) {
  10821. let [, n, quot, part] = match;
  10822. n = parseInt(n, 10);
  10823. if (n in matches) {
  10824. if (n === 0) {
  10825. break;
  10826. }
  10827. continue;
  10828. }
  10829. matches[n] = [quot, part];
  10830. }
  10831. const parts = [];
  10832. for (let n = 0; n < matches.length; ++n) {
  10833. if (!(n in matches)) {
  10834. break;
  10835. }
  10836. let [quot, part] = matches[n];
  10837. part = rfc2616unquote(part);
  10838. if (quot) {
  10839. part = unescape(part);
  10840. if (n === 0) {
  10841. part = rfc5987decode(part);
  10842. }
  10843. }
  10844. parts.push(part);
  10845. }
  10846. return parts.join("");
  10847. }
  10848. function rfc2616unquote(value) {
  10849. if (value.startsWith('"')) {
  10850. const parts = value.slice(1).split('\\"');
  10851. for (let i = 0; i < parts.length; ++i) {
  10852. const quotindex = parts[i].indexOf('"');
  10853. if (quotindex !== -1) {
  10854. parts[i] = parts[i].slice(0, quotindex);
  10855. parts.length = i + 1;
  10856. }
  10857. parts[i] = parts[i].replace(/\\(.)/g, "$1");
  10858. }
  10859. value = parts.join('"');
  10860. }
  10861. return value;
  10862. }
  10863. function rfc5987decode(extvalue) {
  10864. const encodingend = extvalue.indexOf("'");
  10865. if (encodingend === -1) {
  10866. return extvalue;
  10867. }
  10868. const encoding = extvalue.slice(0, encodingend);
  10869. const langvalue = extvalue.slice(encodingend + 1);
  10870. const value = langvalue.replace(/^[^']*'/, "");
  10871. return textdecode(encoding, value);
  10872. }
  10873. function rfc2047decode(value) {
  10874. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  10875. return value;
  10876. }
  10877. return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  10878. if (encoding === "q" || encoding === "Q") {
  10879. text = text.replace(/_/g, " ");
  10880. text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  10881. return String.fromCharCode(parseInt(hex, 16));
  10882. });
  10883. return textdecode(charset, text);
  10884. }
  10885. try {
  10886. text = atob(text);
  10887. } catch (e) {}
  10888. return textdecode(charset, text);
  10889. });
  10890. }
  10891. return "";
  10892. }
  10893. /***/ }),
  10894. /* 25 */
  10895. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10896. Object.defineProperty(exports, "__esModule", ({
  10897. value: true
  10898. }));
  10899. exports.PDFNetworkStream = void 0;
  10900. var _util = __w_pdfjs_require__(2);
  10901. var _network_utils = __w_pdfjs_require__(23);
  10902. ;
  10903. const OK_RESPONSE = 200;
  10904. const PARTIAL_CONTENT_RESPONSE = 206;
  10905. function getArrayBuffer(xhr) {
  10906. const data = xhr.response;
  10907. if (typeof data !== "string") {
  10908. return data;
  10909. }
  10910. const array = (0, _util.stringToBytes)(data);
  10911. return array.buffer;
  10912. }
  10913. class NetworkManager {
  10914. constructor(url, args) {
  10915. this.url = url;
  10916. args = args || {};
  10917. this.isHttp = /^https?:/i.test(url);
  10918. this.httpHeaders = this.isHttp && args.httpHeaders || {};
  10919. this.withCredentials = args.withCredentials || false;
  10920. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  10921. return new XMLHttpRequest();
  10922. };
  10923. this.currXhrId = 0;
  10924. this.pendingRequests = Object.create(null);
  10925. }
  10926. requestRange(begin, end, listeners) {
  10927. const args = {
  10928. begin,
  10929. end
  10930. };
  10931. for (const prop in listeners) {
  10932. args[prop] = listeners[prop];
  10933. }
  10934. return this.request(args);
  10935. }
  10936. requestFull(listeners) {
  10937. return this.request(listeners);
  10938. }
  10939. request(args) {
  10940. const xhr = this.getXhr();
  10941. const xhrId = this.currXhrId++;
  10942. const pendingRequest = this.pendingRequests[xhrId] = {
  10943. xhr
  10944. };
  10945. xhr.open("GET", this.url);
  10946. xhr.withCredentials = this.withCredentials;
  10947. for (const property in this.httpHeaders) {
  10948. const value = this.httpHeaders[property];
  10949. if (typeof value === "undefined") {
  10950. continue;
  10951. }
  10952. xhr.setRequestHeader(property, value);
  10953. }
  10954. if (this.isHttp && "begin" in args && "end" in args) {
  10955. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  10956. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  10957. } else {
  10958. pendingRequest.expectedStatus = OK_RESPONSE;
  10959. }
  10960. xhr.responseType = "arraybuffer";
  10961. if (args.onError) {
  10962. xhr.onerror = function (evt) {
  10963. args.onError(xhr.status);
  10964. };
  10965. }
  10966. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  10967. xhr.onprogress = this.onProgress.bind(this, xhrId);
  10968. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  10969. pendingRequest.onDone = args.onDone;
  10970. pendingRequest.onError = args.onError;
  10971. pendingRequest.onProgress = args.onProgress;
  10972. xhr.send(null);
  10973. return xhrId;
  10974. }
  10975. onProgress(xhrId, evt) {
  10976. const pendingRequest = this.pendingRequests[xhrId];
  10977. if (!pendingRequest) {
  10978. return;
  10979. }
  10980. if (pendingRequest.onProgress) {
  10981. pendingRequest.onProgress(evt);
  10982. }
  10983. }
  10984. onStateChange(xhrId, evt) {
  10985. const pendingRequest = this.pendingRequests[xhrId];
  10986. if (!pendingRequest) {
  10987. return;
  10988. }
  10989. const xhr = pendingRequest.xhr;
  10990. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  10991. pendingRequest.onHeadersReceived();
  10992. delete pendingRequest.onHeadersReceived;
  10993. }
  10994. if (xhr.readyState !== 4) {
  10995. return;
  10996. }
  10997. if (!(xhrId in this.pendingRequests)) {
  10998. return;
  10999. }
  11000. delete this.pendingRequests[xhrId];
  11001. if (xhr.status === 0 && this.isHttp) {
  11002. if (pendingRequest.onError) {
  11003. pendingRequest.onError(xhr.status);
  11004. }
  11005. return;
  11006. }
  11007. const xhrStatus = xhr.status || OK_RESPONSE;
  11008. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  11009. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  11010. if (pendingRequest.onError) {
  11011. pendingRequest.onError(xhr.status);
  11012. }
  11013. return;
  11014. }
  11015. const chunk = getArrayBuffer(xhr);
  11016. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  11017. const rangeHeader = xhr.getResponseHeader("Content-Range");
  11018. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  11019. pendingRequest.onDone({
  11020. begin: parseInt(matches[1], 10),
  11021. chunk
  11022. });
  11023. } else if (chunk) {
  11024. pendingRequest.onDone({
  11025. begin: 0,
  11026. chunk
  11027. });
  11028. } else if (pendingRequest.onError) {
  11029. pendingRequest.onError(xhr.status);
  11030. }
  11031. }
  11032. getRequestXhr(xhrId) {
  11033. return this.pendingRequests[xhrId].xhr;
  11034. }
  11035. isPendingRequest(xhrId) {
  11036. return xhrId in this.pendingRequests;
  11037. }
  11038. abortRequest(xhrId) {
  11039. const xhr = this.pendingRequests[xhrId].xhr;
  11040. delete this.pendingRequests[xhrId];
  11041. xhr.abort();
  11042. }
  11043. }
  11044. class PDFNetworkStream {
  11045. constructor(source) {
  11046. this._source = source;
  11047. this._manager = new NetworkManager(source.url, {
  11048. httpHeaders: source.httpHeaders,
  11049. withCredentials: source.withCredentials
  11050. });
  11051. this._rangeChunkSize = source.rangeChunkSize;
  11052. this._fullRequestReader = null;
  11053. this._rangeRequestReaders = [];
  11054. }
  11055. _onRangeRequestReaderClosed(reader) {
  11056. const i = this._rangeRequestReaders.indexOf(reader);
  11057. if (i >= 0) {
  11058. this._rangeRequestReaders.splice(i, 1);
  11059. }
  11060. }
  11061. getFullReader() {
  11062. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  11063. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  11064. return this._fullRequestReader;
  11065. }
  11066. getRangeReader(begin, end) {
  11067. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  11068. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  11069. this._rangeRequestReaders.push(reader);
  11070. return reader;
  11071. }
  11072. cancelAllRequests(reason) {
  11073. if (this._fullRequestReader) {
  11074. this._fullRequestReader.cancel(reason);
  11075. }
  11076. for (const reader of this._rangeRequestReaders.slice(0)) {
  11077. reader.cancel(reason);
  11078. }
  11079. }
  11080. }
  11081. exports.PDFNetworkStream = PDFNetworkStream;
  11082. class PDFNetworkStreamFullRequestReader {
  11083. constructor(manager, source) {
  11084. this._manager = manager;
  11085. const args = {
  11086. onHeadersReceived: this._onHeadersReceived.bind(this),
  11087. onDone: this._onDone.bind(this),
  11088. onError: this._onError.bind(this),
  11089. onProgress: this._onProgress.bind(this)
  11090. };
  11091. this._url = source.url;
  11092. this._fullRequestId = manager.requestFull(args);
  11093. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  11094. this._disableRange = source.disableRange || false;
  11095. this._contentLength = source.length;
  11096. this._rangeChunkSize = source.rangeChunkSize;
  11097. if (!this._rangeChunkSize && !this._disableRange) {
  11098. this._disableRange = true;
  11099. }
  11100. this._isStreamingSupported = false;
  11101. this._isRangeSupported = false;
  11102. this._cachedChunks = [];
  11103. this._requests = [];
  11104. this._done = false;
  11105. this._storedError = undefined;
  11106. this._filename = null;
  11107. this.onProgress = null;
  11108. }
  11109. _onHeadersReceived() {
  11110. const fullRequestXhrId = this._fullRequestId;
  11111. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  11112. const getResponseHeader = name => {
  11113. return fullRequestXhr.getResponseHeader(name);
  11114. };
  11115. const {
  11116. allowRangeRequests,
  11117. suggestedLength
  11118. } = (0, _network_utils.validateRangeRequestCapabilities)({
  11119. getResponseHeader,
  11120. isHttp: this._manager.isHttp,
  11121. rangeChunkSize: this._rangeChunkSize,
  11122. disableRange: this._disableRange
  11123. });
  11124. if (allowRangeRequests) {
  11125. this._isRangeSupported = true;
  11126. }
  11127. this._contentLength = suggestedLength || this._contentLength;
  11128. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  11129. if (this._isRangeSupported) {
  11130. this._manager.abortRequest(fullRequestXhrId);
  11131. }
  11132. this._headersReceivedCapability.resolve();
  11133. }
  11134. _onDone(args) {
  11135. if (args) {
  11136. if (this._requests.length > 0) {
  11137. const requestCapability = this._requests.shift();
  11138. requestCapability.resolve({
  11139. value: args.chunk,
  11140. done: false
  11141. });
  11142. } else {
  11143. this._cachedChunks.push(args.chunk);
  11144. }
  11145. }
  11146. this._done = true;
  11147. if (this._cachedChunks.length > 0) {
  11148. return;
  11149. }
  11150. for (const requestCapability of this._requests) {
  11151. requestCapability.resolve({
  11152. value: undefined,
  11153. done: true
  11154. });
  11155. }
  11156. this._requests.length = 0;
  11157. }
  11158. _onError(status) {
  11159. const url = this._url;
  11160. const exception = (0, _network_utils.createResponseStatusError)(status, url);
  11161. this._storedError = exception;
  11162. this._headersReceivedCapability.reject(exception);
  11163. for (const requestCapability of this._requests) {
  11164. requestCapability.reject(exception);
  11165. }
  11166. this._requests.length = 0;
  11167. this._cachedChunks.length = 0;
  11168. }
  11169. _onProgress(data) {
  11170. if (this.onProgress) {
  11171. this.onProgress({
  11172. loaded: data.loaded,
  11173. total: data.lengthComputable ? data.total : this._contentLength
  11174. });
  11175. }
  11176. }
  11177. get filename() {
  11178. return this._filename;
  11179. }
  11180. get isRangeSupported() {
  11181. return this._isRangeSupported;
  11182. }
  11183. get isStreamingSupported() {
  11184. return this._isStreamingSupported;
  11185. }
  11186. get contentLength() {
  11187. return this._contentLength;
  11188. }
  11189. get headersReady() {
  11190. return this._headersReceivedCapability.promise;
  11191. }
  11192. async read() {
  11193. if (this._storedError) {
  11194. throw this._storedError;
  11195. }
  11196. if (this._cachedChunks.length > 0) {
  11197. const chunk = this._cachedChunks.shift();
  11198. return {
  11199. value: chunk,
  11200. done: false
  11201. };
  11202. }
  11203. if (this._done) {
  11204. return {
  11205. value: undefined,
  11206. done: true
  11207. };
  11208. }
  11209. const requestCapability = (0, _util.createPromiseCapability)();
  11210. this._requests.push(requestCapability);
  11211. return requestCapability.promise;
  11212. }
  11213. cancel(reason) {
  11214. this._done = true;
  11215. this._headersReceivedCapability.reject(reason);
  11216. for (const requestCapability of this._requests) {
  11217. requestCapability.resolve({
  11218. value: undefined,
  11219. done: true
  11220. });
  11221. }
  11222. this._requests.length = 0;
  11223. if (this._manager.isPendingRequest(this._fullRequestId)) {
  11224. this._manager.abortRequest(this._fullRequestId);
  11225. }
  11226. this._fullRequestReader = null;
  11227. }
  11228. }
  11229. class PDFNetworkStreamRangeRequestReader {
  11230. constructor(manager, begin, end) {
  11231. this._manager = manager;
  11232. const args = {
  11233. onDone: this._onDone.bind(this),
  11234. onProgress: this._onProgress.bind(this)
  11235. };
  11236. this._requestId = manager.requestRange(begin, end, args);
  11237. this._requests = [];
  11238. this._queuedChunk = null;
  11239. this._done = false;
  11240. this.onProgress = null;
  11241. this.onClosed = null;
  11242. }
  11243. _close() {
  11244. if (this.onClosed) {
  11245. this.onClosed(this);
  11246. }
  11247. }
  11248. _onDone(data) {
  11249. const chunk = data.chunk;
  11250. if (this._requests.length > 0) {
  11251. const requestCapability = this._requests.shift();
  11252. requestCapability.resolve({
  11253. value: chunk,
  11254. done: false
  11255. });
  11256. } else {
  11257. this._queuedChunk = chunk;
  11258. }
  11259. this._done = true;
  11260. for (const requestCapability of this._requests) {
  11261. requestCapability.resolve({
  11262. value: undefined,
  11263. done: true
  11264. });
  11265. }
  11266. this._requests.length = 0;
  11267. this._close();
  11268. }
  11269. _onProgress(evt) {
  11270. if (!this.isStreamingSupported && this.onProgress) {
  11271. this.onProgress({
  11272. loaded: evt.loaded
  11273. });
  11274. }
  11275. }
  11276. get isStreamingSupported() {
  11277. return false;
  11278. }
  11279. async read() {
  11280. if (this._queuedChunk !== null) {
  11281. const chunk = this._queuedChunk;
  11282. this._queuedChunk = null;
  11283. return {
  11284. value: chunk,
  11285. done: false
  11286. };
  11287. }
  11288. if (this._done) {
  11289. return {
  11290. value: undefined,
  11291. done: true
  11292. };
  11293. }
  11294. const requestCapability = (0, _util.createPromiseCapability)();
  11295. this._requests.push(requestCapability);
  11296. return requestCapability.promise;
  11297. }
  11298. cancel(reason) {
  11299. this._done = true;
  11300. for (const requestCapability of this._requests) {
  11301. requestCapability.resolve({
  11302. value: undefined,
  11303. done: true
  11304. });
  11305. }
  11306. this._requests.length = 0;
  11307. if (this._manager.isPendingRequest(this._requestId)) {
  11308. this._manager.abortRequest(this._requestId);
  11309. }
  11310. this._close();
  11311. }
  11312. }
  11313. /***/ }),
  11314. /* 26 */
  11315. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11316. Object.defineProperty(exports, "__esModule", ({
  11317. value: true
  11318. }));
  11319. exports.PDFFetchStream = void 0;
  11320. var _util = __w_pdfjs_require__(2);
  11321. var _network_utils = __w_pdfjs_require__(23);
  11322. ;
  11323. function createFetchOptions(headers, withCredentials, abortController) {
  11324. return {
  11325. method: "GET",
  11326. headers,
  11327. signal: abortController?.signal,
  11328. mode: "cors",
  11329. credentials: withCredentials ? "include" : "same-origin",
  11330. redirect: "follow"
  11331. };
  11332. }
  11333. function createHeaders(httpHeaders, ispost = false) {
  11334. const headers = new Headers();
  11335. if (ispost) {
  11336. headers.append('Content-type', 'application/json;charset=UTF-8');
  11337. }
  11338. for (const property in httpHeaders) {
  11339. const value = httpHeaders[property];
  11340. if (typeof value === "undefined") {
  11341. continue;
  11342. }
  11343. headers.append(property, value);
  11344. }
  11345. const tgTicket = localStorage.getItem("auth_token");
  11346. if (tgTicket){
  11347. headers.append('token', tgTicket);
  11348. }
  11349. return headers;
  11350. }
  11351. class PDFFetchStream {
  11352. constructor(source) {
  11353. this.source = source;
  11354. this.isHttp = /^https?:/i.test(source.url);
  11355. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  11356. this._fullRequestReader = null;
  11357. this._rangeRequestReaders = [];
  11358. }
  11359. get _progressiveDataLength() {
  11360. return this._fullRequestReader?._loaded ?? 0;
  11361. }
  11362. getFullReader() {
  11363. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  11364. this._fullRequestReader = new PDFFetchStreamReader(this);
  11365. return this._fullRequestReader;
  11366. }
  11367. getRangeReader(begin, end) {
  11368. if (end <= this._progressiveDataLength) {
  11369. return null;
  11370. }
  11371. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  11372. this._rangeRequestReaders.push(reader);
  11373. return reader;
  11374. }
  11375. cancelAllRequests(reason) {
  11376. if (this._fullRequestReader) {
  11377. this._fullRequestReader.cancel(reason);
  11378. }
  11379. for (const reader of this._rangeRequestReaders.slice(0)) {
  11380. reader.cancel(reason);
  11381. }
  11382. }
  11383. }
  11384. exports.PDFFetchStream = PDFFetchStream;
  11385. class PDFFetchStreamReader {
  11386. constructor(stream) {
  11387. this._stream = stream;
  11388. this._reader = null;
  11389. this._loaded = 0;
  11390. this._filename = null;
  11391. const source = stream.source;
  11392. this._withCredentials = source.withCredentials || false;
  11393. this._contentLength = source.length;
  11394. this._headersCapability = (0, _util.createPromiseCapability)();
  11395. this._disableRange = source.disableRange || false;
  11396. this._rangeChunkSize = source.rangeChunkSize;
  11397. if (!this._rangeChunkSize && !this._disableRange) {
  11398. this._disableRange = true;
  11399. }
  11400. if (typeof AbortController !== "undefined") {
  11401. this._abortController = new AbortController();
  11402. }
  11403. this._isStreamingSupported = !source.disableStream;
  11404. this._isRangeSupported = !source.disableRange;
  11405. let url = source.url;
  11406. let isPost = false;
  11407. let body = null;
  11408. if (url.indexOf('?') > 0) {
  11409. const result = url.split('?');
  11410. url = result[0];
  11411. result[1].split('&').map(item => {
  11412. const arr = item.split('=')
  11413. if (arr[0] === 'params' && arr[1]) {
  11414. body = (arr[1] + '').split(',');
  11415. }
  11416. if (arr[0] === 'ispost' && arr[1] == 1) {
  11417. isPost = true;
  11418. }
  11419. })
  11420. }
  11421. this._headers = createHeaders(this._stream.httpHeaders, isPost);
  11422. let option = createFetchOptions(this._headers, this._withCredentials, this._abortController);
  11423. if (isPost) {
  11424. option.body = JSON.stringify(body);
  11425. option.method = "POST";
  11426. }
  11427. fetch(url, option).then(response => {
  11428. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  11429. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  11430. }
  11431. this._reader = response.body.getReader();
  11432. this._headersCapability.resolve();
  11433. const getResponseHeader = name => {
  11434. return response.headers.get(name);
  11435. };
  11436. const {
  11437. allowRangeRequests,
  11438. suggestedLength
  11439. } = (0, _network_utils.validateRangeRequestCapabilities)({
  11440. getResponseHeader,
  11441. isHttp: this._stream.isHttp,
  11442. rangeChunkSize: this._rangeChunkSize,
  11443. disableRange: this._disableRange
  11444. });
  11445. this._isRangeSupported = allowRangeRequests;
  11446. this._contentLength = suggestedLength || this._contentLength;
  11447. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  11448. if (!this._isStreamingSupported && this._isRangeSupported) {
  11449. this.cancel(new _util.AbortException("Streaming is disabled."));
  11450. }
  11451. }).catch(this._headersCapability.reject);
  11452. this.onProgress = null;
  11453. }
  11454. get headersReady() {
  11455. return this._headersCapability.promise;
  11456. }
  11457. get filename() {
  11458. return this._filename;
  11459. }
  11460. get contentLength() {
  11461. return this._contentLength;
  11462. }
  11463. get isRangeSupported() {
  11464. return this._isRangeSupported;
  11465. }
  11466. get isStreamingSupported() {
  11467. return this._isStreamingSupported;
  11468. }
  11469. async read() {
  11470. await this._headersCapability.promise;
  11471. const {
  11472. value,
  11473. done
  11474. } = await this._reader.read();
  11475. if (done) {
  11476. return {
  11477. value,
  11478. done
  11479. };
  11480. }
  11481. this._loaded += value.byteLength;
  11482. if (this.onProgress) {
  11483. this.onProgress({
  11484. loaded: this._loaded,
  11485. total: this._contentLength
  11486. });
  11487. }
  11488. const buffer = new Uint8Array(value).buffer;
  11489. return {
  11490. value: buffer,
  11491. done: false
  11492. };
  11493. }
  11494. cancel(reason) {
  11495. if (this._reader) {
  11496. this._reader.cancel(reason);
  11497. }
  11498. if (this._abortController) {
  11499. this._abortController.abort();
  11500. }
  11501. }
  11502. }
  11503. class PDFFetchStreamRangeReader {
  11504. constructor(stream, begin, end) {
  11505. this._stream = stream;
  11506. this._reader = null;
  11507. this._loaded = 0;
  11508. const source = stream.source;
  11509. this._withCredentials = source.withCredentials || false;
  11510. this._readCapability = (0, _util.createPromiseCapability)();
  11511. this._isStreamingSupported = !source.disableStream;
  11512. if (typeof AbortController !== "undefined") {
  11513. this._abortController = new AbortController();
  11514. }
  11515. this._headers = createHeaders(this._stream.httpHeaders);
  11516. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  11517. const url = source.url;
  11518. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  11519. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  11520. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  11521. }
  11522. this._readCapability.resolve();
  11523. this._reader = response.body.getReader();
  11524. }).catch(reason => {
  11525. if (reason?.name === "AbortError") {
  11526. return;
  11527. }
  11528. throw reason;
  11529. });
  11530. this.onProgress = null;
  11531. }
  11532. get isStreamingSupported() {
  11533. return this._isStreamingSupported;
  11534. }
  11535. async read() {
  11536. await this._readCapability.promise;
  11537. const {
  11538. value,
  11539. done
  11540. } = await this._reader.read();
  11541. if (done) {
  11542. return {
  11543. value,
  11544. done
  11545. };
  11546. }
  11547. this._loaded += value.byteLength;
  11548. if (this.onProgress) {
  11549. this.onProgress({
  11550. loaded: this._loaded
  11551. });
  11552. }
  11553. const buffer = new Uint8Array(value).buffer;
  11554. return {
  11555. value: buffer,
  11556. done: false
  11557. };
  11558. }
  11559. cancel(reason) {
  11560. if (this._reader) {
  11561. this._reader.cancel(reason);
  11562. }
  11563. if (this._abortController) {
  11564. this._abortController.abort();
  11565. }
  11566. }
  11567. }
  11568. /***/ })
  11569. /******/ ]);
  11570. /************************************************************************/
  11571. /******/ // The module cache
  11572. /******/ var __webpack_module_cache__ = {};
  11573. /******/
  11574. /******/ // The require function
  11575. /******/ function __w_pdfjs_require__(moduleId) {
  11576. /******/ // Check if module is in cache
  11577. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  11578. /******/ if (cachedModule !== undefined) {
  11579. /******/ return cachedModule.exports;
  11580. /******/ }
  11581. /******/ // Create a new module (and put it into the cache)
  11582. /******/ var module = __webpack_module_cache__[moduleId] = {
  11583. /******/ // no module.id needed
  11584. /******/ // no module.loaded needed
  11585. /******/ exports: {}
  11586. /******/ };
  11587. /******/
  11588. /******/ // Execute the module function
  11589. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  11590. /******/
  11591. /******/ // Return the exports of the module
  11592. /******/ return module.exports;
  11593. /******/ }
  11594. /******/
  11595. /************************************************************************/
  11596. var __webpack_exports__ = {};
  11597. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  11598. (() => {
  11599. var exports = __webpack_exports__;
  11600. Object.defineProperty(exports, "__esModule", ({
  11601. value: true
  11602. }));
  11603. Object.defineProperty(exports, "addLinkAttributes", ({
  11604. enumerable: true,
  11605. get: function () {
  11606. return _display_utils.addLinkAttributes;
  11607. }
  11608. }));
  11609. Object.defineProperty(exports, "getFilenameFromUrl", ({
  11610. enumerable: true,
  11611. get: function () {
  11612. return _display_utils.getFilenameFromUrl;
  11613. }
  11614. }));
  11615. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  11616. enumerable: true,
  11617. get: function () {
  11618. return _display_utils.getPdfFilenameFromUrl;
  11619. }
  11620. }));
  11621. Object.defineProperty(exports, "isPdfFile", ({
  11622. enumerable: true,
  11623. get: function () {
  11624. return _display_utils.isPdfFile;
  11625. }
  11626. }));
  11627. Object.defineProperty(exports, "LinkTarget", ({
  11628. enumerable: true,
  11629. get: function () {
  11630. return _display_utils.LinkTarget;
  11631. }
  11632. }));
  11633. Object.defineProperty(exports, "loadScript", ({
  11634. enumerable: true,
  11635. get: function () {
  11636. return _display_utils.loadScript;
  11637. }
  11638. }));
  11639. Object.defineProperty(exports, "PDFDateString", ({
  11640. enumerable: true,
  11641. get: function () {
  11642. return _display_utils.PDFDateString;
  11643. }
  11644. }));
  11645. Object.defineProperty(exports, "RenderingCancelledException", ({
  11646. enumerable: true,
  11647. get: function () {
  11648. return _display_utils.RenderingCancelledException;
  11649. }
  11650. }));
  11651. Object.defineProperty(exports, "build", ({
  11652. enumerable: true,
  11653. get: function () {
  11654. return _api.build;
  11655. }
  11656. }));
  11657. Object.defineProperty(exports, "getDocument", ({
  11658. enumerable: true,
  11659. get: function () {
  11660. return _api.getDocument;
  11661. }
  11662. }));
  11663. Object.defineProperty(exports, "LoopbackPort", ({
  11664. enumerable: true,
  11665. get: function () {
  11666. return _api.LoopbackPort;
  11667. }
  11668. }));
  11669. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  11670. enumerable: true,
  11671. get: function () {
  11672. return _api.PDFDataRangeTransport;
  11673. }
  11674. }));
  11675. Object.defineProperty(exports, "PDFWorker", ({
  11676. enumerable: true,
  11677. get: function () {
  11678. return _api.PDFWorker;
  11679. }
  11680. }));
  11681. Object.defineProperty(exports, "version", ({
  11682. enumerable: true,
  11683. get: function () {
  11684. return _api.version;
  11685. }
  11686. }));
  11687. Object.defineProperty(exports, "CMapCompressionType", ({
  11688. enumerable: true,
  11689. get: function () {
  11690. return _util.CMapCompressionType;
  11691. }
  11692. }));
  11693. Object.defineProperty(exports, "createObjectURL", ({
  11694. enumerable: true,
  11695. get: function () {
  11696. return _util.createObjectURL;
  11697. }
  11698. }));
  11699. Object.defineProperty(exports, "createPromiseCapability", ({
  11700. enumerable: true,
  11701. get: function () {
  11702. return _util.createPromiseCapability;
  11703. }
  11704. }));
  11705. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  11706. enumerable: true,
  11707. get: function () {
  11708. return _util.createValidAbsoluteUrl;
  11709. }
  11710. }));
  11711. Object.defineProperty(exports, "InvalidPDFException", ({
  11712. enumerable: true,
  11713. get: function () {
  11714. return _util.InvalidPDFException;
  11715. }
  11716. }));
  11717. Object.defineProperty(exports, "MissingPDFException", ({
  11718. enumerable: true,
  11719. get: function () {
  11720. return _util.MissingPDFException;
  11721. }
  11722. }));
  11723. Object.defineProperty(exports, "OPS", ({
  11724. enumerable: true,
  11725. get: function () {
  11726. return _util.OPS;
  11727. }
  11728. }));
  11729. Object.defineProperty(exports, "PasswordResponses", ({
  11730. enumerable: true,
  11731. get: function () {
  11732. return _util.PasswordResponses;
  11733. }
  11734. }));
  11735. Object.defineProperty(exports, "PermissionFlag", ({
  11736. enumerable: true,
  11737. get: function () {
  11738. return _util.PermissionFlag;
  11739. }
  11740. }));
  11741. Object.defineProperty(exports, "removeNullCharacters", ({
  11742. enumerable: true,
  11743. get: function () {
  11744. return _util.removeNullCharacters;
  11745. }
  11746. }));
  11747. Object.defineProperty(exports, "shadow", ({
  11748. enumerable: true,
  11749. get: function () {
  11750. return _util.shadow;
  11751. }
  11752. }));
  11753. Object.defineProperty(exports, "UnexpectedResponseException", ({
  11754. enumerable: true,
  11755. get: function () {
  11756. return _util.UnexpectedResponseException;
  11757. }
  11758. }));
  11759. Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  11760. enumerable: true,
  11761. get: function () {
  11762. return _util.UNSUPPORTED_FEATURES;
  11763. }
  11764. }));
  11765. Object.defineProperty(exports, "Util", ({
  11766. enumerable: true,
  11767. get: function () {
  11768. return _util.Util;
  11769. }
  11770. }));
  11771. Object.defineProperty(exports, "VerbosityLevel", ({
  11772. enumerable: true,
  11773. get: function () {
  11774. return _util.VerbosityLevel;
  11775. }
  11776. }));
  11777. Object.defineProperty(exports, "AnnotationLayer", ({
  11778. enumerable: true,
  11779. get: function () {
  11780. return _annotation_layer.AnnotationLayer;
  11781. }
  11782. }));
  11783. Object.defineProperty(exports, "apiCompatibilityParams", ({
  11784. enumerable: true,
  11785. get: function () {
  11786. return _api_compatibility.apiCompatibilityParams;
  11787. }
  11788. }));
  11789. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  11790. enumerable: true,
  11791. get: function () {
  11792. return _worker_options.GlobalWorkerOptions;
  11793. }
  11794. }));
  11795. Object.defineProperty(exports, "renderTextLayer", ({
  11796. enumerable: true,
  11797. get: function () {
  11798. return _text_layer.renderTextLayer;
  11799. }
  11800. }));
  11801. Object.defineProperty(exports, "SVGGraphics", ({
  11802. enumerable: true,
  11803. get: function () {
  11804. return _svg.SVGGraphics;
  11805. }
  11806. }));
  11807. Object.defineProperty(exports, "XfaLayer", ({
  11808. enumerable: true,
  11809. get: function () {
  11810. return _xfa_layer.XfaLayer;
  11811. }
  11812. }));
  11813. var _display_utils = __w_pdfjs_require__(1);
  11814. var _api = __w_pdfjs_require__(5);
  11815. var _util = __w_pdfjs_require__(2);
  11816. var _annotation_layer = __w_pdfjs_require__(17);
  11817. var _api_compatibility = __w_pdfjs_require__(9);
  11818. var _worker_options = __w_pdfjs_require__(12);
  11819. var _text_layer = __w_pdfjs_require__(19);
  11820. var _svg = __w_pdfjs_require__(20);
  11821. var _xfa_layer = __w_pdfjs_require__(21);
  11822. const pdfjsVersion = '2.9.359';
  11823. const pdfjsBuild = 'e667c8cbc';
  11824. {
  11825. const {
  11826. isNodeJS
  11827. } = __w_pdfjs_require__(4);
  11828. if (isNodeJS) {
  11829. const PDFNodeStream = __w_pdfjs_require__(22).PDFNodeStream;
  11830. (0, _api.setPDFNetworkStreamFactory)(params => {
  11831. return new PDFNodeStream(params);
  11832. });
  11833. } else {
  11834. const PDFNetworkStream = __w_pdfjs_require__(25).PDFNetworkStream;
  11835. let PDFFetchStream;
  11836. if ((0, _display_utils.isFetchSupported)()) {
  11837. PDFFetchStream = __w_pdfjs_require__(26).PDFFetchStream;
  11838. }
  11839. (0, _api.setPDFNetworkStreamFactory)(params => {
  11840. if (PDFFetchStream && (0, _display_utils.isValidFetchUrl)(params.url)) {
  11841. return new PDFFetchStream(params);
  11842. }
  11843. return new PDFNetworkStream(params);
  11844. });
  11845. }
  11846. }
  11847. })();
  11848. /******/ return __webpack_exports__;
  11849. /******/ })()
  11850. ;
  11851. });
  11852. //# sourceMappingURL=pdf.js.map