evaluator.js 129 KB

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