evaluator.js 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PartialEvaluator = exports.EvaluatorPreprocessor = void 0;
  27. var _util = require("../shared/util.js");
  28. var _cmap = require("./cmap.js");
  29. var _primitives = require("./primitives.js");
  30. var _fonts = require("./fonts.js");
  31. var _fonts_utils = require("./fonts_utils.js");
  32. var _encodings = require("./encodings.js");
  33. var _standard_fonts = require("./standard_fonts.js");
  34. var _unicode = require("./unicode.js");
  35. var _pattern = require("./pattern.js");
  36. var _xfa_fonts = require("./xfa_fonts.js");
  37. var _to_unicode_map = require("./to_unicode_map.js");
  38. var _function = require("./function.js");
  39. var _parser = require("./parser.js");
  40. var _image_utils = require("./image_utils.js");
  41. var _stream = require("./stream.js");
  42. var _base_stream = require("./base_stream.js");
  43. var _bidi = require("./bidi.js");
  44. var _colorspace = require("./colorspace.js");
  45. var _decode_stream = require("./decode_stream.js");
  46. var _glyphlist = require("./glyphlist.js");
  47. var _core_utils = require("./core_utils.js");
  48. var _metrics = require("./metrics.js");
  49. var _murmurhash = require("../shared/murmurhash3.js");
  50. var _operator_list = require("./operator_list.js");
  51. var _image = require("./image.js");
  52. const DefaultPartialEvaluatorOptions = Object.freeze({
  53. maxImageSize: -1,
  54. disableFontFace: false,
  55. ignoreErrors: false,
  56. isEvalSupported: true,
  57. fontExtraProperties: false,
  58. useSystemFonts: true,
  59. cMapUrl: null,
  60. standardFontDataUrl: null
  61. });
  62. const PatternType = {
  63. TILING: 1,
  64. SHADING: 2
  65. };
  66. const TEXT_CHUNK_BATCH_SIZE = 10;
  67. const deferred = Promise.resolve();
  68. function normalizeBlendMode(value, parsingArray = false) {
  69. if (Array.isArray(value)) {
  70. for (let i = 0, ii = value.length; i < ii; i++) {
  71. const maybeBM = normalizeBlendMode(value[i], true);
  72. if (maybeBM) {
  73. return maybeBM;
  74. }
  75. }
  76. (0, _util.warn)(`Unsupported blend mode Array: ${value}`);
  77. return "source-over";
  78. }
  79. if (!(value instanceof _primitives.Name)) {
  80. if (parsingArray) {
  81. return null;
  82. }
  83. return "source-over";
  84. }
  85. switch (value.name) {
  86. case "Normal":
  87. case "Compatible":
  88. return "source-over";
  89. case "Multiply":
  90. return "multiply";
  91. case "Screen":
  92. return "screen";
  93. case "Overlay":
  94. return "overlay";
  95. case "Darken":
  96. return "darken";
  97. case "Lighten":
  98. return "lighten";
  99. case "ColorDodge":
  100. return "color-dodge";
  101. case "ColorBurn":
  102. return "color-burn";
  103. case "HardLight":
  104. return "hard-light";
  105. case "SoftLight":
  106. return "soft-light";
  107. case "Difference":
  108. return "difference";
  109. case "Exclusion":
  110. return "exclusion";
  111. case "Hue":
  112. return "hue";
  113. case "Saturation":
  114. return "saturation";
  115. case "Color":
  116. return "color";
  117. case "Luminosity":
  118. return "luminosity";
  119. }
  120. if (parsingArray) {
  121. return null;
  122. }
  123. (0, _util.warn)(`Unsupported blend mode: ${value.name}`);
  124. return "source-over";
  125. }
  126. function incrementCachedImageMaskCount(data) {
  127. if (data.fn === _util.OPS.paintImageMaskXObject && data.args[0] && data.args[0].count > 0) {
  128. data.args[0].count++;
  129. }
  130. }
  131. class TimeSlotManager {
  132. static get TIME_SLOT_DURATION_MS() {
  133. return (0, _util.shadow)(this, "TIME_SLOT_DURATION_MS", 20);
  134. }
  135. static get CHECK_TIME_EVERY() {
  136. return (0, _util.shadow)(this, "CHECK_TIME_EVERY", 100);
  137. }
  138. constructor() {
  139. this.reset();
  140. }
  141. check() {
  142. if (++this.checked < TimeSlotManager.CHECK_TIME_EVERY) {
  143. return false;
  144. }
  145. this.checked = 0;
  146. return this.endTime <= Date.now();
  147. }
  148. reset() {
  149. this.endTime = Date.now() + TimeSlotManager.TIME_SLOT_DURATION_MS;
  150. this.checked = 0;
  151. }
  152. }
  153. class PartialEvaluator {
  154. constructor({
  155. xref,
  156. handler,
  157. pageIndex,
  158. idFactory,
  159. fontCache,
  160. builtInCMapCache,
  161. standardFontDataCache,
  162. globalImageCache,
  163. options = null
  164. }) {
  165. this.xref = xref;
  166. this.handler = handler;
  167. this.pageIndex = pageIndex;
  168. this.idFactory = idFactory;
  169. this.fontCache = fontCache;
  170. this.builtInCMapCache = builtInCMapCache;
  171. this.standardFontDataCache = standardFontDataCache;
  172. this.globalImageCache = globalImageCache;
  173. this.options = options || DefaultPartialEvaluatorOptions;
  174. this.parsingType3Font = false;
  175. this._fetchBuiltInCMapBound = this.fetchBuiltInCMap.bind(this);
  176. }
  177. get _pdfFunctionFactory() {
  178. const pdfFunctionFactory = new _function.PDFFunctionFactory({
  179. xref: this.xref,
  180. isEvalSupported: this.options.isEvalSupported
  181. });
  182. return (0, _util.shadow)(this, "_pdfFunctionFactory", pdfFunctionFactory);
  183. }
  184. clone(newOptions = null) {
  185. const newEvaluator = Object.create(this);
  186. newEvaluator.options = Object.assign(Object.create(null), this.options, newOptions);
  187. return newEvaluator;
  188. }
  189. hasBlendModes(resources, nonBlendModesSet) {
  190. if (!(resources instanceof _primitives.Dict)) {
  191. return false;
  192. }
  193. if (resources.objId && nonBlendModesSet.has(resources.objId)) {
  194. return false;
  195. }
  196. const processed = new _primitives.RefSet(nonBlendModesSet);
  197. if (resources.objId) {
  198. processed.put(resources.objId);
  199. }
  200. const nodes = [resources],
  201. xref = this.xref;
  202. while (nodes.length) {
  203. const node = nodes.shift();
  204. const graphicStates = node.get("ExtGState");
  205. if (graphicStates instanceof _primitives.Dict) {
  206. for (let graphicState of graphicStates.getRawValues()) {
  207. if (graphicState instanceof _primitives.Ref) {
  208. if (processed.has(graphicState)) {
  209. continue;
  210. }
  211. try {
  212. graphicState = xref.fetch(graphicState);
  213. } catch (ex) {
  214. processed.put(graphicState);
  215. (0, _util.info)(`hasBlendModes - ignoring ExtGState: "${ex}".`);
  216. continue;
  217. }
  218. }
  219. if (!(graphicState instanceof _primitives.Dict)) {
  220. continue;
  221. }
  222. if (graphicState.objId) {
  223. processed.put(graphicState.objId);
  224. }
  225. const bm = graphicState.get("BM");
  226. if (bm instanceof _primitives.Name) {
  227. if (bm.name !== "Normal") {
  228. return true;
  229. }
  230. continue;
  231. }
  232. if (bm !== undefined && Array.isArray(bm)) {
  233. for (const element of bm) {
  234. if (element instanceof _primitives.Name && element.name !== "Normal") {
  235. return true;
  236. }
  237. }
  238. }
  239. }
  240. }
  241. const xObjects = node.get("XObject");
  242. if (!(xObjects instanceof _primitives.Dict)) {
  243. continue;
  244. }
  245. for (let xObject of xObjects.getRawValues()) {
  246. if (xObject instanceof _primitives.Ref) {
  247. if (processed.has(xObject)) {
  248. continue;
  249. }
  250. try {
  251. xObject = xref.fetch(xObject);
  252. } catch (ex) {
  253. processed.put(xObject);
  254. (0, _util.info)(`hasBlendModes - ignoring XObject: "${ex}".`);
  255. continue;
  256. }
  257. }
  258. if (!(xObject instanceof _base_stream.BaseStream)) {
  259. continue;
  260. }
  261. if (xObject.dict.objId) {
  262. processed.put(xObject.dict.objId);
  263. }
  264. const xResources = xObject.dict.get("Resources");
  265. if (!(xResources instanceof _primitives.Dict)) {
  266. continue;
  267. }
  268. if (xResources.objId && processed.has(xResources.objId)) {
  269. continue;
  270. }
  271. nodes.push(xResources);
  272. if (xResources.objId) {
  273. processed.put(xResources.objId);
  274. }
  275. }
  276. }
  277. for (const ref of processed) {
  278. nonBlendModesSet.put(ref);
  279. }
  280. return false;
  281. }
  282. async fetchBuiltInCMap(name) {
  283. const cachedData = this.builtInCMapCache.get(name);
  284. if (cachedData) {
  285. return cachedData;
  286. }
  287. let data;
  288. if (this.options.cMapUrl !== null) {
  289. const url = `${this.options.cMapUrl}${name}.bcmap`;
  290. const response = await fetch(url);
  291. if (!response.ok) {
  292. throw new Error(`fetchBuiltInCMap: failed to fetch file "${url}" with "${response.statusText}".`);
  293. }
  294. data = {
  295. cMapData: new Uint8Array(await response.arrayBuffer()),
  296. compressionType: _util.CMapCompressionType.BINARY
  297. };
  298. } else {
  299. data = await this.handler.sendWithPromise("FetchBuiltInCMap", {
  300. name
  301. });
  302. }
  303. if (data.compressionType !== _util.CMapCompressionType.NONE) {
  304. this.builtInCMapCache.set(name, data);
  305. }
  306. return data;
  307. }
  308. async fetchStandardFontData(name) {
  309. const cachedData = this.standardFontDataCache.get(name);
  310. if (cachedData) {
  311. return new _stream.Stream(cachedData);
  312. }
  313. if (this.options.useSystemFonts && name !== "Symbol" && name !== "ZapfDingbats") {
  314. return null;
  315. }
  316. const standardFontNameToFileName = (0, _standard_fonts.getFontNameToFileMap)(),
  317. filename = standardFontNameToFileName[name];
  318. let data;
  319. if (this.options.standardFontDataUrl !== null) {
  320. const url = `${this.options.standardFontDataUrl}${filename}`;
  321. const response = await fetch(url);
  322. if (!response.ok) {
  323. (0, _util.warn)(`fetchStandardFontData: failed to fetch file "${url}" with "${response.statusText}".`);
  324. } else {
  325. data = await response.arrayBuffer();
  326. }
  327. } else {
  328. try {
  329. data = await this.handler.sendWithPromise("FetchStandardFontData", {
  330. filename
  331. });
  332. } catch (e) {
  333. (0, _util.warn)(`fetchStandardFontData: failed to fetch file "${filename}" with "${e}".`);
  334. }
  335. }
  336. if (!data) {
  337. return null;
  338. }
  339. this.standardFontDataCache.set(name, data);
  340. return new _stream.Stream(data);
  341. }
  342. async buildFormXObject(resources, xobj, smask, operatorList, task, initialState, localColorSpaceCache) {
  343. const dict = xobj.dict;
  344. const matrix = dict.getArray("Matrix");
  345. let bbox = dict.getArray("BBox");
  346. if (Array.isArray(bbox) && bbox.length === 4) {
  347. bbox = _util.Util.normalizeRect(bbox);
  348. } else {
  349. bbox = null;
  350. }
  351. let optionalContent, groupOptions;
  352. if (dict.has("OC")) {
  353. optionalContent = await this.parseMarkedContentProps(dict.get("OC"), resources);
  354. }
  355. if (optionalContent !== undefined) {
  356. operatorList.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
  357. }
  358. const group = dict.get("Group");
  359. if (group) {
  360. groupOptions = {
  361. matrix,
  362. bbox,
  363. smask,
  364. isolated: false,
  365. knockout: false
  366. };
  367. const groupSubtype = group.get("S");
  368. let colorSpace = null;
  369. if ((0, _primitives.isName)(groupSubtype, "Transparency")) {
  370. groupOptions.isolated = group.get("I") || false;
  371. groupOptions.knockout = group.get("K") || false;
  372. if (group.has("CS")) {
  373. const cs = group.getRaw("CS");
  374. const cachedColorSpace = _colorspace.ColorSpace.getCached(cs, this.xref, localColorSpaceCache);
  375. if (cachedColorSpace) {
  376. colorSpace = cachedColorSpace;
  377. } else {
  378. colorSpace = await this.parseColorSpace({
  379. cs,
  380. resources,
  381. localColorSpaceCache
  382. });
  383. }
  384. }
  385. }
  386. if (smask && smask.backdrop) {
  387. colorSpace = colorSpace || _colorspace.ColorSpace.singletons.rgb;
  388. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  389. }
  390. operatorList.addOp(_util.OPS.beginGroup, [groupOptions]);
  391. }
  392. const args = group ? [matrix, null] : [matrix, bbox];
  393. operatorList.addOp(_util.OPS.paintFormXObjectBegin, args);
  394. return this.getOperatorList({
  395. stream: xobj,
  396. task,
  397. resources: dict.get("Resources") || resources,
  398. operatorList,
  399. initialState
  400. }).then(function () {
  401. operatorList.addOp(_util.OPS.paintFormXObjectEnd, []);
  402. if (group) {
  403. operatorList.addOp(_util.OPS.endGroup, [groupOptions]);
  404. }
  405. if (optionalContent !== undefined) {
  406. operatorList.addOp(_util.OPS.endMarkedContent, []);
  407. }
  408. });
  409. }
  410. _sendImgData(objId, imgData, cacheGlobally = false) {
  411. const transfers = imgData ? [imgData.bitmap || imgData.data.buffer] : null;
  412. if (this.parsingType3Font || cacheGlobally) {
  413. return this.handler.send("commonobj", [objId, "Image", imgData], transfers);
  414. }
  415. return this.handler.send("obj", [objId, this.pageIndex, "Image", imgData], transfers);
  416. }
  417. async buildPaintImageXObject({
  418. resources,
  419. image,
  420. isInline = false,
  421. operatorList,
  422. cacheKey,
  423. localImageCache,
  424. localColorSpaceCache
  425. }) {
  426. const dict = image.dict;
  427. const imageRef = dict.objId;
  428. const w = dict.get("W", "Width");
  429. const h = dict.get("H", "Height");
  430. if (!(w && typeof w === "number") || !(h && typeof h === "number")) {
  431. (0, _util.warn)("Image dimensions are missing, or not numbers.");
  432. return;
  433. }
  434. const maxImageSize = this.options.maxImageSize;
  435. if (maxImageSize !== -1 && w * h > maxImageSize) {
  436. const msg = "Image exceeded maximum allowed size and was removed.";
  437. if (this.options.ignoreErrors) {
  438. (0, _util.warn)(msg);
  439. return;
  440. }
  441. throw new Error(msg);
  442. }
  443. let optionalContent;
  444. if (dict.has("OC")) {
  445. optionalContent = await this.parseMarkedContentProps(dict.get("OC"), resources);
  446. }
  447. const imageMask = dict.get("IM", "ImageMask") || false;
  448. let imgData, args;
  449. if (imageMask) {
  450. const interpolate = dict.get("I", "Interpolate");
  451. const bitStrideLength = w + 7 >> 3;
  452. const imgArray = image.getBytes(bitStrideLength * h);
  453. const decode = dict.getArray("D", "Decode");
  454. if (this.parsingType3Font) {
  455. imgData = _image.PDFImage.createRawMask({
  456. imgArray,
  457. width: w,
  458. height: h,
  459. imageIsFromDecodeStream: image instanceof _decode_stream.DecodeStream,
  460. inverseDecode: !!decode && decode[0] > 0,
  461. interpolate
  462. });
  463. imgData.cached = !!cacheKey;
  464. args = [imgData];
  465. operatorList.addImageOps(_util.OPS.paintImageMaskXObject, args, optionalContent);
  466. if (cacheKey) {
  467. localImageCache.set(cacheKey, imageRef, {
  468. fn: _util.OPS.paintImageMaskXObject,
  469. args,
  470. optionalContent
  471. });
  472. }
  473. return;
  474. }
  475. imgData = _image.PDFImage.createMask({
  476. imgArray,
  477. width: w,
  478. height: h,
  479. imageIsFromDecodeStream: image instanceof _decode_stream.DecodeStream,
  480. inverseDecode: !!decode && decode[0] > 0,
  481. interpolate
  482. });
  483. if (imgData.isSingleOpaquePixel) {
  484. operatorList.addImageOps(_util.OPS.paintSolidColorImageMask, [], optionalContent);
  485. if (cacheKey) {
  486. localImageCache.set(cacheKey, imageRef, {
  487. fn: _util.OPS.paintSolidColorImageMask,
  488. args: [],
  489. optionalContent
  490. });
  491. }
  492. return;
  493. }
  494. const objId = `mask_${this.idFactory.createObjId()}`;
  495. operatorList.addDependency(objId);
  496. this._sendImgData(objId, imgData);
  497. args = [{
  498. data: objId,
  499. width: imgData.width,
  500. height: imgData.height,
  501. interpolate: imgData.interpolate,
  502. count: 1
  503. }];
  504. operatorList.addImageOps(_util.OPS.paintImageMaskXObject, args, optionalContent);
  505. if (cacheKey) {
  506. localImageCache.set(cacheKey, imageRef, {
  507. fn: _util.OPS.paintImageMaskXObject,
  508. args,
  509. optionalContent
  510. });
  511. }
  512. return;
  513. }
  514. const softMask = dict.get("SM", "SMask") || false;
  515. const mask = dict.get("Mask") || false;
  516. const SMALL_IMAGE_DIMENSIONS = 200;
  517. if (isInline && !softMask && !mask && w + h < SMALL_IMAGE_DIMENSIONS) {
  518. const imageObj = new _image.PDFImage({
  519. xref: this.xref,
  520. res: resources,
  521. image,
  522. isInline,
  523. pdfFunctionFactory: this._pdfFunctionFactory,
  524. localColorSpaceCache
  525. });
  526. imgData = imageObj.createImageData(true);
  527. operatorList.addImageOps(_util.OPS.paintInlineImageXObject, [imgData], optionalContent);
  528. return;
  529. }
  530. let objId = `img_${this.idFactory.createObjId()}`,
  531. cacheGlobally = false;
  532. if (this.parsingType3Font) {
  533. objId = `${this.idFactory.getDocId()}_type3_${objId}`;
  534. } else if (imageRef) {
  535. cacheGlobally = this.globalImageCache.shouldCache(imageRef, this.pageIndex);
  536. if (cacheGlobally) {
  537. objId = `${this.idFactory.getDocId()}_${objId}`;
  538. }
  539. }
  540. operatorList.addDependency(objId);
  541. args = [objId, w, h];
  542. _image.PDFImage.buildImage({
  543. xref: this.xref,
  544. res: resources,
  545. image,
  546. isInline,
  547. pdfFunctionFactory: this._pdfFunctionFactory,
  548. localColorSpaceCache
  549. }).then(imageObj => {
  550. imgData = imageObj.createImageData(false);
  551. if (cacheKey && imageRef && cacheGlobally) {
  552. this.globalImageCache.addByteSize(imageRef, imgData.data.length);
  553. }
  554. return this._sendImgData(objId, imgData, cacheGlobally);
  555. }).catch(reason => {
  556. (0, _util.warn)(`Unable to decode image "${objId}": "${reason}".`);
  557. return this._sendImgData(objId, null, cacheGlobally);
  558. });
  559. operatorList.addImageOps(_util.OPS.paintImageXObject, args, optionalContent);
  560. if (cacheKey) {
  561. localImageCache.set(cacheKey, imageRef, {
  562. fn: _util.OPS.paintImageXObject,
  563. args,
  564. optionalContent
  565. });
  566. if (imageRef) {
  567. (0, _util.assert)(!isInline, "Cannot cache an inline image globally.");
  568. this.globalImageCache.addPageIndex(imageRef, this.pageIndex);
  569. if (cacheGlobally) {
  570. this.globalImageCache.setData(imageRef, {
  571. objId,
  572. fn: _util.OPS.paintImageXObject,
  573. args,
  574. optionalContent,
  575. byteSize: 0
  576. });
  577. }
  578. }
  579. }
  580. }
  581. handleSMask(smask, resources, operatorList, task, stateManager, localColorSpaceCache) {
  582. const smaskContent = smask.get("G");
  583. const smaskOptions = {
  584. subtype: smask.get("S").name,
  585. backdrop: smask.get("BC")
  586. };
  587. const transferObj = smask.get("TR");
  588. if ((0, _function.isPDFFunction)(transferObj)) {
  589. const transferFn = this._pdfFunctionFactory.create(transferObj);
  590. const transferMap = new Uint8Array(256);
  591. const tmp = new Float32Array(1);
  592. for (let i = 0; i < 256; i++) {
  593. tmp[0] = i / 255;
  594. transferFn(tmp, 0, tmp, 0);
  595. transferMap[i] = tmp[0] * 255 | 0;
  596. }
  597. smaskOptions.transferMap = transferMap;
  598. }
  599. return this.buildFormXObject(resources, smaskContent, smaskOptions, operatorList, task, stateManager.state.clone(), localColorSpaceCache);
  600. }
  601. handleTransferFunction(tr) {
  602. let transferArray;
  603. if (Array.isArray(tr)) {
  604. transferArray = tr;
  605. } else if ((0, _function.isPDFFunction)(tr)) {
  606. transferArray = [tr];
  607. } else {
  608. return null;
  609. }
  610. const transferMaps = [];
  611. let numFns = 0,
  612. numEffectfulFns = 0;
  613. for (const entry of transferArray) {
  614. const transferObj = this.xref.fetchIfRef(entry);
  615. numFns++;
  616. if ((0, _primitives.isName)(transferObj, "Identity")) {
  617. transferMaps.push(null);
  618. continue;
  619. } else if (!(0, _function.isPDFFunction)(transferObj)) {
  620. return null;
  621. }
  622. const transferFn = this._pdfFunctionFactory.create(transferObj);
  623. const transferMap = new Uint8Array(256),
  624. tmp = new Float32Array(1);
  625. for (let j = 0; j < 256; j++) {
  626. tmp[0] = j / 255;
  627. transferFn(tmp, 0, tmp, 0);
  628. transferMap[j] = tmp[0] * 255 | 0;
  629. }
  630. transferMaps.push(transferMap);
  631. numEffectfulFns++;
  632. }
  633. if (!(numFns === 1 || numFns === 4)) {
  634. return null;
  635. }
  636. if (numEffectfulFns === 0) {
  637. return null;
  638. }
  639. return transferMaps;
  640. }
  641. handleTilingType(fn, color, resources, pattern, patternDict, operatorList, task, localTilingPatternCache) {
  642. const tilingOpList = new _operator_list.OperatorList();
  643. const patternResources = _primitives.Dict.merge({
  644. xref: this.xref,
  645. dictArray: [patternDict.get("Resources"), resources]
  646. });
  647. return this.getOperatorList({
  648. stream: pattern,
  649. task,
  650. resources: patternResources,
  651. operatorList: tilingOpList
  652. }).then(function () {
  653. const operatorListIR = tilingOpList.getIR();
  654. const tilingPatternIR = (0, _pattern.getTilingPatternIR)(operatorListIR, patternDict, color);
  655. operatorList.addDependencies(tilingOpList.dependencies);
  656. operatorList.addOp(fn, tilingPatternIR);
  657. if (patternDict.objId) {
  658. localTilingPatternCache.set(null, patternDict.objId, {
  659. operatorListIR,
  660. dict: patternDict
  661. });
  662. }
  663. }).catch(reason => {
  664. if (reason instanceof _util.AbortException) {
  665. return;
  666. }
  667. if (this.options.ignoreErrors) {
  668. this.handler.send("UnsupportedFeature", {
  669. featureId: _util.UNSUPPORTED_FEATURES.errorTilingPattern
  670. });
  671. (0, _util.warn)(`handleTilingType - ignoring pattern: "${reason}".`);
  672. return;
  673. }
  674. throw reason;
  675. });
  676. }
  677. handleSetFont(resources, fontArgs, fontRef, operatorList, task, state, fallbackFontDict = null, cssFontInfo = null) {
  678. const fontName = fontArgs && fontArgs[0] instanceof _primitives.Name ? fontArgs[0].name : null;
  679. return this.loadFont(fontName, fontRef, resources, fallbackFontDict, cssFontInfo).then(translated => {
  680. if (!translated.font.isType3Font) {
  681. return translated;
  682. }
  683. return translated.loadType3Data(this, resources, task).then(function () {
  684. operatorList.addDependencies(translated.type3Dependencies);
  685. return translated;
  686. }).catch(reason => {
  687. this.handler.send("UnsupportedFeature", {
  688. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadType3
  689. });
  690. return new TranslatedFont({
  691. loadedName: "g_font_error",
  692. font: new _fonts.ErrorFont(`Type3 font load error: ${reason}`),
  693. dict: translated.font,
  694. evaluatorOptions: this.options
  695. });
  696. });
  697. }).then(translated => {
  698. state.font = translated.font;
  699. translated.send(this.handler);
  700. return translated.loadedName;
  701. });
  702. }
  703. handleText(chars, state) {
  704. const font = state.font;
  705. const glyphs = font.charsToGlyphs(chars);
  706. if (font.data) {
  707. const isAddToPathSet = !!(state.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  708. if (isAddToPathSet || state.fillColorSpace.name === "Pattern" || font.disableFontFace || this.options.disableFontFace) {
  709. PartialEvaluator.buildFontPaths(font, glyphs, this.handler, this.options);
  710. }
  711. }
  712. return glyphs;
  713. }
  714. ensureStateFont(state) {
  715. if (state.font) {
  716. return;
  717. }
  718. const reason = new _util.FormatError("Missing setFont (Tf) operator before text rendering operator.");
  719. if (this.options.ignoreErrors) {
  720. this.handler.send("UnsupportedFeature", {
  721. featureId: _util.UNSUPPORTED_FEATURES.errorFontState
  722. });
  723. (0, _util.warn)(`ensureStateFont: "${reason}".`);
  724. return;
  725. }
  726. throw reason;
  727. }
  728. async setGState({
  729. resources,
  730. gState,
  731. operatorList,
  732. cacheKey,
  733. task,
  734. stateManager,
  735. localGStateCache,
  736. localColorSpaceCache
  737. }) {
  738. const gStateRef = gState.objId;
  739. let isSimpleGState = true;
  740. const gStateObj = [];
  741. const gStateKeys = gState.getKeys();
  742. let promise = Promise.resolve();
  743. for (let i = 0, ii = gStateKeys.length; i < ii; i++) {
  744. const key = gStateKeys[i];
  745. const value = gState.get(key);
  746. switch (key) {
  747. case "Type":
  748. break;
  749. case "LW":
  750. case "LC":
  751. case "LJ":
  752. case "ML":
  753. case "D":
  754. case "RI":
  755. case "FL":
  756. case "CA":
  757. case "ca":
  758. gStateObj.push([key, value]);
  759. break;
  760. case "Font":
  761. isSimpleGState = false;
  762. promise = promise.then(() => {
  763. return this.handleSetFont(resources, null, value[0], operatorList, task, stateManager.state).then(function (loadedName) {
  764. operatorList.addDependency(loadedName);
  765. gStateObj.push([key, [loadedName, value[1]]]);
  766. });
  767. });
  768. break;
  769. case "BM":
  770. gStateObj.push([key, normalizeBlendMode(value)]);
  771. break;
  772. case "SMask":
  773. if ((0, _primitives.isName)(value, "None")) {
  774. gStateObj.push([key, false]);
  775. break;
  776. }
  777. if (value instanceof _primitives.Dict) {
  778. isSimpleGState = false;
  779. promise = promise.then(() => {
  780. return this.handleSMask(value, resources, operatorList, task, stateManager, localColorSpaceCache);
  781. });
  782. gStateObj.push([key, true]);
  783. } else {
  784. (0, _util.warn)("Unsupported SMask type");
  785. }
  786. break;
  787. case "TR":
  788. const transferMaps = this.handleTransferFunction(value);
  789. gStateObj.push([key, transferMaps]);
  790. break;
  791. case "OP":
  792. case "op":
  793. case "OPM":
  794. case "BG":
  795. case "BG2":
  796. case "UCR":
  797. case "UCR2":
  798. case "TR2":
  799. case "HT":
  800. case "SM":
  801. case "SA":
  802. case "AIS":
  803. case "TK":
  804. (0, _util.info)("graphic state operator " + key);
  805. break;
  806. default:
  807. (0, _util.info)("Unknown graphic state operator " + key);
  808. break;
  809. }
  810. }
  811. return promise.then(function () {
  812. if (gStateObj.length > 0) {
  813. operatorList.addOp(_util.OPS.setGState, [gStateObj]);
  814. }
  815. if (isSimpleGState) {
  816. localGStateCache.set(cacheKey, gStateRef, gStateObj);
  817. }
  818. });
  819. }
  820. loadFont(fontName, font, resources, fallbackFontDict = null, cssFontInfo = null) {
  821. const errorFont = async () => {
  822. return new TranslatedFont({
  823. loadedName: "g_font_error",
  824. font: new _fonts.ErrorFont(`Font "${fontName}" is not available.`),
  825. dict: font,
  826. evaluatorOptions: this.options
  827. });
  828. };
  829. const xref = this.xref;
  830. let fontRef;
  831. if (font) {
  832. if (font instanceof _primitives.Ref) {
  833. fontRef = font;
  834. }
  835. } else {
  836. const fontRes = resources.get("Font");
  837. if (fontRes) {
  838. fontRef = fontRes.getRaw(fontName);
  839. }
  840. }
  841. if (!fontRef) {
  842. const partialMsg = `Font "${fontName || font && font.toString()}" is not available`;
  843. if (!this.options.ignoreErrors && !this.parsingType3Font) {
  844. (0, _util.warn)(`${partialMsg}.`);
  845. return errorFont();
  846. }
  847. this.handler.send("UnsupportedFeature", {
  848. featureId: _util.UNSUPPORTED_FEATURES.errorFontMissing
  849. });
  850. (0, _util.warn)(`${partialMsg} -- attempting to fallback to a default font.`);
  851. if (fallbackFontDict) {
  852. fontRef = fallbackFontDict;
  853. } else {
  854. fontRef = PartialEvaluator.fallbackFontDict;
  855. }
  856. }
  857. if (this.parsingType3Font && this.type3FontRefs.has(fontRef)) {
  858. return errorFont();
  859. }
  860. if (this.fontCache.has(fontRef)) {
  861. return this.fontCache.get(fontRef);
  862. }
  863. font = xref.fetchIfRef(fontRef);
  864. if (!(font instanceof _primitives.Dict)) {
  865. return errorFont();
  866. }
  867. if (font.cacheKey && this.fontCache.has(font.cacheKey)) {
  868. return this.fontCache.get(font.cacheKey);
  869. }
  870. const fontCapability = (0, _util.createPromiseCapability)();
  871. let preEvaluatedFont;
  872. try {
  873. preEvaluatedFont = this.preEvaluateFont(font);
  874. preEvaluatedFont.cssFontInfo = cssFontInfo;
  875. } catch (reason) {
  876. (0, _util.warn)(`loadFont - preEvaluateFont failed: "${reason}".`);
  877. return errorFont();
  878. }
  879. const {
  880. descriptor,
  881. hash
  882. } = preEvaluatedFont;
  883. const fontRefIsRef = fontRef instanceof _primitives.Ref;
  884. let fontID;
  885. if (fontRefIsRef) {
  886. fontID = `f${fontRef.toString()}`;
  887. }
  888. if (hash && descriptor instanceof _primitives.Dict) {
  889. if (!descriptor.fontAliases) {
  890. descriptor.fontAliases = Object.create(null);
  891. }
  892. const fontAliases = descriptor.fontAliases;
  893. if (fontAliases[hash]) {
  894. const aliasFontRef = fontAliases[hash].aliasRef;
  895. if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
  896. this.fontCache.putAlias(fontRef, aliasFontRef);
  897. return this.fontCache.get(fontRef);
  898. }
  899. } else {
  900. fontAliases[hash] = {
  901. fontID: this.idFactory.createFontId()
  902. };
  903. }
  904. if (fontRefIsRef) {
  905. fontAliases[hash].aliasRef = fontRef;
  906. }
  907. fontID = fontAliases[hash].fontID;
  908. }
  909. if (fontRefIsRef) {
  910. this.fontCache.put(fontRef, fontCapability.promise);
  911. } else {
  912. if (!fontID) {
  913. fontID = this.idFactory.createFontId();
  914. }
  915. font.cacheKey = `cacheKey_${fontID}`;
  916. this.fontCache.put(font.cacheKey, fontCapability.promise);
  917. }
  918. (0, _util.assert)(fontID && fontID.startsWith("f"), 'The "fontID" must be (correctly) defined.');
  919. font.loadedName = `${this.idFactory.getDocId()}_${fontID}`;
  920. this.translateFont(preEvaluatedFont).then(translatedFont => {
  921. if (translatedFont.fontType !== undefined) {
  922. xref.stats.addFontType(translatedFont.fontType);
  923. }
  924. fontCapability.resolve(new TranslatedFont({
  925. loadedName: font.loadedName,
  926. font: translatedFont,
  927. dict: font,
  928. evaluatorOptions: this.options
  929. }));
  930. }).catch(reason => {
  931. this.handler.send("UnsupportedFeature", {
  932. featureId: _util.UNSUPPORTED_FEATURES.errorFontTranslate
  933. });
  934. (0, _util.warn)(`loadFont - translateFont failed: "${reason}".`);
  935. try {
  936. const fontFile3 = descriptor && descriptor.get("FontFile3");
  937. const subtype = fontFile3 && fontFile3.get("Subtype");
  938. const fontType = (0, _fonts_utils.getFontType)(preEvaluatedFont.type, subtype && subtype.name);
  939. if (fontType !== undefined) {
  940. xref.stats.addFontType(fontType);
  941. }
  942. } catch (ex) {}
  943. fontCapability.resolve(new TranslatedFont({
  944. loadedName: font.loadedName,
  945. font: new _fonts.ErrorFont(reason instanceof Error ? reason.message : reason),
  946. dict: font,
  947. evaluatorOptions: this.options
  948. }));
  949. });
  950. return fontCapability.promise;
  951. }
  952. buildPath(operatorList, fn, args, parsingText = false) {
  953. const lastIndex = operatorList.length - 1;
  954. if (!args) {
  955. args = [];
  956. }
  957. let minMax;
  958. if (lastIndex < 0 || operatorList.fnArray[lastIndex] !== _util.OPS.constructPath) {
  959. if (parsingText) {
  960. (0, _util.warn)(`Encountered path operator "${fn}" inside of a text object.`);
  961. operatorList.addOp(_util.OPS.save, null);
  962. }
  963. minMax = [Infinity, -Infinity, Infinity, -Infinity];
  964. operatorList.addOp(_util.OPS.constructPath, [[fn], args, minMax]);
  965. if (parsingText) {
  966. operatorList.addOp(_util.OPS.restore, null);
  967. }
  968. } else {
  969. const opArgs = operatorList.argsArray[lastIndex];
  970. opArgs[0].push(fn);
  971. Array.prototype.push.apply(opArgs[1], args);
  972. minMax = opArgs[2];
  973. }
  974. switch (fn) {
  975. case _util.OPS.rectangle:
  976. minMax[0] = Math.min(minMax[0], args[0], args[0] + args[2]);
  977. minMax[1] = Math.max(minMax[1], args[0], args[0] + args[2]);
  978. minMax[2] = Math.min(minMax[2], args[1], args[1] + args[3]);
  979. minMax[3] = Math.max(minMax[3], args[1], args[1] + args[3]);
  980. break;
  981. case _util.OPS.moveTo:
  982. case _util.OPS.lineTo:
  983. minMax[0] = Math.min(minMax[0], args[0]);
  984. minMax[1] = Math.max(minMax[1], args[0]);
  985. minMax[2] = Math.min(minMax[2], args[1]);
  986. minMax[3] = Math.max(minMax[3], args[1]);
  987. break;
  988. }
  989. }
  990. parseColorSpace({
  991. cs,
  992. resources,
  993. localColorSpaceCache
  994. }) {
  995. return _colorspace.ColorSpace.parseAsync({
  996. cs,
  997. xref: this.xref,
  998. resources,
  999. pdfFunctionFactory: this._pdfFunctionFactory,
  1000. localColorSpaceCache
  1001. }).catch(reason => {
  1002. if (reason instanceof _util.AbortException) {
  1003. return null;
  1004. }
  1005. if (this.options.ignoreErrors) {
  1006. this.handler.send("UnsupportedFeature", {
  1007. featureId: _util.UNSUPPORTED_FEATURES.errorColorSpace
  1008. });
  1009. (0, _util.warn)(`parseColorSpace - ignoring ColorSpace: "${reason}".`);
  1010. return null;
  1011. }
  1012. throw reason;
  1013. });
  1014. }
  1015. parseShading({
  1016. shading,
  1017. resources,
  1018. localColorSpaceCache,
  1019. localShadingPatternCache
  1020. }) {
  1021. let id = localShadingPatternCache.get(shading);
  1022. if (!id) {
  1023. var shadingFill = _pattern.Pattern.parseShading(shading, this.xref, resources, this.handler, this._pdfFunctionFactory, localColorSpaceCache);
  1024. const patternIR = shadingFill.getIR();
  1025. id = `pattern_${this.idFactory.createObjId()}`;
  1026. localShadingPatternCache.set(shading, id);
  1027. this.handler.send("obj", [id, this.pageIndex, "Pattern", patternIR]);
  1028. }
  1029. return id;
  1030. }
  1031. handleColorN(operatorList, fn, args, cs, patterns, resources, task, localColorSpaceCache, localTilingPatternCache, localShadingPatternCache) {
  1032. const patternName = args.pop();
  1033. if (patternName instanceof _primitives.Name) {
  1034. const rawPattern = patterns.getRaw(patternName.name);
  1035. const localTilingPattern = rawPattern instanceof _primitives.Ref && localTilingPatternCache.getByRef(rawPattern);
  1036. if (localTilingPattern) {
  1037. try {
  1038. const color = cs.base ? cs.base.getRgb(args, 0) : null;
  1039. const tilingPatternIR = (0, _pattern.getTilingPatternIR)(localTilingPattern.operatorListIR, localTilingPattern.dict, color);
  1040. operatorList.addOp(fn, tilingPatternIR);
  1041. return undefined;
  1042. } catch (ex) {}
  1043. }
  1044. const pattern = this.xref.fetchIfRef(rawPattern);
  1045. if (pattern) {
  1046. const dict = pattern instanceof _base_stream.BaseStream ? pattern.dict : pattern;
  1047. const typeNum = dict.get("PatternType");
  1048. if (typeNum === PatternType.TILING) {
  1049. const color = cs.base ? cs.base.getRgb(args, 0) : null;
  1050. return this.handleTilingType(fn, color, resources, pattern, dict, operatorList, task, localTilingPatternCache);
  1051. } else if (typeNum === PatternType.SHADING) {
  1052. const shading = dict.get("Shading");
  1053. const matrix = dict.getArray("Matrix");
  1054. const objId = this.parseShading({
  1055. shading,
  1056. resources,
  1057. localColorSpaceCache,
  1058. localShadingPatternCache
  1059. });
  1060. operatorList.addOp(fn, ["Shading", objId, matrix]);
  1061. return undefined;
  1062. }
  1063. throw new _util.FormatError(`Unknown PatternType: ${typeNum}`);
  1064. }
  1065. }
  1066. throw new _util.FormatError(`Unknown PatternName: ${patternName}`);
  1067. }
  1068. _parseVisibilityExpression(array, nestingCounter, currentResult) {
  1069. const MAX_NESTING = 10;
  1070. if (++nestingCounter > MAX_NESTING) {
  1071. (0, _util.warn)("Visibility expression is too deeply nested");
  1072. return;
  1073. }
  1074. const length = array.length;
  1075. const operator = this.xref.fetchIfRef(array[0]);
  1076. if (length < 2 || !(operator instanceof _primitives.Name)) {
  1077. (0, _util.warn)("Invalid visibility expression");
  1078. return;
  1079. }
  1080. switch (operator.name) {
  1081. case "And":
  1082. case "Or":
  1083. case "Not":
  1084. currentResult.push(operator.name);
  1085. break;
  1086. default:
  1087. (0, _util.warn)(`Invalid operator ${operator.name} in visibility expression`);
  1088. return;
  1089. }
  1090. for (let i = 1; i < length; i++) {
  1091. const raw = array[i];
  1092. const object = this.xref.fetchIfRef(raw);
  1093. if (Array.isArray(object)) {
  1094. const nestedResult = [];
  1095. currentResult.push(nestedResult);
  1096. this._parseVisibilityExpression(object, nestingCounter, nestedResult);
  1097. } else if (raw instanceof _primitives.Ref) {
  1098. currentResult.push(raw.toString());
  1099. }
  1100. }
  1101. }
  1102. async parseMarkedContentProps(contentProperties, resources) {
  1103. let optionalContent;
  1104. if (contentProperties instanceof _primitives.Name) {
  1105. const properties = resources.get("Properties");
  1106. optionalContent = properties.get(contentProperties.name);
  1107. } else if (contentProperties instanceof _primitives.Dict) {
  1108. optionalContent = contentProperties;
  1109. } else {
  1110. throw new _util.FormatError("Optional content properties malformed.");
  1111. }
  1112. const optionalContentType = optionalContent.get("Type").name;
  1113. if (optionalContentType === "OCG") {
  1114. return {
  1115. type: optionalContentType,
  1116. id: optionalContent.objId
  1117. };
  1118. } else if (optionalContentType === "OCMD") {
  1119. const expression = optionalContent.get("VE");
  1120. if (Array.isArray(expression)) {
  1121. const result = [];
  1122. this._parseVisibilityExpression(expression, 0, result);
  1123. if (result.length > 0) {
  1124. return {
  1125. type: "OCMD",
  1126. expression: result
  1127. };
  1128. }
  1129. }
  1130. const optionalContentGroups = optionalContent.get("OCGs");
  1131. if (Array.isArray(optionalContentGroups) || optionalContentGroups instanceof _primitives.Dict) {
  1132. const groupIds = [];
  1133. if (Array.isArray(optionalContentGroups)) {
  1134. for (const ocg of optionalContentGroups) {
  1135. groupIds.push(ocg.toString());
  1136. }
  1137. } else {
  1138. groupIds.push(optionalContentGroups.objId);
  1139. }
  1140. return {
  1141. type: optionalContentType,
  1142. ids: groupIds,
  1143. policy: optionalContent.get("P") instanceof _primitives.Name ? optionalContent.get("P").name : null,
  1144. expression: null
  1145. };
  1146. } else if (optionalContentGroups instanceof _primitives.Ref) {
  1147. return {
  1148. type: optionalContentType,
  1149. id: optionalContentGroups.toString()
  1150. };
  1151. }
  1152. }
  1153. return null;
  1154. }
  1155. getOperatorList({
  1156. stream,
  1157. task,
  1158. resources,
  1159. operatorList,
  1160. initialState = null,
  1161. fallbackFontDict = null
  1162. }) {
  1163. resources = resources || _primitives.Dict.empty;
  1164. initialState = initialState || new EvalState();
  1165. if (!operatorList) {
  1166. throw new Error('getOperatorList: missing "operatorList" parameter');
  1167. }
  1168. const self = this;
  1169. const xref = this.xref;
  1170. let parsingText = false;
  1171. const localImageCache = new _image_utils.LocalImageCache();
  1172. const localColorSpaceCache = new _image_utils.LocalColorSpaceCache();
  1173. const localGStateCache = new _image_utils.LocalGStateCache();
  1174. const localTilingPatternCache = new _image_utils.LocalTilingPatternCache();
  1175. const localShadingPatternCache = new Map();
  1176. const xobjs = resources.get("XObject") || _primitives.Dict.empty;
  1177. const patterns = resources.get("Pattern") || _primitives.Dict.empty;
  1178. const stateManager = new StateManager(initialState);
  1179. const preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  1180. const timeSlotManager = new TimeSlotManager();
  1181. function closePendingRestoreOPS(argument) {
  1182. for (let i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  1183. operatorList.addOp(_util.OPS.restore, []);
  1184. }
  1185. }
  1186. return new Promise(function promiseBody(resolve, reject) {
  1187. const next = function (promise) {
  1188. Promise.all([promise, operatorList.ready]).then(function () {
  1189. try {
  1190. promiseBody(resolve, reject);
  1191. } catch (ex) {
  1192. reject(ex);
  1193. }
  1194. }, reject);
  1195. };
  1196. task.ensureNotTerminated();
  1197. timeSlotManager.reset();
  1198. const operation = {};
  1199. let stop, i, ii, cs, name, isValidName;
  1200. while (!(stop = timeSlotManager.check())) {
  1201. operation.args = null;
  1202. if (!preprocessor.read(operation)) {
  1203. break;
  1204. }
  1205. let args = operation.args;
  1206. let fn = operation.fn;
  1207. switch (fn | 0) {
  1208. case _util.OPS.paintXObject:
  1209. isValidName = args[0] instanceof _primitives.Name;
  1210. name = args[0].name;
  1211. if (isValidName) {
  1212. const localImage = localImageCache.getByName(name);
  1213. if (localImage) {
  1214. operatorList.addImageOps(localImage.fn, localImage.args, localImage.optionalContent);
  1215. incrementCachedImageMaskCount(localImage);
  1216. args = null;
  1217. continue;
  1218. }
  1219. }
  1220. next(new Promise(function (resolveXObject, rejectXObject) {
  1221. if (!isValidName) {
  1222. throw new _util.FormatError("XObject must be referred to by name.");
  1223. }
  1224. let xobj = xobjs.getRaw(name);
  1225. if (xobj instanceof _primitives.Ref) {
  1226. const localImage = localImageCache.getByRef(xobj);
  1227. if (localImage) {
  1228. operatorList.addImageOps(localImage.fn, localImage.args, localImage.optionalContent);
  1229. incrementCachedImageMaskCount(localImage);
  1230. resolveXObject();
  1231. return;
  1232. }
  1233. const globalImage = self.globalImageCache.getData(xobj, self.pageIndex);
  1234. if (globalImage) {
  1235. operatorList.addDependency(globalImage.objId);
  1236. operatorList.addImageOps(globalImage.fn, globalImage.args, globalImage.optionalContent);
  1237. resolveXObject();
  1238. return;
  1239. }
  1240. xobj = xref.fetch(xobj);
  1241. }
  1242. if (!(xobj instanceof _base_stream.BaseStream)) {
  1243. throw new _util.FormatError("XObject should be a stream");
  1244. }
  1245. const type = xobj.dict.get("Subtype");
  1246. if (!(type instanceof _primitives.Name)) {
  1247. throw new _util.FormatError("XObject should have a Name subtype");
  1248. }
  1249. if (type.name === "Form") {
  1250. stateManager.save();
  1251. self.buildFormXObject(resources, xobj, null, operatorList, task, stateManager.state.clone(), localColorSpaceCache).then(function () {
  1252. stateManager.restore();
  1253. resolveXObject();
  1254. }, rejectXObject);
  1255. return;
  1256. } else if (type.name === "Image") {
  1257. self.buildPaintImageXObject({
  1258. resources,
  1259. image: xobj,
  1260. operatorList,
  1261. cacheKey: name,
  1262. localImageCache,
  1263. localColorSpaceCache
  1264. }).then(resolveXObject, rejectXObject);
  1265. return;
  1266. } else if (type.name === "PS") {
  1267. (0, _util.info)("Ignored XObject subtype PS");
  1268. } else {
  1269. throw new _util.FormatError(`Unhandled XObject subtype ${type.name}`);
  1270. }
  1271. resolveXObject();
  1272. }).catch(function (reason) {
  1273. if (reason instanceof _util.AbortException) {
  1274. return;
  1275. }
  1276. if (self.options.ignoreErrors) {
  1277. self.handler.send("UnsupportedFeature", {
  1278. featureId: _util.UNSUPPORTED_FEATURES.errorXObject
  1279. });
  1280. (0, _util.warn)(`getOperatorList - ignoring XObject: "${reason}".`);
  1281. return;
  1282. }
  1283. throw reason;
  1284. }));
  1285. return;
  1286. case _util.OPS.setFont:
  1287. var fontSize = args[1];
  1288. next(self.handleSetFont(resources, args, null, operatorList, task, stateManager.state, fallbackFontDict).then(function (loadedName) {
  1289. operatorList.addDependency(loadedName);
  1290. operatorList.addOp(_util.OPS.setFont, [loadedName, fontSize]);
  1291. }));
  1292. return;
  1293. case _util.OPS.beginText:
  1294. parsingText = true;
  1295. break;
  1296. case _util.OPS.endText:
  1297. parsingText = false;
  1298. break;
  1299. case _util.OPS.endInlineImage:
  1300. var cacheKey = args[0].cacheKey;
  1301. if (cacheKey) {
  1302. const localImage = localImageCache.getByName(cacheKey);
  1303. if (localImage) {
  1304. operatorList.addImageOps(localImage.fn, localImage.args, localImage.optionalContent);
  1305. incrementCachedImageMaskCount(localImage);
  1306. args = null;
  1307. continue;
  1308. }
  1309. }
  1310. next(self.buildPaintImageXObject({
  1311. resources,
  1312. image: args[0],
  1313. isInline: true,
  1314. operatorList,
  1315. cacheKey,
  1316. localImageCache,
  1317. localColorSpaceCache
  1318. }));
  1319. return;
  1320. case _util.OPS.showText:
  1321. if (!stateManager.state.font) {
  1322. self.ensureStateFont(stateManager.state);
  1323. continue;
  1324. }
  1325. args[0] = self.handleText(args[0], stateManager.state);
  1326. break;
  1327. case _util.OPS.showSpacedText:
  1328. if (!stateManager.state.font) {
  1329. self.ensureStateFont(stateManager.state);
  1330. continue;
  1331. }
  1332. var arr = args[0];
  1333. var combinedGlyphs = [];
  1334. var arrLength = arr.length;
  1335. var state = stateManager.state;
  1336. for (i = 0; i < arrLength; ++i) {
  1337. const arrItem = arr[i];
  1338. if (typeof arrItem === "string") {
  1339. Array.prototype.push.apply(combinedGlyphs, self.handleText(arrItem, state));
  1340. } else if (typeof arrItem === "number") {
  1341. combinedGlyphs.push(arrItem);
  1342. }
  1343. }
  1344. args[0] = combinedGlyphs;
  1345. fn = _util.OPS.showText;
  1346. break;
  1347. case _util.OPS.nextLineShowText:
  1348. if (!stateManager.state.font) {
  1349. self.ensureStateFont(stateManager.state);
  1350. continue;
  1351. }
  1352. operatorList.addOp(_util.OPS.nextLine);
  1353. args[0] = self.handleText(args[0], stateManager.state);
  1354. fn = _util.OPS.showText;
  1355. break;
  1356. case _util.OPS.nextLineSetSpacingShowText:
  1357. if (!stateManager.state.font) {
  1358. self.ensureStateFont(stateManager.state);
  1359. continue;
  1360. }
  1361. operatorList.addOp(_util.OPS.nextLine);
  1362. operatorList.addOp(_util.OPS.setWordSpacing, [args.shift()]);
  1363. operatorList.addOp(_util.OPS.setCharSpacing, [args.shift()]);
  1364. args[0] = self.handleText(args[0], stateManager.state);
  1365. fn = _util.OPS.showText;
  1366. break;
  1367. case _util.OPS.setTextRenderingMode:
  1368. stateManager.state.textRenderingMode = args[0];
  1369. break;
  1370. case _util.OPS.setFillColorSpace:
  1371. {
  1372. const cachedColorSpace = _colorspace.ColorSpace.getCached(args[0], xref, localColorSpaceCache);
  1373. if (cachedColorSpace) {
  1374. stateManager.state.fillColorSpace = cachedColorSpace;
  1375. continue;
  1376. }
  1377. next(self.parseColorSpace({
  1378. cs: args[0],
  1379. resources,
  1380. localColorSpaceCache
  1381. }).then(function (colorSpace) {
  1382. if (colorSpace) {
  1383. stateManager.state.fillColorSpace = colorSpace;
  1384. }
  1385. }));
  1386. return;
  1387. }
  1388. case _util.OPS.setStrokeColorSpace:
  1389. {
  1390. const cachedColorSpace = _colorspace.ColorSpace.getCached(args[0], xref, localColorSpaceCache);
  1391. if (cachedColorSpace) {
  1392. stateManager.state.strokeColorSpace = cachedColorSpace;
  1393. continue;
  1394. }
  1395. next(self.parseColorSpace({
  1396. cs: args[0],
  1397. resources,
  1398. localColorSpaceCache
  1399. }).then(function (colorSpace) {
  1400. if (colorSpace) {
  1401. stateManager.state.strokeColorSpace = colorSpace;
  1402. }
  1403. }));
  1404. return;
  1405. }
  1406. case _util.OPS.setFillColor:
  1407. cs = stateManager.state.fillColorSpace;
  1408. args = cs.getRgb(args, 0);
  1409. fn = _util.OPS.setFillRGBColor;
  1410. break;
  1411. case _util.OPS.setStrokeColor:
  1412. cs = stateManager.state.strokeColorSpace;
  1413. args = cs.getRgb(args, 0);
  1414. fn = _util.OPS.setStrokeRGBColor;
  1415. break;
  1416. case _util.OPS.setFillGray:
  1417. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  1418. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  1419. fn = _util.OPS.setFillRGBColor;
  1420. break;
  1421. case _util.OPS.setStrokeGray:
  1422. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  1423. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  1424. fn = _util.OPS.setStrokeRGBColor;
  1425. break;
  1426. case _util.OPS.setFillCMYKColor:
  1427. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  1428. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  1429. fn = _util.OPS.setFillRGBColor;
  1430. break;
  1431. case _util.OPS.setStrokeCMYKColor:
  1432. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  1433. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  1434. fn = _util.OPS.setStrokeRGBColor;
  1435. break;
  1436. case _util.OPS.setFillRGBColor:
  1437. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.rgb;
  1438. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  1439. break;
  1440. case _util.OPS.setStrokeRGBColor:
  1441. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.rgb;
  1442. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  1443. break;
  1444. case _util.OPS.setFillColorN:
  1445. cs = stateManager.state.fillColorSpace;
  1446. if (cs.name === "Pattern") {
  1447. next(self.handleColorN(operatorList, _util.OPS.setFillColorN, args, cs, patterns, resources, task, localColorSpaceCache, localTilingPatternCache, localShadingPatternCache));
  1448. return;
  1449. }
  1450. args = cs.getRgb(args, 0);
  1451. fn = _util.OPS.setFillRGBColor;
  1452. break;
  1453. case _util.OPS.setStrokeColorN:
  1454. cs = stateManager.state.strokeColorSpace;
  1455. if (cs.name === "Pattern") {
  1456. next(self.handleColorN(operatorList, _util.OPS.setStrokeColorN, args, cs, patterns, resources, task, localColorSpaceCache, localTilingPatternCache, localShadingPatternCache));
  1457. return;
  1458. }
  1459. args = cs.getRgb(args, 0);
  1460. fn = _util.OPS.setStrokeRGBColor;
  1461. break;
  1462. case _util.OPS.shadingFill:
  1463. var shadingRes = resources.get("Shading");
  1464. if (!shadingRes) {
  1465. throw new _util.FormatError("No shading resource found");
  1466. }
  1467. var shading = shadingRes.get(args[0].name);
  1468. if (!shading) {
  1469. throw new _util.FormatError("No shading object found");
  1470. }
  1471. const patternId = self.parseShading({
  1472. shading,
  1473. resources,
  1474. localColorSpaceCache,
  1475. localShadingPatternCache
  1476. });
  1477. args = [patternId];
  1478. fn = _util.OPS.shadingFill;
  1479. break;
  1480. case _util.OPS.setGState:
  1481. isValidName = args[0] instanceof _primitives.Name;
  1482. name = args[0].name;
  1483. if (isValidName) {
  1484. const localGStateObj = localGStateCache.getByName(name);
  1485. if (localGStateObj) {
  1486. if (localGStateObj.length > 0) {
  1487. operatorList.addOp(_util.OPS.setGState, [localGStateObj]);
  1488. }
  1489. args = null;
  1490. continue;
  1491. }
  1492. }
  1493. next(new Promise(function (resolveGState, rejectGState) {
  1494. if (!isValidName) {
  1495. throw new _util.FormatError("GState must be referred to by name.");
  1496. }
  1497. const extGState = resources.get("ExtGState");
  1498. if (!(extGState instanceof _primitives.Dict)) {
  1499. throw new _util.FormatError("ExtGState should be a dictionary.");
  1500. }
  1501. const gState = extGState.get(name);
  1502. if (!(gState instanceof _primitives.Dict)) {
  1503. throw new _util.FormatError("GState should be a dictionary.");
  1504. }
  1505. self.setGState({
  1506. resources,
  1507. gState,
  1508. operatorList,
  1509. cacheKey: name,
  1510. task,
  1511. stateManager,
  1512. localGStateCache,
  1513. localColorSpaceCache
  1514. }).then(resolveGState, rejectGState);
  1515. }).catch(function (reason) {
  1516. if (reason instanceof _util.AbortException) {
  1517. return;
  1518. }
  1519. if (self.options.ignoreErrors) {
  1520. self.handler.send("UnsupportedFeature", {
  1521. featureId: _util.UNSUPPORTED_FEATURES.errorExtGState
  1522. });
  1523. (0, _util.warn)(`getOperatorList - ignoring ExtGState: "${reason}".`);
  1524. return;
  1525. }
  1526. throw reason;
  1527. }));
  1528. return;
  1529. case _util.OPS.moveTo:
  1530. case _util.OPS.lineTo:
  1531. case _util.OPS.curveTo:
  1532. case _util.OPS.curveTo2:
  1533. case _util.OPS.curveTo3:
  1534. case _util.OPS.closePath:
  1535. case _util.OPS.rectangle:
  1536. self.buildPath(operatorList, fn, args, parsingText);
  1537. continue;
  1538. case _util.OPS.markPoint:
  1539. case _util.OPS.markPointProps:
  1540. case _util.OPS.beginCompat:
  1541. case _util.OPS.endCompat:
  1542. continue;
  1543. case _util.OPS.beginMarkedContentProps:
  1544. if (!(args[0] instanceof _primitives.Name)) {
  1545. (0, _util.warn)(`Expected name for beginMarkedContentProps arg0=${args[0]}`);
  1546. continue;
  1547. }
  1548. if (args[0].name === "OC") {
  1549. next(self.parseMarkedContentProps(args[1], resources).then(data => {
  1550. operatorList.addOp(_util.OPS.beginMarkedContentProps, ["OC", data]);
  1551. }).catch(reason => {
  1552. if (reason instanceof _util.AbortException) {
  1553. return;
  1554. }
  1555. if (self.options.ignoreErrors) {
  1556. self.handler.send("UnsupportedFeature", {
  1557. featureId: _util.UNSUPPORTED_FEATURES.errorMarkedContent
  1558. });
  1559. (0, _util.warn)(`getOperatorList - ignoring beginMarkedContentProps: "${reason}".`);
  1560. return;
  1561. }
  1562. throw reason;
  1563. }));
  1564. return;
  1565. }
  1566. args = [args[0].name, args[1] instanceof _primitives.Dict ? args[1].get("MCID") : null];
  1567. break;
  1568. case _util.OPS.beginMarkedContent:
  1569. case _util.OPS.endMarkedContent:
  1570. default:
  1571. if (args !== null) {
  1572. for (i = 0, ii = args.length; i < ii; i++) {
  1573. if (args[i] instanceof _primitives.Dict) {
  1574. break;
  1575. }
  1576. }
  1577. if (i < ii) {
  1578. (0, _util.warn)("getOperatorList - ignoring operator: " + fn);
  1579. continue;
  1580. }
  1581. }
  1582. }
  1583. operatorList.addOp(fn, args);
  1584. }
  1585. if (stop) {
  1586. next(deferred);
  1587. return;
  1588. }
  1589. closePendingRestoreOPS();
  1590. resolve();
  1591. }).catch(reason => {
  1592. if (reason instanceof _util.AbortException) {
  1593. return;
  1594. }
  1595. if (this.options.ignoreErrors) {
  1596. this.handler.send("UnsupportedFeature", {
  1597. featureId: _util.UNSUPPORTED_FEATURES.errorOperatorList
  1598. });
  1599. (0, _util.warn)(`getOperatorList - ignoring errors during "${task.name}" ` + `task: "${reason}".`);
  1600. closePendingRestoreOPS();
  1601. return;
  1602. }
  1603. throw reason;
  1604. });
  1605. }
  1606. getTextContent({
  1607. stream,
  1608. task,
  1609. resources,
  1610. stateManager = null,
  1611. combineTextItems = false,
  1612. includeMarkedContent = false,
  1613. sink,
  1614. seenStyles = new Set(),
  1615. viewBox
  1616. }) {
  1617. resources = resources || _primitives.Dict.empty;
  1618. stateManager = stateManager || new StateManager(new TextState());
  1619. const NormalizedUnicodes = (0, _unicode.getNormalizedUnicodes)();
  1620. const textContent = {
  1621. items: [],
  1622. styles: Object.create(null)
  1623. };
  1624. const textContentItem = {
  1625. initialized: false,
  1626. str: [],
  1627. totalWidth: 0,
  1628. totalHeight: 0,
  1629. width: 0,
  1630. height: 0,
  1631. vertical: false,
  1632. prevTransform: null,
  1633. textAdvanceScale: 0,
  1634. spaceInFlowMin: 0,
  1635. spaceInFlowMax: 0,
  1636. trackingSpaceMin: Infinity,
  1637. negativeSpaceMax: -Infinity,
  1638. notASpace: -Infinity,
  1639. transform: null,
  1640. fontName: null,
  1641. hasEOL: false
  1642. };
  1643. const twoLastChars = [" ", " "];
  1644. let twoLastCharsPos = 0;
  1645. function saveLastChar(char) {
  1646. const nextPos = (twoLastCharsPos + 1) % 2;
  1647. const ret = twoLastChars[twoLastCharsPos] !== " " && twoLastChars[nextPos] === " ";
  1648. twoLastChars[twoLastCharsPos] = char;
  1649. twoLastCharsPos = nextPos;
  1650. return ret;
  1651. }
  1652. function resetLastChars() {
  1653. twoLastChars[0] = twoLastChars[1] = " ";
  1654. twoLastCharsPos = 0;
  1655. }
  1656. const TRACKING_SPACE_FACTOR = 0.1;
  1657. const NOT_A_SPACE_FACTOR = 0.03;
  1658. const NEGATIVE_SPACE_FACTOR = -0.2;
  1659. const SPACE_IN_FLOW_MIN_FACTOR = 0.1;
  1660. const SPACE_IN_FLOW_MAX_FACTOR = 0.6;
  1661. const self = this;
  1662. const xref = this.xref;
  1663. const showSpacedTextBuffer = [];
  1664. let xobjs = null;
  1665. const emptyXObjectCache = new _image_utils.LocalImageCache();
  1666. const emptyGStateCache = new _image_utils.LocalGStateCache();
  1667. const preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  1668. let textState;
  1669. function getCurrentTextTransform() {
  1670. const font = textState.font;
  1671. const tsm = [textState.fontSize * textState.textHScale, 0, 0, textState.fontSize, 0, textState.textRise];
  1672. if (font.isType3Font && (textState.fontSize <= 1 || font.isCharBBox) && !(0, _util.isArrayEqual)(textState.fontMatrix, _util.FONT_IDENTITY_MATRIX)) {
  1673. const glyphHeight = font.bbox[3] - font.bbox[1];
  1674. if (glyphHeight > 0) {
  1675. tsm[3] *= glyphHeight * textState.fontMatrix[3];
  1676. }
  1677. }
  1678. return _util.Util.transform(textState.ctm, _util.Util.transform(textState.textMatrix, tsm));
  1679. }
  1680. function ensureTextContentItem() {
  1681. if (textContentItem.initialized) {
  1682. return textContentItem;
  1683. }
  1684. const font = textState.font,
  1685. loadedName = font.loadedName;
  1686. if (!seenStyles.has(loadedName)) {
  1687. seenStyles.add(loadedName);
  1688. textContent.styles[loadedName] = {
  1689. fontFamily: font.fallbackName,
  1690. ascent: font.ascent,
  1691. descent: font.descent,
  1692. vertical: font.vertical
  1693. };
  1694. }
  1695. textContentItem.fontName = loadedName;
  1696. const trm = textContentItem.transform = getCurrentTextTransform();
  1697. if (!font.vertical) {
  1698. textContentItem.width = textContentItem.totalWidth = 0;
  1699. textContentItem.height = textContentItem.totalHeight = Math.hypot(trm[2], trm[3]);
  1700. textContentItem.vertical = false;
  1701. } else {
  1702. textContentItem.width = textContentItem.totalWidth = Math.hypot(trm[0], trm[1]);
  1703. textContentItem.height = textContentItem.totalHeight = 0;
  1704. textContentItem.vertical = true;
  1705. }
  1706. const scaleLineX = Math.hypot(textState.textLineMatrix[0], textState.textLineMatrix[1]);
  1707. const scaleCtmX = Math.hypot(textState.ctm[0], textState.ctm[1]);
  1708. textContentItem.textAdvanceScale = scaleCtmX * scaleLineX;
  1709. textContentItem.trackingSpaceMin = textState.fontSize * TRACKING_SPACE_FACTOR;
  1710. textContentItem.notASpace = textState.fontSize * NOT_A_SPACE_FACTOR;
  1711. textContentItem.negativeSpaceMax = textState.fontSize * NEGATIVE_SPACE_FACTOR;
  1712. textContentItem.spaceInFlowMin = textState.fontSize * SPACE_IN_FLOW_MIN_FACTOR;
  1713. textContentItem.spaceInFlowMax = textState.fontSize * SPACE_IN_FLOW_MAX_FACTOR;
  1714. textContentItem.hasEOL = false;
  1715. textContentItem.initialized = true;
  1716. return textContentItem;
  1717. }
  1718. function updateAdvanceScale() {
  1719. if (!textContentItem.initialized) {
  1720. return;
  1721. }
  1722. const scaleLineX = Math.hypot(textState.textLineMatrix[0], textState.textLineMatrix[1]);
  1723. const scaleCtmX = Math.hypot(textState.ctm[0], textState.ctm[1]);
  1724. const scaleFactor = scaleCtmX * scaleLineX;
  1725. if (scaleFactor === textContentItem.textAdvanceScale) {
  1726. return;
  1727. }
  1728. if (!textContentItem.vertical) {
  1729. textContentItem.totalWidth += textContentItem.width * textContentItem.textAdvanceScale;
  1730. textContentItem.width = 0;
  1731. } else {
  1732. textContentItem.totalHeight += textContentItem.height * textContentItem.textAdvanceScale;
  1733. textContentItem.height = 0;
  1734. }
  1735. textContentItem.textAdvanceScale = scaleFactor;
  1736. }
  1737. function runBidiTransform(textChunk) {
  1738. const text = textChunk.str.join("");
  1739. const bidiResult = (0, _bidi.bidi)(text, -1, textChunk.vertical);
  1740. return {
  1741. str: bidiResult.str,
  1742. dir: bidiResult.dir,
  1743. width: Math.abs(textChunk.totalWidth),
  1744. height: Math.abs(textChunk.totalHeight),
  1745. transform: textChunk.transform,
  1746. fontName: textChunk.fontName,
  1747. hasEOL: textChunk.hasEOL
  1748. };
  1749. }
  1750. function handleSetFont(fontName, fontRef) {
  1751. return self.loadFont(fontName, fontRef, resources).then(function (translated) {
  1752. if (!translated.font.isType3Font) {
  1753. return translated;
  1754. }
  1755. return translated.loadType3Data(self, resources, task).catch(function () {}).then(function () {
  1756. return translated;
  1757. });
  1758. }).then(function (translated) {
  1759. textState.font = translated.font;
  1760. textState.fontMatrix = translated.font.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1761. });
  1762. }
  1763. function applyInverseRotation(x, y, matrix) {
  1764. const scale = Math.hypot(matrix[0], matrix[1]);
  1765. return [(matrix[0] * x + matrix[1] * y) / scale, (matrix[2] * x + matrix[3] * y) / scale];
  1766. }
  1767. function compareWithLastPosition() {
  1768. const currentTransform = getCurrentTextTransform();
  1769. let posX = currentTransform[4];
  1770. let posY = currentTransform[5];
  1771. const shiftedX = posX - viewBox[0];
  1772. const shiftedY = posY - viewBox[1];
  1773. if (shiftedX < 0 || shiftedX > viewBox[2] || shiftedY < 0 || shiftedY > viewBox[3]) {
  1774. return false;
  1775. }
  1776. if (!combineTextItems || !textState.font || !textContentItem.prevTransform) {
  1777. return true;
  1778. }
  1779. let lastPosX = textContentItem.prevTransform[4];
  1780. let lastPosY = textContentItem.prevTransform[5];
  1781. if (lastPosX === posX && lastPosY === posY) {
  1782. return true;
  1783. }
  1784. let rotate = -1;
  1785. if (currentTransform[0] && currentTransform[1] === 0 && currentTransform[2] === 0) {
  1786. rotate = currentTransform[0] > 0 ? 0 : 180;
  1787. } else if (currentTransform[1] && currentTransform[0] === 0 && currentTransform[3] === 0) {
  1788. rotate = currentTransform[1] > 0 ? 90 : 270;
  1789. }
  1790. switch (rotate) {
  1791. case 0:
  1792. break;
  1793. case 90:
  1794. [posX, posY] = [posY, posX];
  1795. [lastPosX, lastPosY] = [lastPosY, lastPosX];
  1796. break;
  1797. case 180:
  1798. [posX, posY, lastPosX, lastPosY] = [-posX, -posY, -lastPosX, -lastPosY];
  1799. break;
  1800. case 270:
  1801. [posX, posY] = [-posY, -posX];
  1802. [lastPosX, lastPosY] = [-lastPosY, -lastPosX];
  1803. break;
  1804. default:
  1805. [posX, posY] = applyInverseRotation(posX, posY, currentTransform);
  1806. [lastPosX, lastPosY] = applyInverseRotation(lastPosX, lastPosY, textContentItem.prevTransform);
  1807. }
  1808. if (textState.font.vertical) {
  1809. const advanceY = (lastPosY - posY) / textContentItem.textAdvanceScale;
  1810. const advanceX = posX - lastPosX;
  1811. const textOrientation = Math.sign(textContentItem.height);
  1812. if (advanceY < textOrientation * textContentItem.negativeSpaceMax) {
  1813. if (Math.abs(advanceX) > 0.5 * textContentItem.width) {
  1814. appendEOL();
  1815. return true;
  1816. }
  1817. resetLastChars();
  1818. flushTextContentItem();
  1819. return true;
  1820. }
  1821. if (Math.abs(advanceX) > textContentItem.width) {
  1822. appendEOL();
  1823. return true;
  1824. }
  1825. if (advanceY <= textOrientation * textContentItem.notASpace) {
  1826. resetLastChars();
  1827. }
  1828. if (advanceY <= textOrientation * textContentItem.trackingSpaceMin) {
  1829. textContentItem.height += advanceY;
  1830. } else if (!addFakeSpaces(advanceY, textContentItem.prevTransform, textOrientation)) {
  1831. if (textContentItem.str.length === 0) {
  1832. resetLastChars();
  1833. textContent.items.push({
  1834. str: " ",
  1835. dir: "ltr",
  1836. width: 0,
  1837. height: Math.abs(advanceY),
  1838. transform: textContentItem.prevTransform,
  1839. fontName: textContentItem.fontName,
  1840. hasEOL: false
  1841. });
  1842. } else {
  1843. textContentItem.height += advanceY;
  1844. }
  1845. }
  1846. return true;
  1847. }
  1848. const advanceX = (posX - lastPosX) / textContentItem.textAdvanceScale;
  1849. const advanceY = posY - lastPosY;
  1850. const textOrientation = Math.sign(textContentItem.width);
  1851. if (advanceX < textOrientation * textContentItem.negativeSpaceMax) {
  1852. if (Math.abs(advanceY) > 0.5 * textContentItem.height) {
  1853. appendEOL();
  1854. return true;
  1855. }
  1856. resetLastChars();
  1857. flushTextContentItem();
  1858. return true;
  1859. }
  1860. if (Math.abs(advanceY) > textContentItem.height) {
  1861. appendEOL();
  1862. return true;
  1863. }
  1864. if (advanceX <= textOrientation * textContentItem.notASpace) {
  1865. resetLastChars();
  1866. }
  1867. if (advanceX <= textOrientation * textContentItem.trackingSpaceMin) {
  1868. textContentItem.width += advanceX;
  1869. } else if (!addFakeSpaces(advanceX, textContentItem.prevTransform, textOrientation)) {
  1870. if (textContentItem.str.length === 0) {
  1871. resetLastChars();
  1872. textContent.items.push({
  1873. str: " ",
  1874. dir: "ltr",
  1875. width: Math.abs(advanceX),
  1876. height: 0,
  1877. transform: textContentItem.prevTransform,
  1878. fontName: textContentItem.fontName,
  1879. hasEOL: false
  1880. });
  1881. } else {
  1882. textContentItem.width += advanceX;
  1883. }
  1884. }
  1885. return true;
  1886. }
  1887. function buildTextContentItem({
  1888. chars,
  1889. extraSpacing
  1890. }) {
  1891. const font = textState.font;
  1892. if (!chars) {
  1893. const charSpacing = textState.charSpacing + extraSpacing;
  1894. if (charSpacing) {
  1895. if (!font.vertical) {
  1896. textState.translateTextMatrix(charSpacing * textState.textHScale, 0);
  1897. } else {
  1898. textState.translateTextMatrix(0, -charSpacing);
  1899. }
  1900. }
  1901. return;
  1902. }
  1903. const glyphs = font.charsToGlyphs(chars);
  1904. const scale = textState.fontMatrix[0] * textState.fontSize;
  1905. for (let i = 0, ii = glyphs.length; i < ii; i++) {
  1906. const glyph = glyphs[i];
  1907. if (glyph.isInvisibleFormatMark) {
  1908. continue;
  1909. }
  1910. let charSpacing = textState.charSpacing + (i + 1 === ii ? extraSpacing : 0);
  1911. let glyphWidth = glyph.width;
  1912. if (font.vertical) {
  1913. glyphWidth = glyph.vmetric ? glyph.vmetric[0] : -glyphWidth;
  1914. }
  1915. let scaledDim = glyphWidth * scale;
  1916. if (glyph.isWhitespace) {
  1917. if (!font.vertical) {
  1918. charSpacing += scaledDim + textState.wordSpacing;
  1919. textState.translateTextMatrix(charSpacing * textState.textHScale, 0);
  1920. } else {
  1921. charSpacing += -scaledDim + textState.wordSpacing;
  1922. textState.translateTextMatrix(0, -charSpacing);
  1923. }
  1924. saveLastChar(" ");
  1925. continue;
  1926. }
  1927. if (!compareWithLastPosition()) {
  1928. continue;
  1929. }
  1930. const textChunk = ensureTextContentItem();
  1931. if (glyph.isZeroWidthDiacritic) {
  1932. scaledDim = 0;
  1933. }
  1934. if (!font.vertical) {
  1935. scaledDim *= textState.textHScale;
  1936. textState.translateTextMatrix(scaledDim, 0);
  1937. textChunk.width += scaledDim;
  1938. } else {
  1939. textState.translateTextMatrix(0, scaledDim);
  1940. scaledDim = Math.abs(scaledDim);
  1941. textChunk.height += scaledDim;
  1942. }
  1943. if (scaledDim) {
  1944. textChunk.prevTransform = getCurrentTextTransform();
  1945. }
  1946. let glyphUnicode = glyph.unicode;
  1947. glyphUnicode = NormalizedUnicodes[glyphUnicode] || glyphUnicode;
  1948. glyphUnicode = (0, _unicode.reverseIfRtl)(glyphUnicode);
  1949. if (saveLastChar(glyphUnicode)) {
  1950. textChunk.str.push(" ");
  1951. }
  1952. textChunk.str.push(glyphUnicode);
  1953. if (charSpacing) {
  1954. if (!font.vertical) {
  1955. textState.translateTextMatrix(charSpacing * textState.textHScale, 0);
  1956. } else {
  1957. textState.translateTextMatrix(0, -charSpacing);
  1958. }
  1959. }
  1960. }
  1961. }
  1962. function appendEOL() {
  1963. resetLastChars();
  1964. if (textContentItem.initialized) {
  1965. textContentItem.hasEOL = true;
  1966. flushTextContentItem();
  1967. } else {
  1968. textContent.items.push({
  1969. str: "",
  1970. dir: "ltr",
  1971. width: 0,
  1972. height: 0,
  1973. transform: getCurrentTextTransform(),
  1974. fontName: textState.font.loadedName,
  1975. hasEOL: true
  1976. });
  1977. }
  1978. }
  1979. function addFakeSpaces(width, transf, textOrientation) {
  1980. if (textOrientation * textContentItem.spaceInFlowMin <= width && width <= textOrientation * textContentItem.spaceInFlowMax) {
  1981. if (textContentItem.initialized) {
  1982. resetLastChars();
  1983. textContentItem.str.push(" ");
  1984. }
  1985. return false;
  1986. }
  1987. const fontName = textContentItem.fontName;
  1988. let height = 0;
  1989. if (textContentItem.vertical) {
  1990. height = width;
  1991. width = 0;
  1992. }
  1993. flushTextContentItem();
  1994. resetLastChars();
  1995. textContent.items.push({
  1996. str: " ",
  1997. dir: "ltr",
  1998. width: Math.abs(width),
  1999. height: Math.abs(height),
  2000. transform: transf || getCurrentTextTransform(),
  2001. fontName,
  2002. hasEOL: false
  2003. });
  2004. return true;
  2005. }
  2006. function flushTextContentItem() {
  2007. if (!textContentItem.initialized || !textContentItem.str) {
  2008. return;
  2009. }
  2010. if (!textContentItem.vertical) {
  2011. textContentItem.totalWidth += textContentItem.width * textContentItem.textAdvanceScale;
  2012. } else {
  2013. textContentItem.totalHeight += textContentItem.height * textContentItem.textAdvanceScale;
  2014. }
  2015. textContent.items.push(runBidiTransform(textContentItem));
  2016. textContentItem.initialized = false;
  2017. textContentItem.str.length = 0;
  2018. }
  2019. function enqueueChunk(batch = false) {
  2020. const length = textContent.items.length;
  2021. if (length === 0) {
  2022. return;
  2023. }
  2024. if (batch && length < TEXT_CHUNK_BATCH_SIZE) {
  2025. return;
  2026. }
  2027. sink.enqueue(textContent, length);
  2028. textContent.items = [];
  2029. textContent.styles = Object.create(null);
  2030. }
  2031. const timeSlotManager = new TimeSlotManager();
  2032. return new Promise(function promiseBody(resolve, reject) {
  2033. const next = function (promise) {
  2034. enqueueChunk(true);
  2035. Promise.all([promise, sink.ready]).then(function () {
  2036. try {
  2037. promiseBody(resolve, reject);
  2038. } catch (ex) {
  2039. reject(ex);
  2040. }
  2041. }, reject);
  2042. };
  2043. task.ensureNotTerminated();
  2044. timeSlotManager.reset();
  2045. const operation = {};
  2046. let stop,
  2047. args = [];
  2048. while (!(stop = timeSlotManager.check())) {
  2049. args.length = 0;
  2050. operation.args = args;
  2051. if (!preprocessor.read(operation)) {
  2052. break;
  2053. }
  2054. textState = stateManager.state;
  2055. const fn = operation.fn;
  2056. args = operation.args;
  2057. switch (fn | 0) {
  2058. case _util.OPS.setFont:
  2059. var fontNameArg = args[0].name,
  2060. fontSizeArg = args[1];
  2061. if (textState.font && fontNameArg === textState.fontName && fontSizeArg === textState.fontSize) {
  2062. break;
  2063. }
  2064. flushTextContentItem();
  2065. textState.fontName = fontNameArg;
  2066. textState.fontSize = fontSizeArg;
  2067. next(handleSetFont(fontNameArg, null));
  2068. return;
  2069. case _util.OPS.setTextRise:
  2070. textState.textRise = args[0];
  2071. break;
  2072. case _util.OPS.setHScale:
  2073. textState.textHScale = args[0] / 100;
  2074. break;
  2075. case _util.OPS.setLeading:
  2076. textState.leading = args[0];
  2077. break;
  2078. case _util.OPS.moveText:
  2079. textState.translateTextLineMatrix(args[0], args[1]);
  2080. textState.textMatrix = textState.textLineMatrix.slice();
  2081. break;
  2082. case _util.OPS.setLeadingMoveText:
  2083. textState.leading = -args[1];
  2084. textState.translateTextLineMatrix(args[0], args[1]);
  2085. textState.textMatrix = textState.textLineMatrix.slice();
  2086. break;
  2087. case _util.OPS.nextLine:
  2088. textState.carriageReturn();
  2089. break;
  2090. case _util.OPS.setTextMatrix:
  2091. textState.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  2092. textState.setTextLineMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  2093. updateAdvanceScale();
  2094. break;
  2095. case _util.OPS.setCharSpacing:
  2096. textState.charSpacing = args[0];
  2097. break;
  2098. case _util.OPS.setWordSpacing:
  2099. textState.wordSpacing = args[0];
  2100. break;
  2101. case _util.OPS.beginText:
  2102. textState.textMatrix = _util.IDENTITY_MATRIX.slice();
  2103. textState.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  2104. break;
  2105. case _util.OPS.showSpacedText:
  2106. if (!stateManager.state.font) {
  2107. self.ensureStateFont(stateManager.state);
  2108. continue;
  2109. }
  2110. const spaceFactor = (textState.font.vertical ? 1 : -1) * textState.fontSize / 1000;
  2111. const elements = args[0];
  2112. for (let i = 0, ii = elements.length; i < ii - 1; i++) {
  2113. const item = elements[i];
  2114. if (typeof item === "string") {
  2115. showSpacedTextBuffer.push(item);
  2116. } else if (typeof item === "number" && item !== 0) {
  2117. const str = showSpacedTextBuffer.join("");
  2118. showSpacedTextBuffer.length = 0;
  2119. buildTextContentItem({
  2120. chars: str,
  2121. extraSpacing: item * spaceFactor
  2122. });
  2123. }
  2124. }
  2125. const item = elements.at(-1);
  2126. if (typeof item === "string") {
  2127. showSpacedTextBuffer.push(item);
  2128. }
  2129. if (showSpacedTextBuffer.length > 0) {
  2130. const str = showSpacedTextBuffer.join("");
  2131. showSpacedTextBuffer.length = 0;
  2132. buildTextContentItem({
  2133. chars: str,
  2134. extraSpacing: 0
  2135. });
  2136. }
  2137. break;
  2138. case _util.OPS.showText:
  2139. if (!stateManager.state.font) {
  2140. self.ensureStateFont(stateManager.state);
  2141. continue;
  2142. }
  2143. buildTextContentItem({
  2144. chars: args[0],
  2145. extraSpacing: 0
  2146. });
  2147. break;
  2148. case _util.OPS.nextLineShowText:
  2149. if (!stateManager.state.font) {
  2150. self.ensureStateFont(stateManager.state);
  2151. continue;
  2152. }
  2153. textState.carriageReturn();
  2154. buildTextContentItem({
  2155. chars: args[0],
  2156. extraSpacing: 0
  2157. });
  2158. break;
  2159. case _util.OPS.nextLineSetSpacingShowText:
  2160. if (!stateManager.state.font) {
  2161. self.ensureStateFont(stateManager.state);
  2162. continue;
  2163. }
  2164. textState.wordSpacing = args[0];
  2165. textState.charSpacing = args[1];
  2166. textState.carriageReturn();
  2167. buildTextContentItem({
  2168. chars: args[2],
  2169. extraSpacing: 0
  2170. });
  2171. break;
  2172. case _util.OPS.paintXObject:
  2173. flushTextContentItem();
  2174. if (!xobjs) {
  2175. xobjs = resources.get("XObject") || _primitives.Dict.empty;
  2176. }
  2177. var isValidName = args[0] instanceof _primitives.Name;
  2178. var name = args[0].name;
  2179. if (isValidName && emptyXObjectCache.getByName(name)) {
  2180. break;
  2181. }
  2182. next(new Promise(function (resolveXObject, rejectXObject) {
  2183. if (!isValidName) {
  2184. throw new _util.FormatError("XObject must be referred to by name.");
  2185. }
  2186. let xobj = xobjs.getRaw(name);
  2187. if (xobj instanceof _primitives.Ref) {
  2188. if (emptyXObjectCache.getByRef(xobj)) {
  2189. resolveXObject();
  2190. return;
  2191. }
  2192. const globalImage = self.globalImageCache.getData(xobj, self.pageIndex);
  2193. if (globalImage) {
  2194. resolveXObject();
  2195. return;
  2196. }
  2197. xobj = xref.fetch(xobj);
  2198. }
  2199. if (!(xobj instanceof _base_stream.BaseStream)) {
  2200. throw new _util.FormatError("XObject should be a stream");
  2201. }
  2202. const type = xobj.dict.get("Subtype");
  2203. if (!(type instanceof _primitives.Name)) {
  2204. throw new _util.FormatError("XObject should have a Name subtype");
  2205. }
  2206. if (type.name !== "Form") {
  2207. emptyXObjectCache.set(name, xobj.dict.objId, true);
  2208. resolveXObject();
  2209. return;
  2210. }
  2211. const currentState = stateManager.state.clone();
  2212. const xObjStateManager = new StateManager(currentState);
  2213. const matrix = xobj.dict.getArray("Matrix");
  2214. if (Array.isArray(matrix) && matrix.length === 6) {
  2215. xObjStateManager.transform(matrix);
  2216. }
  2217. enqueueChunk();
  2218. const sinkWrapper = {
  2219. enqueueInvoked: false,
  2220. enqueue(chunk, size) {
  2221. this.enqueueInvoked = true;
  2222. sink.enqueue(chunk, size);
  2223. },
  2224. get desiredSize() {
  2225. return sink.desiredSize;
  2226. },
  2227. get ready() {
  2228. return sink.ready;
  2229. }
  2230. };
  2231. self.getTextContent({
  2232. stream: xobj,
  2233. task,
  2234. resources: xobj.dict.get("Resources") || resources,
  2235. stateManager: xObjStateManager,
  2236. combineTextItems,
  2237. includeMarkedContent,
  2238. sink: sinkWrapper,
  2239. seenStyles,
  2240. viewBox
  2241. }).then(function () {
  2242. if (!sinkWrapper.enqueueInvoked) {
  2243. emptyXObjectCache.set(name, xobj.dict.objId, true);
  2244. }
  2245. resolveXObject();
  2246. }, rejectXObject);
  2247. }).catch(function (reason) {
  2248. if (reason instanceof _util.AbortException) {
  2249. return;
  2250. }
  2251. if (self.options.ignoreErrors) {
  2252. (0, _util.warn)(`getTextContent - ignoring XObject: "${reason}".`);
  2253. return;
  2254. }
  2255. throw reason;
  2256. }));
  2257. return;
  2258. case _util.OPS.setGState:
  2259. isValidName = args[0] instanceof _primitives.Name;
  2260. name = args[0].name;
  2261. if (isValidName && emptyGStateCache.getByName(name)) {
  2262. break;
  2263. }
  2264. next(new Promise(function (resolveGState, rejectGState) {
  2265. if (!isValidName) {
  2266. throw new _util.FormatError("GState must be referred to by name.");
  2267. }
  2268. const extGState = resources.get("ExtGState");
  2269. if (!(extGState instanceof _primitives.Dict)) {
  2270. throw new _util.FormatError("ExtGState should be a dictionary.");
  2271. }
  2272. const gState = extGState.get(name);
  2273. if (!(gState instanceof _primitives.Dict)) {
  2274. throw new _util.FormatError("GState should be a dictionary.");
  2275. }
  2276. const gStateFont = gState.get("Font");
  2277. if (!gStateFont) {
  2278. emptyGStateCache.set(name, gState.objId, true);
  2279. resolveGState();
  2280. return;
  2281. }
  2282. flushTextContentItem();
  2283. textState.fontName = null;
  2284. textState.fontSize = gStateFont[1];
  2285. handleSetFont(null, gStateFont[0]).then(resolveGState, rejectGState);
  2286. }).catch(function (reason) {
  2287. if (reason instanceof _util.AbortException) {
  2288. return;
  2289. }
  2290. if (self.options.ignoreErrors) {
  2291. (0, _util.warn)(`getTextContent - ignoring ExtGState: "${reason}".`);
  2292. return;
  2293. }
  2294. throw reason;
  2295. }));
  2296. return;
  2297. case _util.OPS.beginMarkedContent:
  2298. flushTextContentItem();
  2299. if (includeMarkedContent) {
  2300. textContent.items.push({
  2301. type: "beginMarkedContent",
  2302. tag: args[0] instanceof _primitives.Name ? args[0].name : null
  2303. });
  2304. }
  2305. break;
  2306. case _util.OPS.beginMarkedContentProps:
  2307. flushTextContentItem();
  2308. if (includeMarkedContent) {
  2309. let mcid = null;
  2310. if (args[1] instanceof _primitives.Dict) {
  2311. mcid = args[1].get("MCID");
  2312. }
  2313. textContent.items.push({
  2314. type: "beginMarkedContentProps",
  2315. id: Number.isInteger(mcid) ? `${self.idFactory.getPageObjId()}_mcid${mcid}` : null,
  2316. tag: args[0] instanceof _primitives.Name ? args[0].name : null
  2317. });
  2318. }
  2319. break;
  2320. case _util.OPS.endMarkedContent:
  2321. flushTextContentItem();
  2322. if (includeMarkedContent) {
  2323. textContent.items.push({
  2324. type: "endMarkedContent"
  2325. });
  2326. }
  2327. break;
  2328. }
  2329. if (textContent.items.length >= sink.desiredSize) {
  2330. stop = true;
  2331. break;
  2332. }
  2333. }
  2334. if (stop) {
  2335. next(deferred);
  2336. return;
  2337. }
  2338. flushTextContentItem();
  2339. enqueueChunk();
  2340. resolve();
  2341. }).catch(reason => {
  2342. if (reason instanceof _util.AbortException) {
  2343. return;
  2344. }
  2345. if (this.options.ignoreErrors) {
  2346. (0, _util.warn)(`getTextContent - ignoring errors during "${task.name}" ` + `task: "${reason}".`);
  2347. flushTextContentItem();
  2348. enqueueChunk();
  2349. return;
  2350. }
  2351. throw reason;
  2352. });
  2353. }
  2354. extractDataStructures(dict, baseDict, properties) {
  2355. const xref = this.xref;
  2356. let cidToGidBytes;
  2357. const toUnicodePromise = this.readToUnicode(properties.toUnicode || dict.get("ToUnicode") || baseDict.get("ToUnicode"));
  2358. if (properties.composite) {
  2359. const cidSystemInfo = dict.get("CIDSystemInfo");
  2360. if (cidSystemInfo instanceof _primitives.Dict) {
  2361. properties.cidSystemInfo = {
  2362. registry: (0, _util.stringToPDFString)(cidSystemInfo.get("Registry")),
  2363. ordering: (0, _util.stringToPDFString)(cidSystemInfo.get("Ordering")),
  2364. supplement: cidSystemInfo.get("Supplement")
  2365. };
  2366. }
  2367. try {
  2368. const cidToGidMap = dict.get("CIDToGIDMap");
  2369. if (cidToGidMap instanceof _base_stream.BaseStream) {
  2370. cidToGidBytes = cidToGidMap.getBytes();
  2371. }
  2372. } catch (ex) {
  2373. if (!this.options.ignoreErrors) {
  2374. throw ex;
  2375. }
  2376. (0, _util.warn)(`extractDataStructures - ignoring CIDToGIDMap data: "${ex}".`);
  2377. }
  2378. }
  2379. const differences = [];
  2380. let baseEncodingName = null;
  2381. let encoding;
  2382. if (dict.has("Encoding")) {
  2383. encoding = dict.get("Encoding");
  2384. if (encoding instanceof _primitives.Dict) {
  2385. baseEncodingName = encoding.get("BaseEncoding");
  2386. baseEncodingName = baseEncodingName instanceof _primitives.Name ? baseEncodingName.name : null;
  2387. if (encoding.has("Differences")) {
  2388. const diffEncoding = encoding.get("Differences");
  2389. let index = 0;
  2390. for (let j = 0, jj = diffEncoding.length; j < jj; j++) {
  2391. const data = xref.fetchIfRef(diffEncoding[j]);
  2392. if (typeof data === "number") {
  2393. index = data;
  2394. } else if (data instanceof _primitives.Name) {
  2395. differences[index++] = data.name;
  2396. } else {
  2397. throw new _util.FormatError(`Invalid entry in 'Differences' array: ${data}`);
  2398. }
  2399. }
  2400. }
  2401. } else if (encoding instanceof _primitives.Name) {
  2402. baseEncodingName = encoding.name;
  2403. } else {
  2404. const msg = "Encoding is not a Name nor a Dict";
  2405. if (!this.options.ignoreErrors) {
  2406. throw new _util.FormatError(msg);
  2407. }
  2408. (0, _util.warn)(msg);
  2409. }
  2410. if (baseEncodingName !== "MacRomanEncoding" && baseEncodingName !== "MacExpertEncoding" && baseEncodingName !== "WinAnsiEncoding") {
  2411. baseEncodingName = null;
  2412. }
  2413. }
  2414. if (baseEncodingName) {
  2415. properties.defaultEncoding = (0, _encodings.getEncoding)(baseEncodingName);
  2416. } else {
  2417. const isSymbolicFont = !!(properties.flags & _fonts_utils.FontFlags.Symbolic);
  2418. const isNonsymbolicFont = !!(properties.flags & _fonts_utils.FontFlags.Nonsymbolic);
  2419. encoding = _encodings.StandardEncoding;
  2420. if (properties.type === "TrueType" && !isNonsymbolicFont) {
  2421. encoding = _encodings.WinAnsiEncoding;
  2422. }
  2423. if (isSymbolicFont) {
  2424. encoding = _encodings.MacRomanEncoding;
  2425. if (!properties.file || properties.isInternalFont) {
  2426. if (/Symbol/i.test(properties.name)) {
  2427. encoding = _encodings.SymbolSetEncoding;
  2428. } else if (/Dingbats|Wingdings/i.test(properties.name)) {
  2429. encoding = _encodings.ZapfDingbatsEncoding;
  2430. }
  2431. }
  2432. }
  2433. properties.defaultEncoding = encoding;
  2434. }
  2435. properties.differences = differences;
  2436. properties.baseEncodingName = baseEncodingName;
  2437. properties.hasEncoding = !!baseEncodingName || differences.length > 0;
  2438. properties.dict = dict;
  2439. return toUnicodePromise.then(readToUnicode => {
  2440. properties.toUnicode = readToUnicode;
  2441. return this.buildToUnicode(properties);
  2442. }).then(builtToUnicode => {
  2443. properties.toUnicode = builtToUnicode;
  2444. if (cidToGidBytes) {
  2445. properties.cidToGidMap = this.readCidToGidMap(cidToGidBytes, builtToUnicode);
  2446. }
  2447. return properties;
  2448. });
  2449. }
  2450. _simpleFontToUnicode(properties, forceGlyphs = false) {
  2451. (0, _util.assert)(!properties.composite, "Must be a simple font.");
  2452. const toUnicode = [];
  2453. const encoding = properties.defaultEncoding.slice();
  2454. const baseEncodingName = properties.baseEncodingName;
  2455. const differences = properties.differences;
  2456. for (const charcode in differences) {
  2457. const glyphName = differences[charcode];
  2458. if (glyphName === ".notdef") {
  2459. continue;
  2460. }
  2461. encoding[charcode] = glyphName;
  2462. }
  2463. const glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  2464. for (const charcode in encoding) {
  2465. let glyphName = encoding[charcode];
  2466. if (glyphName === "") {
  2467. continue;
  2468. } else if (glyphsUnicodeMap[glyphName] === undefined) {
  2469. let code = 0;
  2470. switch (glyphName[0]) {
  2471. case "G":
  2472. if (glyphName.length === 3) {
  2473. code = parseInt(glyphName.substring(1), 16);
  2474. }
  2475. break;
  2476. case "g":
  2477. if (glyphName.length === 5) {
  2478. code = parseInt(glyphName.substring(1), 16);
  2479. }
  2480. break;
  2481. case "C":
  2482. case "c":
  2483. if (glyphName.length >= 3 && glyphName.length <= 4) {
  2484. const codeStr = glyphName.substring(1);
  2485. if (forceGlyphs) {
  2486. code = parseInt(codeStr, 16);
  2487. break;
  2488. }
  2489. code = +codeStr;
  2490. if (Number.isNaN(code) && Number.isInteger(parseInt(codeStr, 16))) {
  2491. return this._simpleFontToUnicode(properties, true);
  2492. }
  2493. }
  2494. break;
  2495. default:
  2496. const unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
  2497. if (unicode !== -1) {
  2498. code = unicode;
  2499. }
  2500. }
  2501. if (code > 0 && code <= 0x10ffff && Number.isInteger(code)) {
  2502. if (baseEncodingName && code === +charcode) {
  2503. const baseEncoding = (0, _encodings.getEncoding)(baseEncodingName);
  2504. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  2505. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  2506. continue;
  2507. }
  2508. }
  2509. toUnicode[charcode] = String.fromCodePoint(code);
  2510. }
  2511. continue;
  2512. }
  2513. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  2514. }
  2515. return toUnicode;
  2516. }
  2517. async buildToUnicode(properties) {
  2518. properties.hasIncludedToUnicodeMap = !!properties.toUnicode && properties.toUnicode.length > 0;
  2519. if (properties.hasIncludedToUnicodeMap) {
  2520. if (!properties.composite && properties.hasEncoding) {
  2521. properties.fallbackToUnicode = this._simpleFontToUnicode(properties);
  2522. }
  2523. return properties.toUnicode;
  2524. }
  2525. if (!properties.composite) {
  2526. return new _to_unicode_map.ToUnicodeMap(this._simpleFontToUnicode(properties));
  2527. }
  2528. if (properties.composite && (properties.cMap.builtInCMap && !(properties.cMap instanceof _cmap.IdentityCMap) || properties.cidSystemInfo.registry === "Adobe" && (properties.cidSystemInfo.ordering === "GB1" || properties.cidSystemInfo.ordering === "CNS1" || properties.cidSystemInfo.ordering === "Japan1" || properties.cidSystemInfo.ordering === "Korea1"))) {
  2529. const {
  2530. registry,
  2531. ordering
  2532. } = properties.cidSystemInfo;
  2533. const ucs2CMapName = _primitives.Name.get(`${registry}-${ordering}-UCS2`);
  2534. const ucs2CMap = await _cmap.CMapFactory.create({
  2535. encoding: ucs2CMapName,
  2536. fetchBuiltInCMap: this._fetchBuiltInCMapBound,
  2537. useCMap: null
  2538. });
  2539. const toUnicode = [];
  2540. properties.cMap.forEach(function (charcode, cid) {
  2541. if (cid > 0xffff) {
  2542. throw new _util.FormatError("Max size of CID is 65,535");
  2543. }
  2544. const ucs2 = ucs2CMap.lookup(cid);
  2545. if (ucs2) {
  2546. toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) + ucs2.charCodeAt(1));
  2547. }
  2548. });
  2549. return new _to_unicode_map.ToUnicodeMap(toUnicode);
  2550. }
  2551. return new _to_unicode_map.IdentityToUnicodeMap(properties.firstChar, properties.lastChar);
  2552. }
  2553. readToUnicode(cmapObj) {
  2554. if (!cmapObj) {
  2555. return Promise.resolve(null);
  2556. }
  2557. if (cmapObj instanceof _primitives.Name) {
  2558. return _cmap.CMapFactory.create({
  2559. encoding: cmapObj,
  2560. fetchBuiltInCMap: this._fetchBuiltInCMapBound,
  2561. useCMap: null
  2562. }).then(function (cmap) {
  2563. if (cmap instanceof _cmap.IdentityCMap) {
  2564. return new _to_unicode_map.IdentityToUnicodeMap(0, 0xffff);
  2565. }
  2566. return new _to_unicode_map.ToUnicodeMap(cmap.getMap());
  2567. });
  2568. } else if (cmapObj instanceof _base_stream.BaseStream) {
  2569. return _cmap.CMapFactory.create({
  2570. encoding: cmapObj,
  2571. fetchBuiltInCMap: this._fetchBuiltInCMapBound,
  2572. useCMap: null
  2573. }).then(function (cmap) {
  2574. if (cmap instanceof _cmap.IdentityCMap) {
  2575. return new _to_unicode_map.IdentityToUnicodeMap(0, 0xffff);
  2576. }
  2577. const map = new Array(cmap.length);
  2578. cmap.forEach(function (charCode, token) {
  2579. if (typeof token === "number") {
  2580. map[charCode] = String.fromCodePoint(token);
  2581. return;
  2582. }
  2583. const str = [];
  2584. for (let k = 0; k < token.length; k += 2) {
  2585. const w1 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  2586. if ((w1 & 0xf800) !== 0xd800) {
  2587. str.push(w1);
  2588. continue;
  2589. }
  2590. k += 2;
  2591. const w2 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  2592. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  2593. }
  2594. map[charCode] = String.fromCodePoint(...str);
  2595. });
  2596. return new _to_unicode_map.ToUnicodeMap(map);
  2597. }, reason => {
  2598. if (reason instanceof _util.AbortException) {
  2599. return null;
  2600. }
  2601. if (this.options.ignoreErrors) {
  2602. this.handler.send("UnsupportedFeature", {
  2603. featureId: _util.UNSUPPORTED_FEATURES.errorFontToUnicode
  2604. });
  2605. (0, _util.warn)(`readToUnicode - ignoring ToUnicode data: "${reason}".`);
  2606. return null;
  2607. }
  2608. throw reason;
  2609. });
  2610. }
  2611. return Promise.resolve(null);
  2612. }
  2613. readCidToGidMap(glyphsData, toUnicode) {
  2614. const result = [];
  2615. for (let j = 0, jj = glyphsData.length; j < jj; j++) {
  2616. const glyphID = glyphsData[j++] << 8 | glyphsData[j];
  2617. const code = j >> 1;
  2618. if (glyphID === 0 && !toUnicode.has(code)) {
  2619. continue;
  2620. }
  2621. result[code] = glyphID;
  2622. }
  2623. return result;
  2624. }
  2625. extractWidths(dict, descriptor, properties) {
  2626. const xref = this.xref;
  2627. let glyphsWidths = [];
  2628. let defaultWidth = 0;
  2629. const glyphsVMetrics = [];
  2630. let defaultVMetrics;
  2631. let i, ii, j, jj, start, code, widths;
  2632. if (properties.composite) {
  2633. defaultWidth = dict.has("DW") ? dict.get("DW") : 1000;
  2634. widths = dict.get("W");
  2635. if (widths) {
  2636. for (i = 0, ii = widths.length; i < ii; i++) {
  2637. start = xref.fetchIfRef(widths[i++]);
  2638. code = xref.fetchIfRef(widths[i]);
  2639. if (Array.isArray(code)) {
  2640. for (j = 0, jj = code.length; j < jj; j++) {
  2641. glyphsWidths[start++] = xref.fetchIfRef(code[j]);
  2642. }
  2643. } else {
  2644. const width = xref.fetchIfRef(widths[++i]);
  2645. for (j = start; j <= code; j++) {
  2646. glyphsWidths[j] = width;
  2647. }
  2648. }
  2649. }
  2650. }
  2651. if (properties.vertical) {
  2652. let vmetrics = dict.getArray("DW2") || [880, -1000];
  2653. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  2654. vmetrics = dict.get("W2");
  2655. if (vmetrics) {
  2656. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  2657. start = xref.fetchIfRef(vmetrics[i++]);
  2658. code = xref.fetchIfRef(vmetrics[i]);
  2659. if (Array.isArray(code)) {
  2660. for (j = 0, jj = code.length; j < jj; j++) {
  2661. glyphsVMetrics[start++] = [xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j])];
  2662. }
  2663. } else {
  2664. const vmetric = [xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i])];
  2665. for (j = start; j <= code; j++) {
  2666. glyphsVMetrics[j] = vmetric;
  2667. }
  2668. }
  2669. }
  2670. }
  2671. }
  2672. } else {
  2673. const firstChar = properties.firstChar;
  2674. widths = dict.get("Widths");
  2675. if (widths) {
  2676. j = firstChar;
  2677. for (i = 0, ii = widths.length; i < ii; i++) {
  2678. glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
  2679. }
  2680. defaultWidth = parseFloat(descriptor.get("MissingWidth")) || 0;
  2681. } else {
  2682. const baseFontName = dict.get("BaseFont");
  2683. if (baseFontName instanceof _primitives.Name) {
  2684. const metrics = this.getBaseFontMetrics(baseFontName.name);
  2685. glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
  2686. defaultWidth = metrics.defaultWidth;
  2687. }
  2688. }
  2689. }
  2690. let isMonospace = true;
  2691. let firstWidth = defaultWidth;
  2692. for (const glyph in glyphsWidths) {
  2693. const glyphWidth = glyphsWidths[glyph];
  2694. if (!glyphWidth) {
  2695. continue;
  2696. }
  2697. if (!firstWidth) {
  2698. firstWidth = glyphWidth;
  2699. continue;
  2700. }
  2701. if (firstWidth !== glyphWidth) {
  2702. isMonospace = false;
  2703. break;
  2704. }
  2705. }
  2706. if (isMonospace) {
  2707. properties.flags |= _fonts_utils.FontFlags.FixedPitch;
  2708. }
  2709. properties.defaultWidth = defaultWidth;
  2710. properties.widths = glyphsWidths;
  2711. properties.defaultVMetrics = defaultVMetrics;
  2712. properties.vmetrics = glyphsVMetrics;
  2713. }
  2714. isSerifFont(baseFontName) {
  2715. const fontNameWoStyle = baseFontName.split("-")[0];
  2716. return fontNameWoStyle in (0, _standard_fonts.getSerifFonts)() || fontNameWoStyle.search(/serif/gi) !== -1;
  2717. }
  2718. getBaseFontMetrics(name) {
  2719. let defaultWidth = 0;
  2720. let widths = Object.create(null);
  2721. let monospace = false;
  2722. const stdFontMap = (0, _standard_fonts.getStdFontMap)();
  2723. let lookupName = stdFontMap[name] || name;
  2724. const Metrics = (0, _metrics.getMetrics)();
  2725. if (!(lookupName in Metrics)) {
  2726. if (this.isSerifFont(name)) {
  2727. lookupName = "Times-Roman";
  2728. } else {
  2729. lookupName = "Helvetica";
  2730. }
  2731. }
  2732. const glyphWidths = Metrics[lookupName];
  2733. if (typeof glyphWidths === "number") {
  2734. defaultWidth = glyphWidths;
  2735. monospace = true;
  2736. } else {
  2737. widths = glyphWidths();
  2738. }
  2739. return {
  2740. defaultWidth,
  2741. monospace,
  2742. widths
  2743. };
  2744. }
  2745. buildCharCodeToWidth(widthsByGlyphName, properties) {
  2746. const widths = Object.create(null);
  2747. const differences = properties.differences;
  2748. const encoding = properties.defaultEncoding;
  2749. for (let charCode = 0; charCode < 256; charCode++) {
  2750. if (charCode in differences && widthsByGlyphName[differences[charCode]]) {
  2751. widths[charCode] = widthsByGlyphName[differences[charCode]];
  2752. continue;
  2753. }
  2754. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  2755. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  2756. continue;
  2757. }
  2758. }
  2759. return widths;
  2760. }
  2761. preEvaluateFont(dict) {
  2762. const baseDict = dict;
  2763. let type = dict.get("Subtype");
  2764. if (!(type instanceof _primitives.Name)) {
  2765. throw new _util.FormatError("invalid font Subtype");
  2766. }
  2767. let composite = false;
  2768. let hash, toUnicode;
  2769. if (type.name === "Type0") {
  2770. const df = dict.get("DescendantFonts");
  2771. if (!df) {
  2772. throw new _util.FormatError("Descendant fonts are not specified");
  2773. }
  2774. dict = Array.isArray(df) ? this.xref.fetchIfRef(df[0]) : df;
  2775. if (!(dict instanceof _primitives.Dict)) {
  2776. throw new _util.FormatError("Descendant font is not a dictionary.");
  2777. }
  2778. type = dict.get("Subtype");
  2779. if (!(type instanceof _primitives.Name)) {
  2780. throw new _util.FormatError("invalid font Subtype");
  2781. }
  2782. composite = true;
  2783. }
  2784. const firstChar = dict.get("FirstChar") || 0,
  2785. lastChar = dict.get("LastChar") || (composite ? 0xffff : 0xff);
  2786. const descriptor = dict.get("FontDescriptor");
  2787. if (descriptor) {
  2788. hash = new _murmurhash.MurmurHash3_64();
  2789. const encoding = baseDict.getRaw("Encoding");
  2790. if (encoding instanceof _primitives.Name) {
  2791. hash.update(encoding.name);
  2792. } else if (encoding instanceof _primitives.Ref) {
  2793. hash.update(encoding.toString());
  2794. } else if (encoding instanceof _primitives.Dict) {
  2795. for (const entry of encoding.getRawValues()) {
  2796. if (entry instanceof _primitives.Name) {
  2797. hash.update(entry.name);
  2798. } else if (entry instanceof _primitives.Ref) {
  2799. hash.update(entry.toString());
  2800. } else if (Array.isArray(entry)) {
  2801. const diffLength = entry.length,
  2802. diffBuf = new Array(diffLength);
  2803. for (let j = 0; j < diffLength; j++) {
  2804. const diffEntry = entry[j];
  2805. if (diffEntry instanceof _primitives.Name) {
  2806. diffBuf[j] = diffEntry.name;
  2807. } else if (typeof diffEntry === "number" || diffEntry instanceof _primitives.Ref) {
  2808. diffBuf[j] = diffEntry.toString();
  2809. }
  2810. }
  2811. hash.update(diffBuf.join());
  2812. }
  2813. }
  2814. }
  2815. hash.update(`${firstChar}-${lastChar}`);
  2816. toUnicode = dict.get("ToUnicode") || baseDict.get("ToUnicode");
  2817. if (toUnicode instanceof _base_stream.BaseStream) {
  2818. const stream = toUnicode.str || toUnicode;
  2819. const uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
  2820. hash.update(uint8array);
  2821. } else if (toUnicode instanceof _primitives.Name) {
  2822. hash.update(toUnicode.name);
  2823. }
  2824. const widths = dict.get("Widths") || baseDict.get("Widths");
  2825. if (Array.isArray(widths)) {
  2826. const widthsBuf = [];
  2827. for (const entry of widths) {
  2828. if (typeof entry === "number" || entry instanceof _primitives.Ref) {
  2829. widthsBuf.push(entry.toString());
  2830. }
  2831. }
  2832. hash.update(widthsBuf.join());
  2833. }
  2834. if (composite) {
  2835. hash.update("compositeFont");
  2836. const compositeWidths = dict.get("W") || baseDict.get("W");
  2837. if (Array.isArray(compositeWidths)) {
  2838. const widthsBuf = [];
  2839. for (const entry of compositeWidths) {
  2840. if (typeof entry === "number" || entry instanceof _primitives.Ref) {
  2841. widthsBuf.push(entry.toString());
  2842. } else if (Array.isArray(entry)) {
  2843. const subWidthsBuf = [];
  2844. for (const element of entry) {
  2845. if (typeof element === "number" || element instanceof _primitives.Ref) {
  2846. subWidthsBuf.push(element.toString());
  2847. }
  2848. }
  2849. widthsBuf.push(`[${subWidthsBuf.join()}]`);
  2850. }
  2851. }
  2852. hash.update(widthsBuf.join());
  2853. }
  2854. const cidToGidMap = dict.getRaw("CIDToGIDMap") || baseDict.getRaw("CIDToGIDMap");
  2855. if (cidToGidMap instanceof _primitives.Name) {
  2856. hash.update(cidToGidMap.name);
  2857. } else if (cidToGidMap instanceof _primitives.Ref) {
  2858. hash.update(cidToGidMap.toString());
  2859. } else if (cidToGidMap instanceof _base_stream.BaseStream) {
  2860. hash.update(cidToGidMap.peekBytes());
  2861. }
  2862. }
  2863. }
  2864. return {
  2865. descriptor,
  2866. dict,
  2867. baseDict,
  2868. composite,
  2869. type: type.name,
  2870. firstChar,
  2871. lastChar,
  2872. toUnicode,
  2873. hash: hash ? hash.hexdigest() : ""
  2874. };
  2875. }
  2876. async translateFont({
  2877. descriptor,
  2878. dict,
  2879. baseDict,
  2880. composite,
  2881. type,
  2882. firstChar,
  2883. lastChar,
  2884. toUnicode,
  2885. cssFontInfo
  2886. }) {
  2887. const isType3Font = type === "Type3";
  2888. let properties;
  2889. if (!descriptor) {
  2890. if (isType3Font) {
  2891. descriptor = new _primitives.Dict(null);
  2892. descriptor.set("FontName", _primitives.Name.get(type));
  2893. descriptor.set("FontBBox", dict.getArray("FontBBox") || [0, 0, 0, 0]);
  2894. } else {
  2895. let baseFontName = dict.get("BaseFont");
  2896. if (!(baseFontName instanceof _primitives.Name)) {
  2897. throw new _util.FormatError("Base font is not specified");
  2898. }
  2899. baseFontName = baseFontName.name.replace(/[,_]/g, "-");
  2900. const metrics = this.getBaseFontMetrics(baseFontName);
  2901. const fontNameWoStyle = baseFontName.split("-")[0];
  2902. const flags = (this.isSerifFont(fontNameWoStyle) ? _fonts_utils.FontFlags.Serif : 0) | (metrics.monospace ? _fonts_utils.FontFlags.FixedPitch : 0) | ((0, _standard_fonts.getSymbolsFonts)()[fontNameWoStyle] ? _fonts_utils.FontFlags.Symbolic : _fonts_utils.FontFlags.Nonsymbolic);
  2903. properties = {
  2904. type,
  2905. name: baseFontName,
  2906. loadedName: baseDict.loadedName,
  2907. widths: metrics.widths,
  2908. defaultWidth: metrics.defaultWidth,
  2909. isSimulatedFlags: true,
  2910. flags,
  2911. firstChar,
  2912. lastChar,
  2913. toUnicode,
  2914. xHeight: 0,
  2915. capHeight: 0,
  2916. italicAngle: 0,
  2917. isType3Font
  2918. };
  2919. const widths = dict.get("Widths");
  2920. const standardFontName = (0, _standard_fonts.getStandardFontName)(baseFontName);
  2921. let file = null;
  2922. if (standardFontName) {
  2923. properties.isStandardFont = true;
  2924. file = await this.fetchStandardFontData(standardFontName);
  2925. properties.isInternalFont = !!file;
  2926. }
  2927. return this.extractDataStructures(dict, dict, properties).then(newProperties => {
  2928. if (widths) {
  2929. const glyphWidths = [];
  2930. let j = firstChar;
  2931. for (let i = 0, ii = widths.length; i < ii; i++) {
  2932. glyphWidths[j++] = this.xref.fetchIfRef(widths[i]);
  2933. }
  2934. newProperties.widths = glyphWidths;
  2935. } else {
  2936. newProperties.widths = this.buildCharCodeToWidth(metrics.widths, newProperties);
  2937. }
  2938. return new _fonts.Font(baseFontName, file, newProperties);
  2939. });
  2940. }
  2941. }
  2942. let fontName = descriptor.get("FontName");
  2943. let baseFont = dict.get("BaseFont");
  2944. if (typeof fontName === "string") {
  2945. fontName = _primitives.Name.get(fontName);
  2946. }
  2947. if (typeof baseFont === "string") {
  2948. baseFont = _primitives.Name.get(baseFont);
  2949. }
  2950. if (!isType3Font) {
  2951. const fontNameStr = fontName && fontName.name;
  2952. const baseFontStr = baseFont && baseFont.name;
  2953. if (fontNameStr !== baseFontStr) {
  2954. (0, _util.info)(`The FontDescriptor's FontName is "${fontNameStr}" but ` + `should be the same as the Font's BaseFont "${baseFontStr}".`);
  2955. if (fontNameStr && baseFontStr && baseFontStr.startsWith(fontNameStr)) {
  2956. fontName = baseFont;
  2957. }
  2958. }
  2959. }
  2960. fontName = fontName || baseFont;
  2961. if (!(fontName instanceof _primitives.Name)) {
  2962. throw new _util.FormatError("invalid font name");
  2963. }
  2964. let fontFile, subtype, length1, length2, length3;
  2965. try {
  2966. fontFile = descriptor.get("FontFile", "FontFile2", "FontFile3");
  2967. } catch (ex) {
  2968. if (!this.options.ignoreErrors) {
  2969. throw ex;
  2970. }
  2971. (0, _util.warn)(`translateFont - fetching "${fontName.name}" font file: "${ex}".`);
  2972. fontFile = new _stream.NullStream();
  2973. }
  2974. let isStandardFont = false;
  2975. let isInternalFont = false;
  2976. let glyphScaleFactors = null;
  2977. if (fontFile) {
  2978. if (fontFile.dict) {
  2979. const subtypeEntry = fontFile.dict.get("Subtype");
  2980. if (subtypeEntry instanceof _primitives.Name) {
  2981. subtype = subtypeEntry.name;
  2982. }
  2983. length1 = fontFile.dict.get("Length1");
  2984. length2 = fontFile.dict.get("Length2");
  2985. length3 = fontFile.dict.get("Length3");
  2986. }
  2987. } else if (cssFontInfo) {
  2988. const standardFontName = (0, _xfa_fonts.getXfaFontName)(fontName.name);
  2989. if (standardFontName) {
  2990. cssFontInfo.fontFamily = `${cssFontInfo.fontFamily}-PdfJS-XFA`;
  2991. cssFontInfo.metrics = standardFontName.metrics || null;
  2992. glyphScaleFactors = standardFontName.factors || null;
  2993. fontFile = await this.fetchStandardFontData(standardFontName.name);
  2994. isInternalFont = !!fontFile;
  2995. baseDict = dict = (0, _xfa_fonts.getXfaFontDict)(fontName.name);
  2996. composite = true;
  2997. }
  2998. } else if (!isType3Font) {
  2999. const standardFontName = (0, _standard_fonts.getStandardFontName)(fontName.name);
  3000. if (standardFontName) {
  3001. isStandardFont = true;
  3002. fontFile = await this.fetchStandardFontData(standardFontName);
  3003. isInternalFont = !!fontFile;
  3004. }
  3005. }
  3006. properties = {
  3007. type,
  3008. name: fontName.name,
  3009. subtype,
  3010. file: fontFile,
  3011. length1,
  3012. length2,
  3013. length3,
  3014. isStandardFont,
  3015. isInternalFont,
  3016. loadedName: baseDict.loadedName,
  3017. composite,
  3018. fixedPitch: false,
  3019. fontMatrix: dict.getArray("FontMatrix") || _util.FONT_IDENTITY_MATRIX,
  3020. firstChar,
  3021. lastChar,
  3022. toUnicode,
  3023. bbox: descriptor.getArray("FontBBox") || dict.getArray("FontBBox"),
  3024. ascent: descriptor.get("Ascent"),
  3025. descent: descriptor.get("Descent"),
  3026. xHeight: descriptor.get("XHeight") || 0,
  3027. capHeight: descriptor.get("CapHeight") || 0,
  3028. flags: descriptor.get("Flags"),
  3029. italicAngle: descriptor.get("ItalicAngle") || 0,
  3030. isType3Font,
  3031. cssFontInfo,
  3032. scaleFactors: glyphScaleFactors
  3033. };
  3034. if (composite) {
  3035. const cidEncoding = baseDict.get("Encoding");
  3036. if (cidEncoding instanceof _primitives.Name) {
  3037. properties.cidEncoding = cidEncoding.name;
  3038. }
  3039. const cMap = await _cmap.CMapFactory.create({
  3040. encoding: cidEncoding,
  3041. fetchBuiltInCMap: this._fetchBuiltInCMapBound,
  3042. useCMap: null
  3043. });
  3044. properties.cMap = cMap;
  3045. properties.vertical = properties.cMap.vertical;
  3046. }
  3047. return this.extractDataStructures(dict, baseDict, properties).then(newProperties => {
  3048. this.extractWidths(dict, descriptor, newProperties);
  3049. return new _fonts.Font(fontName.name, fontFile, newProperties);
  3050. });
  3051. }
  3052. static buildFontPaths(font, glyphs, handler, evaluatorOptions) {
  3053. function buildPath(fontChar) {
  3054. const glyphName = `${font.loadedName}_path_${fontChar}`;
  3055. try {
  3056. if (font.renderer.hasBuiltPath(fontChar)) {
  3057. return;
  3058. }
  3059. handler.send("commonobj", [glyphName, "FontPath", font.renderer.getPathJs(fontChar)]);
  3060. } catch (reason) {
  3061. if (evaluatorOptions.ignoreErrors) {
  3062. handler.send("UnsupportedFeature", {
  3063. featureId: _util.UNSUPPORTED_FEATURES.errorFontBuildPath
  3064. });
  3065. (0, _util.warn)(`buildFontPaths - ignoring ${glyphName} glyph: "${reason}".`);
  3066. return;
  3067. }
  3068. throw reason;
  3069. }
  3070. }
  3071. for (const glyph of glyphs) {
  3072. buildPath(glyph.fontChar);
  3073. const accent = glyph.accent;
  3074. if (accent && accent.fontChar) {
  3075. buildPath(accent.fontChar);
  3076. }
  3077. }
  3078. }
  3079. static get fallbackFontDict() {
  3080. const dict = new _primitives.Dict();
  3081. dict.set("BaseFont", _primitives.Name.get("PDFJS-FallbackFont"));
  3082. dict.set("Type", _primitives.Name.get("FallbackType"));
  3083. dict.set("Subtype", _primitives.Name.get("FallbackType"));
  3084. dict.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
  3085. return (0, _util.shadow)(this, "fallbackFontDict", dict);
  3086. }
  3087. }
  3088. exports.PartialEvaluator = PartialEvaluator;
  3089. class TranslatedFont {
  3090. constructor({
  3091. loadedName,
  3092. font,
  3093. dict,
  3094. evaluatorOptions
  3095. }) {
  3096. this.loadedName = loadedName;
  3097. this.font = font;
  3098. this.dict = dict;
  3099. this._evaluatorOptions = evaluatorOptions || DefaultPartialEvaluatorOptions;
  3100. this.type3Loaded = null;
  3101. this.type3Dependencies = font.isType3Font ? new Set() : null;
  3102. this.sent = false;
  3103. }
  3104. send(handler) {
  3105. if (this.sent) {
  3106. return;
  3107. }
  3108. this.sent = true;
  3109. handler.send("commonobj", [this.loadedName, "Font", this.font.exportData(this._evaluatorOptions.fontExtraProperties)]);
  3110. }
  3111. fallback(handler) {
  3112. if (!this.font.data) {
  3113. return;
  3114. }
  3115. this.font.disableFontFace = true;
  3116. PartialEvaluator.buildFontPaths(this.font, this.font.glyphCacheValues, handler, this._evaluatorOptions);
  3117. }
  3118. loadType3Data(evaluator, resources, task) {
  3119. if (this.type3Loaded) {
  3120. return this.type3Loaded;
  3121. }
  3122. if (!this.font.isType3Font) {
  3123. throw new Error("Must be a Type3 font.");
  3124. }
  3125. const type3Evaluator = evaluator.clone({
  3126. ignoreErrors: false
  3127. });
  3128. type3Evaluator.parsingType3Font = true;
  3129. const type3FontRefs = new _primitives.RefSet(evaluator.type3FontRefs);
  3130. if (this.dict.objId && !type3FontRefs.has(this.dict.objId)) {
  3131. type3FontRefs.put(this.dict.objId);
  3132. }
  3133. type3Evaluator.type3FontRefs = type3FontRefs;
  3134. const translatedFont = this.font,
  3135. type3Dependencies = this.type3Dependencies;
  3136. let loadCharProcsPromise = Promise.resolve();
  3137. const charProcs = this.dict.get("CharProcs");
  3138. const fontResources = this.dict.get("Resources") || resources;
  3139. const charProcOperatorList = Object.create(null);
  3140. const fontBBox = _util.Util.normalizeRect(translatedFont.bbox || [0, 0, 0, 0]),
  3141. width = fontBBox[2] - fontBBox[0],
  3142. height = fontBBox[3] - fontBBox[1];
  3143. const fontBBoxSize = Math.hypot(width, height);
  3144. for (const key of charProcs.getKeys()) {
  3145. loadCharProcsPromise = loadCharProcsPromise.then(() => {
  3146. const glyphStream = charProcs.get(key);
  3147. const operatorList = new _operator_list.OperatorList();
  3148. return type3Evaluator.getOperatorList({
  3149. stream: glyphStream,
  3150. task,
  3151. resources: fontResources,
  3152. operatorList
  3153. }).then(() => {
  3154. if (operatorList.fnArray[0] === _util.OPS.setCharWidthAndBounds) {
  3155. this._removeType3ColorOperators(operatorList, fontBBoxSize);
  3156. }
  3157. charProcOperatorList[key] = operatorList.getIR();
  3158. for (const dependency of operatorList.dependencies) {
  3159. type3Dependencies.add(dependency);
  3160. }
  3161. }).catch(function (reason) {
  3162. (0, _util.warn)(`Type3 font resource "${key}" is not available.`);
  3163. const dummyOperatorList = new _operator_list.OperatorList();
  3164. charProcOperatorList[key] = dummyOperatorList.getIR();
  3165. });
  3166. });
  3167. }
  3168. this.type3Loaded = loadCharProcsPromise.then(() => {
  3169. translatedFont.charProcOperatorList = charProcOperatorList;
  3170. if (this._bbox) {
  3171. translatedFont.isCharBBox = true;
  3172. translatedFont.bbox = this._bbox;
  3173. }
  3174. });
  3175. return this.type3Loaded;
  3176. }
  3177. _removeType3ColorOperators(operatorList, fontBBoxSize = NaN) {
  3178. const charBBox = _util.Util.normalizeRect(operatorList.argsArray[0].slice(2)),
  3179. width = charBBox[2] - charBBox[0],
  3180. height = charBBox[3] - charBBox[1];
  3181. const charBBoxSize = Math.hypot(width, height);
  3182. if (width === 0 || height === 0) {
  3183. operatorList.fnArray.splice(0, 1);
  3184. operatorList.argsArray.splice(0, 1);
  3185. } else if (fontBBoxSize === 0 || Math.round(charBBoxSize / fontBBoxSize) >= 10) {
  3186. if (!this._bbox) {
  3187. this._bbox = [Infinity, Infinity, -Infinity, -Infinity];
  3188. }
  3189. this._bbox[0] = Math.min(this._bbox[0], charBBox[0]);
  3190. this._bbox[1] = Math.min(this._bbox[1], charBBox[1]);
  3191. this._bbox[2] = Math.max(this._bbox[2], charBBox[2]);
  3192. this._bbox[3] = Math.max(this._bbox[3], charBBox[3]);
  3193. }
  3194. let i = 0,
  3195. ii = operatorList.length;
  3196. while (i < ii) {
  3197. switch (operatorList.fnArray[i]) {
  3198. case _util.OPS.setCharWidthAndBounds:
  3199. break;
  3200. case _util.OPS.setStrokeColorSpace:
  3201. case _util.OPS.setFillColorSpace:
  3202. case _util.OPS.setStrokeColor:
  3203. case _util.OPS.setStrokeColorN:
  3204. case _util.OPS.setFillColor:
  3205. case _util.OPS.setFillColorN:
  3206. case _util.OPS.setStrokeGray:
  3207. case _util.OPS.setFillGray:
  3208. case _util.OPS.setStrokeRGBColor:
  3209. case _util.OPS.setFillRGBColor:
  3210. case _util.OPS.setStrokeCMYKColor:
  3211. case _util.OPS.setFillCMYKColor:
  3212. case _util.OPS.shadingFill:
  3213. case _util.OPS.setRenderingIntent:
  3214. operatorList.fnArray.splice(i, 1);
  3215. operatorList.argsArray.splice(i, 1);
  3216. ii--;
  3217. continue;
  3218. case _util.OPS.setGState:
  3219. const [gStateObj] = operatorList.argsArray[i];
  3220. let j = 0,
  3221. jj = gStateObj.length;
  3222. while (j < jj) {
  3223. const [gStateKey] = gStateObj[j];
  3224. switch (gStateKey) {
  3225. case "TR":
  3226. case "TR2":
  3227. case "HT":
  3228. case "BG":
  3229. case "BG2":
  3230. case "UCR":
  3231. case "UCR2":
  3232. gStateObj.splice(j, 1);
  3233. jj--;
  3234. continue;
  3235. }
  3236. j++;
  3237. }
  3238. break;
  3239. }
  3240. i++;
  3241. }
  3242. }
  3243. }
  3244. class StateManager {
  3245. constructor(initialState = new EvalState()) {
  3246. this.state = initialState;
  3247. this.stateStack = [];
  3248. }
  3249. save() {
  3250. const old = this.state;
  3251. this.stateStack.push(this.state);
  3252. this.state = old.clone();
  3253. }
  3254. restore() {
  3255. const prev = this.stateStack.pop();
  3256. if (prev) {
  3257. this.state = prev;
  3258. }
  3259. }
  3260. transform(args) {
  3261. this.state.ctm = _util.Util.transform(this.state.ctm, args);
  3262. }
  3263. }
  3264. class TextState {
  3265. constructor() {
  3266. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  3267. this.fontName = null;
  3268. this.fontSize = 0;
  3269. this.font = null;
  3270. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  3271. this.textMatrix = _util.IDENTITY_MATRIX.slice();
  3272. this.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  3273. this.charSpacing = 0;
  3274. this.wordSpacing = 0;
  3275. this.leading = 0;
  3276. this.textHScale = 1;
  3277. this.textRise = 0;
  3278. }
  3279. setTextMatrix(a, b, c, d, e, f) {
  3280. const m = this.textMatrix;
  3281. m[0] = a;
  3282. m[1] = b;
  3283. m[2] = c;
  3284. m[3] = d;
  3285. m[4] = e;
  3286. m[5] = f;
  3287. }
  3288. setTextLineMatrix(a, b, c, d, e, f) {
  3289. const m = this.textLineMatrix;
  3290. m[0] = a;
  3291. m[1] = b;
  3292. m[2] = c;
  3293. m[3] = d;
  3294. m[4] = e;
  3295. m[5] = f;
  3296. }
  3297. translateTextMatrix(x, y) {
  3298. const m = this.textMatrix;
  3299. m[4] = m[0] * x + m[2] * y + m[4];
  3300. m[5] = m[1] * x + m[3] * y + m[5];
  3301. }
  3302. translateTextLineMatrix(x, y) {
  3303. const m = this.textLineMatrix;
  3304. m[4] = m[0] * x + m[2] * y + m[4];
  3305. m[5] = m[1] * x + m[3] * y + m[5];
  3306. }
  3307. carriageReturn() {
  3308. this.translateTextLineMatrix(0, -this.leading);
  3309. this.textMatrix = this.textLineMatrix.slice();
  3310. }
  3311. clone() {
  3312. const clone = Object.create(this);
  3313. clone.textMatrix = this.textMatrix.slice();
  3314. clone.textLineMatrix = this.textLineMatrix.slice();
  3315. clone.fontMatrix = this.fontMatrix.slice();
  3316. return clone;
  3317. }
  3318. }
  3319. class EvalState {
  3320. constructor() {
  3321. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  3322. this.font = null;
  3323. this.textRenderingMode = _util.TextRenderingMode.FILL;
  3324. this.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  3325. this.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  3326. }
  3327. clone() {
  3328. return Object.create(this);
  3329. }
  3330. }
  3331. class EvaluatorPreprocessor {
  3332. static get opMap() {
  3333. const getOPMap = (0, _core_utils.getLookupTableFactory)(function (t) {
  3334. t.w = {
  3335. id: _util.OPS.setLineWidth,
  3336. numArgs: 1,
  3337. variableArgs: false
  3338. };
  3339. t.J = {
  3340. id: _util.OPS.setLineCap,
  3341. numArgs: 1,
  3342. variableArgs: false
  3343. };
  3344. t.j = {
  3345. id: _util.OPS.setLineJoin,
  3346. numArgs: 1,
  3347. variableArgs: false
  3348. };
  3349. t.M = {
  3350. id: _util.OPS.setMiterLimit,
  3351. numArgs: 1,
  3352. variableArgs: false
  3353. };
  3354. t.d = {
  3355. id: _util.OPS.setDash,
  3356. numArgs: 2,
  3357. variableArgs: false
  3358. };
  3359. t.ri = {
  3360. id: _util.OPS.setRenderingIntent,
  3361. numArgs: 1,
  3362. variableArgs: false
  3363. };
  3364. t.i = {
  3365. id: _util.OPS.setFlatness,
  3366. numArgs: 1,
  3367. variableArgs: false
  3368. };
  3369. t.gs = {
  3370. id: _util.OPS.setGState,
  3371. numArgs: 1,
  3372. variableArgs: false
  3373. };
  3374. t.q = {
  3375. id: _util.OPS.save,
  3376. numArgs: 0,
  3377. variableArgs: false
  3378. };
  3379. t.Q = {
  3380. id: _util.OPS.restore,
  3381. numArgs: 0,
  3382. variableArgs: false
  3383. };
  3384. t.cm = {
  3385. id: _util.OPS.transform,
  3386. numArgs: 6,
  3387. variableArgs: false
  3388. };
  3389. t.m = {
  3390. id: _util.OPS.moveTo,
  3391. numArgs: 2,
  3392. variableArgs: false
  3393. };
  3394. t.l = {
  3395. id: _util.OPS.lineTo,
  3396. numArgs: 2,
  3397. variableArgs: false
  3398. };
  3399. t.c = {
  3400. id: _util.OPS.curveTo,
  3401. numArgs: 6,
  3402. variableArgs: false
  3403. };
  3404. t.v = {
  3405. id: _util.OPS.curveTo2,
  3406. numArgs: 4,
  3407. variableArgs: false
  3408. };
  3409. t.y = {
  3410. id: _util.OPS.curveTo3,
  3411. numArgs: 4,
  3412. variableArgs: false
  3413. };
  3414. t.h = {
  3415. id: _util.OPS.closePath,
  3416. numArgs: 0,
  3417. variableArgs: false
  3418. };
  3419. t.re = {
  3420. id: _util.OPS.rectangle,
  3421. numArgs: 4,
  3422. variableArgs: false
  3423. };
  3424. t.S = {
  3425. id: _util.OPS.stroke,
  3426. numArgs: 0,
  3427. variableArgs: false
  3428. };
  3429. t.s = {
  3430. id: _util.OPS.closeStroke,
  3431. numArgs: 0,
  3432. variableArgs: false
  3433. };
  3434. t.f = {
  3435. id: _util.OPS.fill,
  3436. numArgs: 0,
  3437. variableArgs: false
  3438. };
  3439. t.F = {
  3440. id: _util.OPS.fill,
  3441. numArgs: 0,
  3442. variableArgs: false
  3443. };
  3444. t["f*"] = {
  3445. id: _util.OPS.eoFill,
  3446. numArgs: 0,
  3447. variableArgs: false
  3448. };
  3449. t.B = {
  3450. id: _util.OPS.fillStroke,
  3451. numArgs: 0,
  3452. variableArgs: false
  3453. };
  3454. t["B*"] = {
  3455. id: _util.OPS.eoFillStroke,
  3456. numArgs: 0,
  3457. variableArgs: false
  3458. };
  3459. t.b = {
  3460. id: _util.OPS.closeFillStroke,
  3461. numArgs: 0,
  3462. variableArgs: false
  3463. };
  3464. t["b*"] = {
  3465. id: _util.OPS.closeEOFillStroke,
  3466. numArgs: 0,
  3467. variableArgs: false
  3468. };
  3469. t.n = {
  3470. id: _util.OPS.endPath,
  3471. numArgs: 0,
  3472. variableArgs: false
  3473. };
  3474. t.W = {
  3475. id: _util.OPS.clip,
  3476. numArgs: 0,
  3477. variableArgs: false
  3478. };
  3479. t["W*"] = {
  3480. id: _util.OPS.eoClip,
  3481. numArgs: 0,
  3482. variableArgs: false
  3483. };
  3484. t.BT = {
  3485. id: _util.OPS.beginText,
  3486. numArgs: 0,
  3487. variableArgs: false
  3488. };
  3489. t.ET = {
  3490. id: _util.OPS.endText,
  3491. numArgs: 0,
  3492. variableArgs: false
  3493. };
  3494. t.Tc = {
  3495. id: _util.OPS.setCharSpacing,
  3496. numArgs: 1,
  3497. variableArgs: false
  3498. };
  3499. t.Tw = {
  3500. id: _util.OPS.setWordSpacing,
  3501. numArgs: 1,
  3502. variableArgs: false
  3503. };
  3504. t.Tz = {
  3505. id: _util.OPS.setHScale,
  3506. numArgs: 1,
  3507. variableArgs: false
  3508. };
  3509. t.TL = {
  3510. id: _util.OPS.setLeading,
  3511. numArgs: 1,
  3512. variableArgs: false
  3513. };
  3514. t.Tf = {
  3515. id: _util.OPS.setFont,
  3516. numArgs: 2,
  3517. variableArgs: false
  3518. };
  3519. t.Tr = {
  3520. id: _util.OPS.setTextRenderingMode,
  3521. numArgs: 1,
  3522. variableArgs: false
  3523. };
  3524. t.Ts = {
  3525. id: _util.OPS.setTextRise,
  3526. numArgs: 1,
  3527. variableArgs: false
  3528. };
  3529. t.Td = {
  3530. id: _util.OPS.moveText,
  3531. numArgs: 2,
  3532. variableArgs: false
  3533. };
  3534. t.TD = {
  3535. id: _util.OPS.setLeadingMoveText,
  3536. numArgs: 2,
  3537. variableArgs: false
  3538. };
  3539. t.Tm = {
  3540. id: _util.OPS.setTextMatrix,
  3541. numArgs: 6,
  3542. variableArgs: false
  3543. };
  3544. t["T*"] = {
  3545. id: _util.OPS.nextLine,
  3546. numArgs: 0,
  3547. variableArgs: false
  3548. };
  3549. t.Tj = {
  3550. id: _util.OPS.showText,
  3551. numArgs: 1,
  3552. variableArgs: false
  3553. };
  3554. t.TJ = {
  3555. id: _util.OPS.showSpacedText,
  3556. numArgs: 1,
  3557. variableArgs: false
  3558. };
  3559. t["'"] = {
  3560. id: _util.OPS.nextLineShowText,
  3561. numArgs: 1,
  3562. variableArgs: false
  3563. };
  3564. t['"'] = {
  3565. id: _util.OPS.nextLineSetSpacingShowText,
  3566. numArgs: 3,
  3567. variableArgs: false
  3568. };
  3569. t.d0 = {
  3570. id: _util.OPS.setCharWidth,
  3571. numArgs: 2,
  3572. variableArgs: false
  3573. };
  3574. t.d1 = {
  3575. id: _util.OPS.setCharWidthAndBounds,
  3576. numArgs: 6,
  3577. variableArgs: false
  3578. };
  3579. t.CS = {
  3580. id: _util.OPS.setStrokeColorSpace,
  3581. numArgs: 1,
  3582. variableArgs: false
  3583. };
  3584. t.cs = {
  3585. id: _util.OPS.setFillColorSpace,
  3586. numArgs: 1,
  3587. variableArgs: false
  3588. };
  3589. t.SC = {
  3590. id: _util.OPS.setStrokeColor,
  3591. numArgs: 4,
  3592. variableArgs: true
  3593. };
  3594. t.SCN = {
  3595. id: _util.OPS.setStrokeColorN,
  3596. numArgs: 33,
  3597. variableArgs: true
  3598. };
  3599. t.sc = {
  3600. id: _util.OPS.setFillColor,
  3601. numArgs: 4,
  3602. variableArgs: true
  3603. };
  3604. t.scn = {
  3605. id: _util.OPS.setFillColorN,
  3606. numArgs: 33,
  3607. variableArgs: true
  3608. };
  3609. t.G = {
  3610. id: _util.OPS.setStrokeGray,
  3611. numArgs: 1,
  3612. variableArgs: false
  3613. };
  3614. t.g = {
  3615. id: _util.OPS.setFillGray,
  3616. numArgs: 1,
  3617. variableArgs: false
  3618. };
  3619. t.RG = {
  3620. id: _util.OPS.setStrokeRGBColor,
  3621. numArgs: 3,
  3622. variableArgs: false
  3623. };
  3624. t.rg = {
  3625. id: _util.OPS.setFillRGBColor,
  3626. numArgs: 3,
  3627. variableArgs: false
  3628. };
  3629. t.K = {
  3630. id: _util.OPS.setStrokeCMYKColor,
  3631. numArgs: 4,
  3632. variableArgs: false
  3633. };
  3634. t.k = {
  3635. id: _util.OPS.setFillCMYKColor,
  3636. numArgs: 4,
  3637. variableArgs: false
  3638. };
  3639. t.sh = {
  3640. id: _util.OPS.shadingFill,
  3641. numArgs: 1,
  3642. variableArgs: false
  3643. };
  3644. t.BI = {
  3645. id: _util.OPS.beginInlineImage,
  3646. numArgs: 0,
  3647. variableArgs: false
  3648. };
  3649. t.ID = {
  3650. id: _util.OPS.beginImageData,
  3651. numArgs: 0,
  3652. variableArgs: false
  3653. };
  3654. t.EI = {
  3655. id: _util.OPS.endInlineImage,
  3656. numArgs: 1,
  3657. variableArgs: false
  3658. };
  3659. t.Do = {
  3660. id: _util.OPS.paintXObject,
  3661. numArgs: 1,
  3662. variableArgs: false
  3663. };
  3664. t.MP = {
  3665. id: _util.OPS.markPoint,
  3666. numArgs: 1,
  3667. variableArgs: false
  3668. };
  3669. t.DP = {
  3670. id: _util.OPS.markPointProps,
  3671. numArgs: 2,
  3672. variableArgs: false
  3673. };
  3674. t.BMC = {
  3675. id: _util.OPS.beginMarkedContent,
  3676. numArgs: 1,
  3677. variableArgs: false
  3678. };
  3679. t.BDC = {
  3680. id: _util.OPS.beginMarkedContentProps,
  3681. numArgs: 2,
  3682. variableArgs: false
  3683. };
  3684. t.EMC = {
  3685. id: _util.OPS.endMarkedContent,
  3686. numArgs: 0,
  3687. variableArgs: false
  3688. };
  3689. t.BX = {
  3690. id: _util.OPS.beginCompat,
  3691. numArgs: 0,
  3692. variableArgs: false
  3693. };
  3694. t.EX = {
  3695. id: _util.OPS.endCompat,
  3696. numArgs: 0,
  3697. variableArgs: false
  3698. };
  3699. t.BM = null;
  3700. t.BD = null;
  3701. t.true = null;
  3702. t.fa = null;
  3703. t.fal = null;
  3704. t.fals = null;
  3705. t.false = null;
  3706. t.nu = null;
  3707. t.nul = null;
  3708. t.null = null;
  3709. });
  3710. return (0, _util.shadow)(this, "opMap", getOPMap());
  3711. }
  3712. static get MAX_INVALID_PATH_OPS() {
  3713. return (0, _util.shadow)(this, "MAX_INVALID_PATH_OPS", 10);
  3714. }
  3715. constructor(stream, xref, stateManager = new StateManager()) {
  3716. this.parser = new _parser.Parser({
  3717. lexer: new _parser.Lexer(stream, EvaluatorPreprocessor.opMap),
  3718. xref
  3719. });
  3720. this.stateManager = stateManager;
  3721. this.nonProcessedArgs = [];
  3722. this._isPathOp = false;
  3723. this._numInvalidPathOPS = 0;
  3724. }
  3725. get savedStatesDepth() {
  3726. return this.stateManager.stateStack.length;
  3727. }
  3728. read(operation) {
  3729. let args = operation.args;
  3730. while (true) {
  3731. const obj = this.parser.getObj();
  3732. if (obj instanceof _primitives.Cmd) {
  3733. const cmd = obj.cmd;
  3734. const opSpec = EvaluatorPreprocessor.opMap[cmd];
  3735. if (!opSpec) {
  3736. (0, _util.warn)(`Unknown command "${cmd}".`);
  3737. continue;
  3738. }
  3739. const fn = opSpec.id;
  3740. const numArgs = opSpec.numArgs;
  3741. let argsLength = args !== null ? args.length : 0;
  3742. if (!this._isPathOp) {
  3743. this._numInvalidPathOPS = 0;
  3744. }
  3745. this._isPathOp = fn >= _util.OPS.moveTo && fn <= _util.OPS.endPath;
  3746. if (!opSpec.variableArgs) {
  3747. if (argsLength !== numArgs) {
  3748. const nonProcessedArgs = this.nonProcessedArgs;
  3749. while (argsLength > numArgs) {
  3750. nonProcessedArgs.push(args.shift());
  3751. argsLength--;
  3752. }
  3753. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  3754. if (args === null) {
  3755. args = [];
  3756. }
  3757. args.unshift(nonProcessedArgs.pop());
  3758. argsLength++;
  3759. }
  3760. }
  3761. if (argsLength < numArgs) {
  3762. const partialMsg = `command ${cmd}: expected ${numArgs} args, ` + `but received ${argsLength} args.`;
  3763. if (this._isPathOp && ++this._numInvalidPathOPS > EvaluatorPreprocessor.MAX_INVALID_PATH_OPS) {
  3764. throw new _util.FormatError(`Invalid ${partialMsg}`);
  3765. }
  3766. (0, _util.warn)(`Skipping ${partialMsg}`);
  3767. if (args !== null) {
  3768. args.length = 0;
  3769. }
  3770. continue;
  3771. }
  3772. } else if (argsLength > numArgs) {
  3773. (0, _util.info)(`Command ${cmd}: expected [0, ${numArgs}] args, ` + `but received ${argsLength} args.`);
  3774. }
  3775. this.preprocessCommand(fn, args);
  3776. operation.fn = fn;
  3777. operation.args = args;
  3778. return true;
  3779. }
  3780. if (obj === _primitives.EOF) {
  3781. return false;
  3782. }
  3783. if (obj !== null) {
  3784. if (args === null) {
  3785. args = [];
  3786. }
  3787. args.push(obj);
  3788. if (args.length > 33) {
  3789. throw new _util.FormatError("Too many arguments");
  3790. }
  3791. }
  3792. }
  3793. }
  3794. preprocessCommand(fn, args) {
  3795. switch (fn | 0) {
  3796. case _util.OPS.save:
  3797. this.stateManager.save();
  3798. break;
  3799. case _util.OPS.restore:
  3800. this.stateManager.restore();
  3801. break;
  3802. case _util.OPS.transform:
  3803. this.stateManager.transform(args);
  3804. break;
  3805. }
  3806. }
  3807. }
  3808. exports.EvaluatorPreprocessor = EvaluatorPreprocessor;