evaluator.js 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 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 = 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 _encodings = require("./encodings.js");
  32. var _core_utils = require("./core_utils.js");
  33. var _unicode = require("./unicode.js");
  34. var _standard_fonts = require("./standard_fonts.js");
  35. var _pattern = require("./pattern.js");
  36. var _parser = require("./parser.js");
  37. var _bidi = require("./bidi.js");
  38. var _colorspace = require("./colorspace.js");
  39. var _stream = require("./stream.js");
  40. var _glyphlist = require("./glyphlist.js");
  41. var _metrics = require("./metrics.js");
  42. var _function = require("./function.js");
  43. var _jpeg_stream = require("./jpeg_stream.js");
  44. var _murmurhash = require("./murmurhash3.js");
  45. var _image_utils = require("./image_utils.js");
  46. var _operator_list = require("./operator_list.js");
  47. var _image = require("./image.js");
  48. var PartialEvaluator = function PartialEvaluatorClosure() {
  49. const DefaultPartialEvaluatorOptions = {
  50. forceDataSchema: false,
  51. maxImageSize: -1,
  52. disableFontFace: false,
  53. nativeImageDecoderSupport: _util.NativeImageDecoding.DECODE,
  54. ignoreErrors: false,
  55. isEvalSupported: true
  56. };
  57. function PartialEvaluator({
  58. xref,
  59. handler,
  60. pageIndex,
  61. idFactory,
  62. fontCache,
  63. builtInCMapCache,
  64. options = null,
  65. pdfFunctionFactory
  66. }) {
  67. this.xref = xref;
  68. this.handler = handler;
  69. this.pageIndex = pageIndex;
  70. this.idFactory = idFactory;
  71. this.fontCache = fontCache;
  72. this.builtInCMapCache = builtInCMapCache;
  73. this.options = options || DefaultPartialEvaluatorOptions;
  74. this.pdfFunctionFactory = pdfFunctionFactory;
  75. this.parsingType3Font = false;
  76. this.fetchBuiltInCMap = async name => {
  77. if (this.builtInCMapCache.has(name)) {
  78. return this.builtInCMapCache.get(name);
  79. }
  80. const readableStream = this.handler.sendWithStream("FetchBuiltInCMap", {
  81. name
  82. });
  83. const reader = readableStream.getReader();
  84. const data = await new Promise(function (resolve, reject) {
  85. function pump() {
  86. reader.read().then(function ({
  87. value,
  88. done
  89. }) {
  90. if (done) {
  91. return;
  92. }
  93. resolve(value);
  94. pump();
  95. }, reject);
  96. }
  97. pump();
  98. });
  99. if (data.compressionType !== _util.CMapCompressionType.NONE) {
  100. this.builtInCMapCache.set(name, data);
  101. }
  102. return data;
  103. };
  104. }
  105. var TIME_SLOT_DURATION_MS = 20;
  106. var CHECK_TIME_EVERY = 100;
  107. function TimeSlotManager() {
  108. this.reset();
  109. }
  110. TimeSlotManager.prototype = {
  111. check: function TimeSlotManager_check() {
  112. if (++this.checked < CHECK_TIME_EVERY) {
  113. return false;
  114. }
  115. this.checked = 0;
  116. return this.endTime <= Date.now();
  117. },
  118. reset: function TimeSlotManager_reset() {
  119. this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
  120. this.checked = 0;
  121. }
  122. };
  123. function normalizeBlendMode(value, parsingArray = false) {
  124. if (Array.isArray(value)) {
  125. for (let i = 0, ii = value.length; i < ii; i++) {
  126. const maybeBM = normalizeBlendMode(value[i], true);
  127. if (maybeBM) {
  128. return maybeBM;
  129. }
  130. }
  131. (0, _util.warn)(`Unsupported blend mode Array: ${value}`);
  132. return "source-over";
  133. }
  134. if (!(0, _primitives.isName)(value)) {
  135. if (parsingArray) {
  136. return null;
  137. }
  138. return "source-over";
  139. }
  140. switch (value.name) {
  141. case "Normal":
  142. case "Compatible":
  143. return "source-over";
  144. case "Multiply":
  145. return "multiply";
  146. case "Screen":
  147. return "screen";
  148. case "Overlay":
  149. return "overlay";
  150. case "Darken":
  151. return "darken";
  152. case "Lighten":
  153. return "lighten";
  154. case "ColorDodge":
  155. return "color-dodge";
  156. case "ColorBurn":
  157. return "color-burn";
  158. case "HardLight":
  159. return "hard-light";
  160. case "SoftLight":
  161. return "soft-light";
  162. case "Difference":
  163. return "difference";
  164. case "Exclusion":
  165. return "exclusion";
  166. case "Hue":
  167. return "hue";
  168. case "Saturation":
  169. return "saturation";
  170. case "Color":
  171. return "color";
  172. case "Luminosity":
  173. return "luminosity";
  174. }
  175. if (parsingArray) {
  176. return null;
  177. }
  178. (0, _util.warn)(`Unsupported blend mode: ${value.name}`);
  179. return "source-over";
  180. }
  181. var deferred = Promise.resolve();
  182. var TILING_PATTERN = 1,
  183. SHADING_PATTERN = 2;
  184. PartialEvaluator.prototype = {
  185. clone(newOptions = DefaultPartialEvaluatorOptions) {
  186. var newEvaluator = Object.create(this);
  187. newEvaluator.options = newOptions;
  188. return newEvaluator;
  189. },
  190. hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
  191. if (!(resources instanceof _primitives.Dict)) {
  192. return false;
  193. }
  194. var processed = Object.create(null);
  195. if (resources.objId) {
  196. processed[resources.objId] = true;
  197. }
  198. var nodes = [resources],
  199. xref = this.xref;
  200. while (nodes.length) {
  201. var node = nodes.shift();
  202. var graphicStates = node.get("ExtGState");
  203. if (graphicStates instanceof _primitives.Dict) {
  204. var graphicStatesKeys = graphicStates.getKeys();
  205. for (let i = 0, ii = graphicStatesKeys.length; i < ii; i++) {
  206. const key = graphicStatesKeys[i];
  207. let graphicState = graphicStates.getRaw(key);
  208. if (graphicState instanceof _primitives.Ref) {
  209. if (processed[graphicState.toString()]) {
  210. continue;
  211. }
  212. try {
  213. graphicState = xref.fetch(graphicState);
  214. } catch (ex) {
  215. if (ex instanceof _core_utils.MissingDataException) {
  216. throw ex;
  217. }
  218. if (this.options.ignoreErrors) {
  219. if (graphicState instanceof _primitives.Ref) {
  220. processed[graphicState.toString()] = true;
  221. }
  222. this.handler.send("UnsupportedFeature", {
  223. featureId: _util.UNSUPPORTED_FEATURES.unknown
  224. });
  225. (0, _util.warn)(`hasBlendModes - ignoring ExtGState: "${ex}".`);
  226. continue;
  227. }
  228. throw ex;
  229. }
  230. }
  231. if (!(graphicState instanceof _primitives.Dict)) {
  232. continue;
  233. }
  234. if (graphicState.objId) {
  235. processed[graphicState.objId] = true;
  236. }
  237. const bm = graphicState.get("BM");
  238. if (bm instanceof _primitives.Name) {
  239. if (bm.name !== "Normal") {
  240. return true;
  241. }
  242. continue;
  243. }
  244. if (bm !== undefined && Array.isArray(bm)) {
  245. for (let j = 0, jj = bm.length; j < jj; j++) {
  246. if (bm[j] instanceof _primitives.Name && bm[j].name !== "Normal") {
  247. return true;
  248. }
  249. }
  250. }
  251. }
  252. }
  253. var xObjects = node.get("XObject");
  254. if (!(xObjects instanceof _primitives.Dict)) {
  255. continue;
  256. }
  257. var xObjectsKeys = xObjects.getKeys();
  258. for (let i = 0, ii = xObjectsKeys.length; i < ii; i++) {
  259. const key = xObjectsKeys[i];
  260. var xObject = xObjects.getRaw(key);
  261. if (xObject instanceof _primitives.Ref) {
  262. if (processed[xObject.toString()]) {
  263. continue;
  264. }
  265. try {
  266. xObject = xref.fetch(xObject);
  267. } catch (ex) {
  268. if (ex instanceof _core_utils.MissingDataException) {
  269. throw ex;
  270. }
  271. if (this.options.ignoreErrors) {
  272. if (xObject instanceof _primitives.Ref) {
  273. processed[xObject.toString()] = true;
  274. }
  275. this.handler.send("UnsupportedFeature", {
  276. featureId: _util.UNSUPPORTED_FEATURES.unknown
  277. });
  278. (0, _util.warn)(`hasBlendModes - ignoring XObject: "${ex}".`);
  279. continue;
  280. }
  281. throw ex;
  282. }
  283. }
  284. if (!(0, _primitives.isStream)(xObject)) {
  285. continue;
  286. }
  287. if (xObject.dict.objId) {
  288. if (processed[xObject.dict.objId]) {
  289. continue;
  290. }
  291. processed[xObject.dict.objId] = true;
  292. }
  293. var xResources = xObject.dict.get("Resources");
  294. if (xResources instanceof _primitives.Dict && (!xResources.objId || !processed[xResources.objId])) {
  295. nodes.push(xResources);
  296. if (xResources.objId) {
  297. processed[xResources.objId] = true;
  298. }
  299. }
  300. }
  301. }
  302. return false;
  303. },
  304. async buildFormXObject(resources, xobj, smask, operatorList, task, initialState) {
  305. var dict = xobj.dict;
  306. var matrix = dict.getArray("Matrix");
  307. var bbox = dict.getArray("BBox");
  308. if (Array.isArray(bbox) && bbox.length === 4) {
  309. bbox = _util.Util.normalizeRect(bbox);
  310. } else {
  311. bbox = null;
  312. }
  313. var group = dict.get("Group");
  314. if (group) {
  315. var groupOptions = {
  316. matrix,
  317. bbox,
  318. smask,
  319. isolated: false,
  320. knockout: false
  321. };
  322. var groupSubtype = group.get("S");
  323. var colorSpace = null;
  324. if ((0, _primitives.isName)(groupSubtype, "Transparency")) {
  325. groupOptions.isolated = group.get("I") || false;
  326. groupOptions.knockout = group.get("K") || false;
  327. if (group.has("CS")) {
  328. colorSpace = await this.parseColorSpace({
  329. cs: group.get("CS"),
  330. resources
  331. });
  332. }
  333. }
  334. if (smask && smask.backdrop) {
  335. colorSpace = colorSpace || _colorspace.ColorSpace.singletons.rgb;
  336. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  337. }
  338. operatorList.addOp(_util.OPS.beginGroup, [groupOptions]);
  339. }
  340. operatorList.addOp(_util.OPS.paintFormXObjectBegin, [matrix, bbox]);
  341. return this.getOperatorList({
  342. stream: xobj,
  343. task,
  344. resources: dict.get("Resources") || resources,
  345. operatorList,
  346. initialState
  347. }).then(function () {
  348. operatorList.addOp(_util.OPS.paintFormXObjectEnd, []);
  349. if (group) {
  350. operatorList.addOp(_util.OPS.endGroup, [groupOptions]);
  351. }
  352. });
  353. },
  354. async buildPaintImageXObject({
  355. resources,
  356. image,
  357. isInline = false,
  358. operatorList,
  359. cacheKey,
  360. imageCache,
  361. forceDisableNativeImageDecoder = false
  362. }) {
  363. var dict = image.dict;
  364. var w = dict.get("Width", "W");
  365. var h = dict.get("Height", "H");
  366. if (!(w && (0, _util.isNum)(w)) || !(h && (0, _util.isNum)(h))) {
  367. (0, _util.warn)("Image dimensions are missing, or not numbers.");
  368. return undefined;
  369. }
  370. var maxImageSize = this.options.maxImageSize;
  371. if (maxImageSize !== -1 && w * h > maxImageSize) {
  372. (0, _util.warn)("Image exceeded maximum allowed size and was removed.");
  373. return undefined;
  374. }
  375. var imageMask = dict.get("ImageMask", "IM") || false;
  376. var imgData, args;
  377. if (imageMask) {
  378. var width = dict.get("Width", "W");
  379. var height = dict.get("Height", "H");
  380. var bitStrideLength = width + 7 >> 3;
  381. var imgArray = image.getBytes(bitStrideLength * height, true);
  382. var decode = dict.getArray("Decode", "D");
  383. imgData = _image.PDFImage.createMask({
  384. imgArray,
  385. width,
  386. height,
  387. imageIsFromDecodeStream: image instanceof _stream.DecodeStream,
  388. inverseDecode: !!decode && decode[0] > 0
  389. });
  390. imgData.cached = !!cacheKey;
  391. args = [imgData];
  392. operatorList.addOp(_util.OPS.paintImageMaskXObject, args);
  393. if (cacheKey) {
  394. imageCache[cacheKey] = {
  395. fn: _util.OPS.paintImageMaskXObject,
  396. args
  397. };
  398. }
  399. return undefined;
  400. }
  401. var softMask = dict.get("SMask", "SM") || false;
  402. var mask = dict.get("Mask") || false;
  403. var SMALL_IMAGE_DIMENSIONS = 200;
  404. if (isInline && !softMask && !mask && !(image instanceof _jpeg_stream.JpegStream) && w + h < SMALL_IMAGE_DIMENSIONS) {
  405. const imageObj = new _image.PDFImage({
  406. xref: this.xref,
  407. res: resources,
  408. image,
  409. isInline,
  410. pdfFunctionFactory: this.pdfFunctionFactory
  411. });
  412. imgData = imageObj.createImageData(true);
  413. operatorList.addOp(_util.OPS.paintInlineImageXObject, [imgData]);
  414. return undefined;
  415. }
  416. const nativeImageDecoderSupport = forceDisableNativeImageDecoder ? _util.NativeImageDecoding.NONE : this.options.nativeImageDecoderSupport;
  417. let objId = `img_${this.idFactory.createObjId()}`;
  418. if (this.parsingType3Font) {
  419. (0, _util.assert)(nativeImageDecoderSupport === _util.NativeImageDecoding.NONE, "Type3 image resources should be completely decoded in the worker.");
  420. objId = `${this.idFactory.getDocId()}_type3res_${objId}`;
  421. }
  422. if (nativeImageDecoderSupport !== _util.NativeImageDecoding.NONE && !softMask && !mask && image instanceof _jpeg_stream.JpegStream && _image_utils.NativeImageDecoder.isSupported(image, this.xref, resources, this.pdfFunctionFactory) && image.maybeValidDimensions) {
  423. return this.handler.sendWithPromise("obj", [objId, this.pageIndex, "JpegStream", image.getIR(this.options.forceDataSchema)]).then(function () {
  424. operatorList.addDependency(objId);
  425. args = [objId, w, h];
  426. operatorList.addOp(_util.OPS.paintJpegXObject, args);
  427. if (cacheKey) {
  428. imageCache[cacheKey] = {
  429. fn: _util.OPS.paintJpegXObject,
  430. args
  431. };
  432. }
  433. }, reason => {
  434. (0, _util.warn)("Native JPEG decoding failed -- trying to recover: " + (reason && reason.message));
  435. return this.buildPaintImageXObject({
  436. resources,
  437. image,
  438. isInline,
  439. operatorList,
  440. cacheKey,
  441. imageCache,
  442. forceDisableNativeImageDecoder: true
  443. });
  444. });
  445. }
  446. var nativeImageDecoder = null;
  447. if (nativeImageDecoderSupport === _util.NativeImageDecoding.DECODE && (image instanceof _jpeg_stream.JpegStream || mask instanceof _jpeg_stream.JpegStream || softMask instanceof _jpeg_stream.JpegStream)) {
  448. nativeImageDecoder = new _image_utils.NativeImageDecoder({
  449. xref: this.xref,
  450. resources,
  451. handler: this.handler,
  452. forceDataSchema: this.options.forceDataSchema,
  453. pdfFunctionFactory: this.pdfFunctionFactory
  454. });
  455. }
  456. operatorList.addDependency(objId);
  457. args = [objId, w, h];
  458. const imgPromise = _image.PDFImage.buildImage({
  459. handler: this.handler,
  460. xref: this.xref,
  461. res: resources,
  462. image,
  463. isInline,
  464. nativeDecoder: nativeImageDecoder,
  465. pdfFunctionFactory: this.pdfFunctionFactory
  466. }).then(imageObj => {
  467. var imgData = imageObj.createImageData(false);
  468. if (this.parsingType3Font) {
  469. return this.handler.sendWithPromise("commonobj", [objId, "FontType3Res", imgData], [imgData.data.buffer]);
  470. }
  471. this.handler.send("obj", [objId, this.pageIndex, "Image", imgData], [imgData.data.buffer]);
  472. return undefined;
  473. }).catch(reason => {
  474. (0, _util.warn)("Unable to decode image: " + reason);
  475. if (this.parsingType3Font) {
  476. return this.handler.sendWithPromise("commonobj", [objId, "FontType3Res", null]);
  477. }
  478. this.handler.send("obj", [objId, this.pageIndex, "Image", null]);
  479. return undefined;
  480. });
  481. if (this.parsingType3Font) {
  482. await imgPromise;
  483. }
  484. operatorList.addOp(_util.OPS.paintImageXObject, args);
  485. if (cacheKey) {
  486. imageCache[cacheKey] = {
  487. fn: _util.OPS.paintImageXObject,
  488. args
  489. };
  490. }
  491. return undefined;
  492. },
  493. handleSMask: function PartialEvaluator_handleSmask(smask, resources, operatorList, task, stateManager) {
  494. var smaskContent = smask.get("G");
  495. var smaskOptions = {
  496. subtype: smask.get("S").name,
  497. backdrop: smask.get("BC")
  498. };
  499. var transferObj = smask.get("TR");
  500. if ((0, _function.isPDFFunction)(transferObj)) {
  501. const transferFn = this.pdfFunctionFactory.create(transferObj);
  502. var transferMap = new Uint8Array(256);
  503. var tmp = new Float32Array(1);
  504. for (var i = 0; i < 256; i++) {
  505. tmp[0] = i / 255;
  506. transferFn(tmp, 0, tmp, 0);
  507. transferMap[i] = tmp[0] * 255 | 0;
  508. }
  509. smaskOptions.transferMap = transferMap;
  510. }
  511. return this.buildFormXObject(resources, smaskContent, smaskOptions, operatorList, task, stateManager.state.clone());
  512. },
  513. handleTilingType(fn, args, resources, pattern, patternDict, operatorList, task) {
  514. const tilingOpList = new _operator_list.OperatorList();
  515. const resourcesArray = [patternDict.get("Resources"), resources];
  516. const patternResources = _primitives.Dict.merge(this.xref, resourcesArray);
  517. return this.getOperatorList({
  518. stream: pattern,
  519. task,
  520. resources: patternResources,
  521. operatorList: tilingOpList
  522. }).then(function () {
  523. return (0, _pattern.getTilingPatternIR)({
  524. fnArray: tilingOpList.fnArray,
  525. argsArray: tilingOpList.argsArray
  526. }, patternDict, args);
  527. }).then(function (tilingPatternIR) {
  528. operatorList.addDependencies(tilingOpList.dependencies);
  529. operatorList.addOp(fn, tilingPatternIR);
  530. }, reason => {
  531. if (reason instanceof _util.AbortException) {
  532. return;
  533. }
  534. if (this.options.ignoreErrors) {
  535. this.handler.send("UnsupportedFeature", {
  536. featureId: _util.UNSUPPORTED_FEATURES.unknown
  537. });
  538. (0, _util.warn)(`handleTilingType - ignoring pattern: "${reason}".`);
  539. return;
  540. }
  541. throw reason;
  542. });
  543. },
  544. handleSetFont: function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef, operatorList, task, state) {
  545. var fontName;
  546. if (fontArgs) {
  547. fontArgs = fontArgs.slice();
  548. fontName = fontArgs[0].name;
  549. }
  550. return this.loadFont(fontName, fontRef, resources).then(translated => {
  551. if (!translated.font.isType3Font) {
  552. return translated;
  553. }
  554. return translated.loadType3Data(this, resources, operatorList, task).then(function () {
  555. return translated;
  556. }).catch(reason => {
  557. this.handler.send("UnsupportedFeature", {
  558. featureId: _util.UNSUPPORTED_FEATURES.font
  559. });
  560. return new TranslatedFont("g_font_error", new _fonts.ErrorFont("Type3 font load error: " + reason), translated.font);
  561. });
  562. }).then(translated => {
  563. state.font = translated.font;
  564. translated.send(this.handler);
  565. return translated.loadedName;
  566. });
  567. },
  568. handleText(chars, state) {
  569. const font = state.font;
  570. const glyphs = font.charsToGlyphs(chars);
  571. if (font.data) {
  572. const isAddToPathSet = !!(state.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  573. if (isAddToPathSet || state.fillColorSpace.name === "Pattern" || font.disableFontFace || this.options.disableFontFace) {
  574. PartialEvaluator.buildFontPaths(font, glyphs, this.handler);
  575. }
  576. }
  577. return glyphs;
  578. },
  579. ensureStateFont(state) {
  580. if (state.font) {
  581. return;
  582. }
  583. const reason = new _util.FormatError("Missing setFont (Tf) operator before text rendering operator.");
  584. if (this.options.ignoreErrors) {
  585. this.handler.send("UnsupportedFeature", {
  586. featureId: _util.UNSUPPORTED_FEATURES.font
  587. });
  588. (0, _util.warn)(`ensureStateFont: "${reason}".`);
  589. return;
  590. }
  591. throw reason;
  592. },
  593. setGState: function PartialEvaluator_setGState(resources, gState, operatorList, task, stateManager) {
  594. var gStateObj = [];
  595. var gStateKeys = gState.getKeys();
  596. var promise = Promise.resolve();
  597. for (var i = 0, ii = gStateKeys.length; i < ii; i++) {
  598. const key = gStateKeys[i];
  599. const value = gState.get(key);
  600. switch (key) {
  601. case "Type":
  602. break;
  603. case "LW":
  604. case "LC":
  605. case "LJ":
  606. case "ML":
  607. case "D":
  608. case "RI":
  609. case "FL":
  610. case "CA":
  611. case "ca":
  612. gStateObj.push([key, value]);
  613. break;
  614. case "Font":
  615. promise = promise.then(() => {
  616. return this.handleSetFont(resources, null, value[0], operatorList, task, stateManager.state).then(function (loadedName) {
  617. operatorList.addDependency(loadedName);
  618. gStateObj.push([key, [loadedName, value[1]]]);
  619. });
  620. });
  621. break;
  622. case "BM":
  623. gStateObj.push([key, normalizeBlendMode(value)]);
  624. break;
  625. case "SMask":
  626. if ((0, _primitives.isName)(value, "None")) {
  627. gStateObj.push([key, false]);
  628. break;
  629. }
  630. if ((0, _primitives.isDict)(value)) {
  631. promise = promise.then(() => {
  632. return this.handleSMask(value, resources, operatorList, task, stateManager);
  633. });
  634. gStateObj.push([key, true]);
  635. } else {
  636. (0, _util.warn)("Unsupported SMask type");
  637. }
  638. break;
  639. case "OP":
  640. case "op":
  641. case "OPM":
  642. case "BG":
  643. case "BG2":
  644. case "UCR":
  645. case "UCR2":
  646. case "TR":
  647. case "TR2":
  648. case "HT":
  649. case "SM":
  650. case "SA":
  651. case "AIS":
  652. case "TK":
  653. (0, _util.info)("graphic state operator " + key);
  654. break;
  655. default:
  656. (0, _util.info)("Unknown graphic state operator " + key);
  657. break;
  658. }
  659. }
  660. return promise.then(function () {
  661. if (gStateObj.length > 0) {
  662. operatorList.addOp(_util.OPS.setGState, [gStateObj]);
  663. }
  664. });
  665. },
  666. loadFont: function PartialEvaluator_loadFont(fontName, font, resources) {
  667. function errorFont() {
  668. return Promise.resolve(new TranslatedFont("g_font_error", new _fonts.ErrorFont("Font " + fontName + " is not available"), font));
  669. }
  670. var fontRef,
  671. xref = this.xref;
  672. if (font) {
  673. if (!(0, _primitives.isRef)(font)) {
  674. throw new _util.FormatError('The "font" object should be a reference.');
  675. }
  676. fontRef = font;
  677. } else {
  678. var fontRes = resources.get("Font");
  679. if (fontRes) {
  680. fontRef = fontRes.getRaw(fontName);
  681. }
  682. }
  683. if (!fontRef) {
  684. const partialMsg = `Font "${fontName || font && font.toString()}" is not available`;
  685. if (!this.options.ignoreErrors && !this.parsingType3Font) {
  686. (0, _util.warn)(`${partialMsg}.`);
  687. return errorFont();
  688. }
  689. this.handler.send("UnsupportedFeature", {
  690. featureId: _util.UNSUPPORTED_FEATURES.font
  691. });
  692. (0, _util.warn)(`${partialMsg} -- attempting to fallback to a default font.`);
  693. fontRef = PartialEvaluator.getFallbackFontDict();
  694. }
  695. if (this.fontCache.has(fontRef)) {
  696. return this.fontCache.get(fontRef);
  697. }
  698. font = xref.fetchIfRef(fontRef);
  699. if (!(0, _primitives.isDict)(font)) {
  700. return errorFont();
  701. }
  702. if (font.translated) {
  703. return font.translated;
  704. }
  705. var fontCapability = (0, _util.createPromiseCapability)();
  706. var preEvaluatedFont = this.preEvaluateFont(font);
  707. const {
  708. descriptor,
  709. hash
  710. } = preEvaluatedFont;
  711. var fontRefIsRef = (0, _primitives.isRef)(fontRef),
  712. fontID;
  713. if (fontRefIsRef) {
  714. fontID = fontRef.toString();
  715. }
  716. if (hash && (0, _primitives.isDict)(descriptor)) {
  717. if (!descriptor.fontAliases) {
  718. descriptor.fontAliases = Object.create(null);
  719. }
  720. var fontAliases = descriptor.fontAliases;
  721. if (fontAliases[hash]) {
  722. var aliasFontRef = fontAliases[hash].aliasRef;
  723. if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
  724. this.fontCache.putAlias(fontRef, aliasFontRef);
  725. return this.fontCache.get(fontRef);
  726. }
  727. } else {
  728. fontAliases[hash] = {
  729. fontID: _fonts.Font.getFontID()
  730. };
  731. }
  732. if (fontRefIsRef) {
  733. fontAliases[hash].aliasRef = fontRef;
  734. }
  735. fontID = fontAliases[hash].fontID;
  736. }
  737. if (fontRefIsRef) {
  738. this.fontCache.put(fontRef, fontCapability.promise);
  739. } else {
  740. if (!fontID) {
  741. fontID = this.idFactory.createObjId();
  742. }
  743. this.fontCache.put(`id_${fontID}`, fontCapability.promise);
  744. }
  745. (0, _util.assert)(fontID, 'The "fontID" must be defined.');
  746. font.loadedName = `${this.idFactory.getDocId()}_f${fontID}`;
  747. font.translated = fontCapability.promise;
  748. var translatedPromise;
  749. try {
  750. translatedPromise = this.translateFont(preEvaluatedFont);
  751. } catch (e) {
  752. translatedPromise = Promise.reject(e);
  753. }
  754. translatedPromise.then(function (translatedFont) {
  755. if (translatedFont.fontType !== undefined) {
  756. var xrefFontStats = xref.stats.fontTypes;
  757. xrefFontStats[translatedFont.fontType] = true;
  758. }
  759. fontCapability.resolve(new TranslatedFont(font.loadedName, translatedFont, font));
  760. }).catch(reason => {
  761. this.handler.send("UnsupportedFeature", {
  762. featureId: _util.UNSUPPORTED_FEATURES.font
  763. });
  764. try {
  765. var fontFile3 = descriptor && descriptor.get("FontFile3");
  766. var subtype = fontFile3 && fontFile3.get("Subtype");
  767. var fontType = (0, _fonts.getFontType)(preEvaluatedFont.type, subtype && subtype.name);
  768. var xrefFontStats = xref.stats.fontTypes;
  769. xrefFontStats[fontType] = true;
  770. } catch (ex) {}
  771. fontCapability.resolve(new TranslatedFont(font.loadedName, new _fonts.ErrorFont(reason instanceof Error ? reason.message : reason), font));
  772. });
  773. return fontCapability.promise;
  774. },
  775. buildPath(operatorList, fn, args, parsingText = false) {
  776. var lastIndex = operatorList.length - 1;
  777. if (!args) {
  778. args = [];
  779. }
  780. if (lastIndex < 0 || operatorList.fnArray[lastIndex] !== _util.OPS.constructPath) {
  781. if (parsingText) {
  782. (0, _util.warn)(`Encountered path operator "${fn}" inside of a text object.`);
  783. operatorList.addOp(_util.OPS.save, null);
  784. }
  785. operatorList.addOp(_util.OPS.constructPath, [[fn], args]);
  786. if (parsingText) {
  787. operatorList.addOp(_util.OPS.restore, null);
  788. }
  789. } else {
  790. var opArgs = operatorList.argsArray[lastIndex];
  791. opArgs[0].push(fn);
  792. Array.prototype.push.apply(opArgs[1], args);
  793. }
  794. },
  795. parseColorSpace({
  796. cs,
  797. resources
  798. }) {
  799. return new Promise(resolve => {
  800. resolve(_colorspace.ColorSpace.parse(cs, this.xref, resources, this.pdfFunctionFactory));
  801. }).catch(reason => {
  802. if (reason instanceof _util.AbortException) {
  803. return null;
  804. }
  805. if (this.options.ignoreErrors) {
  806. this.handler.send("UnsupportedFeature", {
  807. featureId: _util.UNSUPPORTED_FEATURES.unknown
  808. });
  809. (0, _util.warn)(`parseColorSpace - ignoring ColorSpace: "${reason}".`);
  810. return null;
  811. }
  812. throw reason;
  813. });
  814. },
  815. async handleColorN(operatorList, fn, args, cs, patterns, resources, task) {
  816. var patternName = args[args.length - 1];
  817. var pattern;
  818. if ((0, _primitives.isName)(patternName) && (pattern = patterns.get(patternName.name))) {
  819. var dict = (0, _primitives.isStream)(pattern) ? pattern.dict : pattern;
  820. var typeNum = dict.get("PatternType");
  821. if (typeNum === TILING_PATTERN) {
  822. var color = cs.base ? cs.base.getRgb(args, 0) : null;
  823. return this.handleTilingType(fn, color, resources, pattern, dict, operatorList, task);
  824. } else if (typeNum === SHADING_PATTERN) {
  825. var shading = dict.get("Shading");
  826. var matrix = dict.getArray("Matrix");
  827. pattern = _pattern.Pattern.parseShading(shading, matrix, this.xref, resources, this.handler, this.pdfFunctionFactory);
  828. operatorList.addOp(fn, pattern.getIR());
  829. return undefined;
  830. }
  831. throw new _util.FormatError(`Unknown PatternType: ${typeNum}`);
  832. }
  833. throw new _util.FormatError(`Unknown PatternName: ${patternName}`);
  834. },
  835. getOperatorList({
  836. stream,
  837. task,
  838. resources,
  839. operatorList,
  840. initialState = null
  841. }) {
  842. resources = resources || _primitives.Dict.empty;
  843. initialState = initialState || new EvalState();
  844. if (!operatorList) {
  845. throw new Error('getOperatorList: missing "operatorList" parameter');
  846. }
  847. var self = this;
  848. var xref = this.xref;
  849. let parsingText = false;
  850. var imageCache = Object.create(null);
  851. var xobjs = resources.get("XObject") || _primitives.Dict.empty;
  852. var patterns = resources.get("Pattern") || _primitives.Dict.empty;
  853. var stateManager = new StateManager(initialState);
  854. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  855. var timeSlotManager = new TimeSlotManager();
  856. function closePendingRestoreOPS(argument) {
  857. for (var i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  858. operatorList.addOp(_util.OPS.restore, []);
  859. }
  860. }
  861. return new Promise(function promiseBody(resolve, reject) {
  862. const next = function (promise) {
  863. Promise.all([promise, operatorList.ready]).then(function () {
  864. try {
  865. promiseBody(resolve, reject);
  866. } catch (ex) {
  867. reject(ex);
  868. }
  869. }, reject);
  870. };
  871. task.ensureNotTerminated();
  872. timeSlotManager.reset();
  873. var stop,
  874. operation = {},
  875. i,
  876. ii,
  877. cs;
  878. while (!(stop = timeSlotManager.check())) {
  879. operation.args = null;
  880. if (!preprocessor.read(operation)) {
  881. break;
  882. }
  883. var args = operation.args;
  884. var fn = operation.fn;
  885. switch (fn | 0) {
  886. case _util.OPS.paintXObject:
  887. var name = args[0].name;
  888. if (name && imageCache[name] !== undefined) {
  889. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  890. args = null;
  891. continue;
  892. }
  893. next(new Promise(function (resolveXObject, rejectXObject) {
  894. if (!name) {
  895. throw new _util.FormatError("XObject must be referred to by name.");
  896. }
  897. const xobj = xobjs.get(name);
  898. if (!xobj) {
  899. operatorList.addOp(fn, args);
  900. resolveXObject();
  901. return;
  902. }
  903. if (!(0, _primitives.isStream)(xobj)) {
  904. throw new _util.FormatError("XObject should be a stream");
  905. }
  906. const type = xobj.dict.get("Subtype");
  907. if (!(0, _primitives.isName)(type)) {
  908. throw new _util.FormatError("XObject should have a Name subtype");
  909. }
  910. if (type.name === "Form") {
  911. stateManager.save();
  912. self.buildFormXObject(resources, xobj, null, operatorList, task, stateManager.state.clone()).then(function () {
  913. stateManager.restore();
  914. resolveXObject();
  915. }, rejectXObject);
  916. return;
  917. } else if (type.name === "Image") {
  918. self.buildPaintImageXObject({
  919. resources,
  920. image: xobj,
  921. operatorList,
  922. cacheKey: name,
  923. imageCache
  924. }).then(resolveXObject, rejectXObject);
  925. return;
  926. } else if (type.name === "PS") {
  927. (0, _util.info)("Ignored XObject subtype PS");
  928. } else {
  929. throw new _util.FormatError(`Unhandled XObject subtype ${type.name}`);
  930. }
  931. resolveXObject();
  932. }).catch(function (reason) {
  933. if (reason instanceof _util.AbortException) {
  934. return;
  935. }
  936. if (self.options.ignoreErrors) {
  937. self.handler.send("UnsupportedFeature", {
  938. featureId: _util.UNSUPPORTED_FEATURES.unknown
  939. });
  940. (0, _util.warn)(`getOperatorList - ignoring XObject: "${reason}".`);
  941. return;
  942. }
  943. throw reason;
  944. }));
  945. return;
  946. case _util.OPS.setFont:
  947. var fontSize = args[1];
  948. next(self.handleSetFont(resources, args, null, operatorList, task, stateManager.state).then(function (loadedName) {
  949. operatorList.addDependency(loadedName);
  950. operatorList.addOp(_util.OPS.setFont, [loadedName, fontSize]);
  951. }));
  952. return;
  953. case _util.OPS.beginText:
  954. parsingText = true;
  955. break;
  956. case _util.OPS.endText:
  957. parsingText = false;
  958. break;
  959. case _util.OPS.endInlineImage:
  960. var cacheKey = args[0].cacheKey;
  961. if (cacheKey) {
  962. var cacheEntry = imageCache[cacheKey];
  963. if (cacheEntry !== undefined) {
  964. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  965. args = null;
  966. continue;
  967. }
  968. }
  969. next(self.buildPaintImageXObject({
  970. resources,
  971. image: args[0],
  972. isInline: true,
  973. operatorList,
  974. cacheKey,
  975. imageCache
  976. }));
  977. return;
  978. case _util.OPS.showText:
  979. if (!stateManager.state.font) {
  980. self.ensureStateFont(stateManager.state);
  981. continue;
  982. }
  983. args[0] = self.handleText(args[0], stateManager.state);
  984. break;
  985. case _util.OPS.showSpacedText:
  986. if (!stateManager.state.font) {
  987. self.ensureStateFont(stateManager.state);
  988. continue;
  989. }
  990. var arr = args[0];
  991. var combinedGlyphs = [];
  992. var arrLength = arr.length;
  993. var state = stateManager.state;
  994. for (i = 0; i < arrLength; ++i) {
  995. var arrItem = arr[i];
  996. if ((0, _util.isString)(arrItem)) {
  997. Array.prototype.push.apply(combinedGlyphs, self.handleText(arrItem, state));
  998. } else if ((0, _util.isNum)(arrItem)) {
  999. combinedGlyphs.push(arrItem);
  1000. }
  1001. }
  1002. args[0] = combinedGlyphs;
  1003. fn = _util.OPS.showText;
  1004. break;
  1005. case _util.OPS.nextLineShowText:
  1006. if (!stateManager.state.font) {
  1007. self.ensureStateFont(stateManager.state);
  1008. continue;
  1009. }
  1010. operatorList.addOp(_util.OPS.nextLine);
  1011. args[0] = self.handleText(args[0], stateManager.state);
  1012. fn = _util.OPS.showText;
  1013. break;
  1014. case _util.OPS.nextLineSetSpacingShowText:
  1015. if (!stateManager.state.font) {
  1016. self.ensureStateFont(stateManager.state);
  1017. continue;
  1018. }
  1019. operatorList.addOp(_util.OPS.nextLine);
  1020. operatorList.addOp(_util.OPS.setWordSpacing, [args.shift()]);
  1021. operatorList.addOp(_util.OPS.setCharSpacing, [args.shift()]);
  1022. args[0] = self.handleText(args[0], stateManager.state);
  1023. fn = _util.OPS.showText;
  1024. break;
  1025. case _util.OPS.setTextRenderingMode:
  1026. stateManager.state.textRenderingMode = args[0];
  1027. break;
  1028. case _util.OPS.setFillColorSpace:
  1029. next(self.parseColorSpace({
  1030. cs: args[0],
  1031. resources
  1032. }).then(function (colorSpace) {
  1033. if (colorSpace) {
  1034. stateManager.state.fillColorSpace = colorSpace;
  1035. }
  1036. }));
  1037. return;
  1038. case _util.OPS.setStrokeColorSpace:
  1039. next(self.parseColorSpace({
  1040. cs: args[0],
  1041. resources
  1042. }).then(function (colorSpace) {
  1043. if (colorSpace) {
  1044. stateManager.state.strokeColorSpace = colorSpace;
  1045. }
  1046. }));
  1047. return;
  1048. case _util.OPS.setFillColor:
  1049. cs = stateManager.state.fillColorSpace;
  1050. args = cs.getRgb(args, 0);
  1051. fn = _util.OPS.setFillRGBColor;
  1052. break;
  1053. case _util.OPS.setStrokeColor:
  1054. cs = stateManager.state.strokeColorSpace;
  1055. args = cs.getRgb(args, 0);
  1056. fn = _util.OPS.setStrokeRGBColor;
  1057. break;
  1058. case _util.OPS.setFillGray:
  1059. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  1060. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  1061. fn = _util.OPS.setFillRGBColor;
  1062. break;
  1063. case _util.OPS.setStrokeGray:
  1064. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  1065. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  1066. fn = _util.OPS.setStrokeRGBColor;
  1067. break;
  1068. case _util.OPS.setFillCMYKColor:
  1069. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  1070. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  1071. fn = _util.OPS.setFillRGBColor;
  1072. break;
  1073. case _util.OPS.setStrokeCMYKColor:
  1074. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  1075. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  1076. fn = _util.OPS.setStrokeRGBColor;
  1077. break;
  1078. case _util.OPS.setFillRGBColor:
  1079. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.rgb;
  1080. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  1081. break;
  1082. case _util.OPS.setStrokeRGBColor:
  1083. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.rgb;
  1084. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  1085. break;
  1086. case _util.OPS.setFillColorN:
  1087. cs = stateManager.state.fillColorSpace;
  1088. if (cs.name === "Pattern") {
  1089. next(self.handleColorN(operatorList, _util.OPS.setFillColorN, args, cs, patterns, resources, task));
  1090. return;
  1091. }
  1092. args = cs.getRgb(args, 0);
  1093. fn = _util.OPS.setFillRGBColor;
  1094. break;
  1095. case _util.OPS.setStrokeColorN:
  1096. cs = stateManager.state.strokeColorSpace;
  1097. if (cs.name === "Pattern") {
  1098. next(self.handleColorN(operatorList, _util.OPS.setStrokeColorN, args, cs, patterns, resources, task));
  1099. return;
  1100. }
  1101. args = cs.getRgb(args, 0);
  1102. fn = _util.OPS.setStrokeRGBColor;
  1103. break;
  1104. case _util.OPS.shadingFill:
  1105. var shadingRes = resources.get("Shading");
  1106. if (!shadingRes) {
  1107. throw new _util.FormatError("No shading resource found");
  1108. }
  1109. var shading = shadingRes.get(args[0].name);
  1110. if (!shading) {
  1111. throw new _util.FormatError("No shading object found");
  1112. }
  1113. var shadingFill = _pattern.Pattern.parseShading(shading, null, xref, resources, self.handler, self.pdfFunctionFactory);
  1114. var patternIR = shadingFill.getIR();
  1115. args = [patternIR];
  1116. fn = _util.OPS.shadingFill;
  1117. break;
  1118. case _util.OPS.setGState:
  1119. var dictName = args[0];
  1120. var extGState = resources.get("ExtGState");
  1121. if (!(0, _primitives.isDict)(extGState) || !extGState.has(dictName.name)) {
  1122. break;
  1123. }
  1124. var gState = extGState.get(dictName.name);
  1125. next(self.setGState(resources, gState, operatorList, task, stateManager));
  1126. return;
  1127. case _util.OPS.moveTo:
  1128. case _util.OPS.lineTo:
  1129. case _util.OPS.curveTo:
  1130. case _util.OPS.curveTo2:
  1131. case _util.OPS.curveTo3:
  1132. case _util.OPS.closePath:
  1133. case _util.OPS.rectangle:
  1134. self.buildPath(operatorList, fn, args, parsingText);
  1135. continue;
  1136. case _util.OPS.markPoint:
  1137. case _util.OPS.markPointProps:
  1138. case _util.OPS.beginMarkedContent:
  1139. case _util.OPS.beginMarkedContentProps:
  1140. case _util.OPS.endMarkedContent:
  1141. case _util.OPS.beginCompat:
  1142. case _util.OPS.endCompat:
  1143. continue;
  1144. default:
  1145. if (args !== null) {
  1146. for (i = 0, ii = args.length; i < ii; i++) {
  1147. if (args[i] instanceof _primitives.Dict) {
  1148. break;
  1149. }
  1150. }
  1151. if (i < ii) {
  1152. (0, _util.warn)("getOperatorList - ignoring operator: " + fn);
  1153. continue;
  1154. }
  1155. }
  1156. }
  1157. operatorList.addOp(fn, args);
  1158. }
  1159. if (stop) {
  1160. next(deferred);
  1161. return;
  1162. }
  1163. closePendingRestoreOPS();
  1164. resolve();
  1165. }).catch(reason => {
  1166. if (reason instanceof _util.AbortException) {
  1167. return;
  1168. }
  1169. if (this.options.ignoreErrors) {
  1170. this.handler.send("UnsupportedFeature", {
  1171. featureId: _util.UNSUPPORTED_FEATURES.unknown
  1172. });
  1173. (0, _util.warn)(`getOperatorList - ignoring errors during "${task.name}" ` + `task: "${reason}".`);
  1174. closePendingRestoreOPS();
  1175. return;
  1176. }
  1177. throw reason;
  1178. });
  1179. },
  1180. getTextContent({
  1181. stream,
  1182. task,
  1183. resources,
  1184. stateManager = null,
  1185. normalizeWhitespace = false,
  1186. combineTextItems = false,
  1187. sink,
  1188. seenStyles = Object.create(null)
  1189. }) {
  1190. resources = resources || _primitives.Dict.empty;
  1191. stateManager = stateManager || new StateManager(new TextState());
  1192. var WhitespaceRegexp = /\s/g;
  1193. var textContent = {
  1194. items: [],
  1195. styles: Object.create(null)
  1196. };
  1197. var textContentItem = {
  1198. initialized: false,
  1199. str: [],
  1200. width: 0,
  1201. height: 0,
  1202. vertical: false,
  1203. lastAdvanceWidth: 0,
  1204. lastAdvanceHeight: 0,
  1205. textAdvanceScale: 0,
  1206. spaceWidth: 0,
  1207. fakeSpaceMin: Infinity,
  1208. fakeMultiSpaceMin: Infinity,
  1209. fakeMultiSpaceMax: -0,
  1210. textRunBreakAllowed: false,
  1211. transform: null,
  1212. fontName: null
  1213. };
  1214. var SPACE_FACTOR = 0.3;
  1215. var MULTI_SPACE_FACTOR = 1.5;
  1216. var MULTI_SPACE_FACTOR_MAX = 4;
  1217. var self = this;
  1218. var xref = this.xref;
  1219. var xobjs = null;
  1220. var skipEmptyXObjs = Object.create(null);
  1221. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  1222. var textState;
  1223. function ensureTextContentItem() {
  1224. if (textContentItem.initialized) {
  1225. return textContentItem;
  1226. }
  1227. var font = textState.font;
  1228. if (!(font.loadedName in seenStyles)) {
  1229. seenStyles[font.loadedName] = true;
  1230. textContent.styles[font.loadedName] = {
  1231. fontFamily: font.fallbackName,
  1232. ascent: font.ascent,
  1233. descent: font.descent,
  1234. vertical: !!font.vertical
  1235. };
  1236. }
  1237. textContentItem.fontName = font.loadedName;
  1238. var tsm = [textState.fontSize * textState.textHScale, 0, 0, textState.fontSize, 0, textState.textRise];
  1239. if (font.isType3Font && textState.fontSize <= 1 && !(0, _util.isArrayEqual)(textState.fontMatrix, _util.FONT_IDENTITY_MATRIX)) {
  1240. const glyphHeight = font.bbox[3] - font.bbox[1];
  1241. if (glyphHeight > 0) {
  1242. tsm[3] *= glyphHeight * textState.fontMatrix[3];
  1243. }
  1244. }
  1245. var trm = _util.Util.transform(textState.ctm, _util.Util.transform(textState.textMatrix, tsm));
  1246. textContentItem.transform = trm;
  1247. if (!font.vertical) {
  1248. textContentItem.width = 0;
  1249. textContentItem.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  1250. textContentItem.vertical = false;
  1251. } else {
  1252. textContentItem.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  1253. textContentItem.height = 0;
  1254. textContentItem.vertical = true;
  1255. }
  1256. var a = textState.textLineMatrix[0];
  1257. var b = textState.textLineMatrix[1];
  1258. var scaleLineX = Math.sqrt(a * a + b * b);
  1259. a = textState.ctm[0];
  1260. b = textState.ctm[1];
  1261. var scaleCtmX = Math.sqrt(a * a + b * b);
  1262. textContentItem.textAdvanceScale = scaleCtmX * scaleLineX;
  1263. textContentItem.lastAdvanceWidth = 0;
  1264. textContentItem.lastAdvanceHeight = 0;
  1265. var spaceWidth = font.spaceWidth / 1000 * textState.fontSize;
  1266. if (spaceWidth) {
  1267. textContentItem.spaceWidth = spaceWidth;
  1268. textContentItem.fakeSpaceMin = spaceWidth * SPACE_FACTOR;
  1269. textContentItem.fakeMultiSpaceMin = spaceWidth * MULTI_SPACE_FACTOR;
  1270. textContentItem.fakeMultiSpaceMax = spaceWidth * MULTI_SPACE_FACTOR_MAX;
  1271. textContentItem.textRunBreakAllowed = !font.isMonospace;
  1272. } else {
  1273. textContentItem.spaceWidth = 0;
  1274. textContentItem.fakeSpaceMin = Infinity;
  1275. textContentItem.fakeMultiSpaceMin = Infinity;
  1276. textContentItem.fakeMultiSpaceMax = 0;
  1277. textContentItem.textRunBreakAllowed = false;
  1278. }
  1279. textContentItem.initialized = true;
  1280. return textContentItem;
  1281. }
  1282. function replaceWhitespace(str) {
  1283. var i = 0,
  1284. ii = str.length,
  1285. code;
  1286. while (i < ii && (code = str.charCodeAt(i)) >= 0x20 && code <= 0x7f) {
  1287. i++;
  1288. }
  1289. return i < ii ? str.replace(WhitespaceRegexp, " ") : str;
  1290. }
  1291. function runBidiTransform(textChunk) {
  1292. var str = textChunk.str.join("");
  1293. var bidiResult = (0, _bidi.bidi)(str, -1, textChunk.vertical);
  1294. return {
  1295. str: normalizeWhitespace ? replaceWhitespace(bidiResult.str) : bidiResult.str,
  1296. dir: bidiResult.dir,
  1297. width: textChunk.width,
  1298. height: textChunk.height,
  1299. transform: textChunk.transform,
  1300. fontName: textChunk.fontName
  1301. };
  1302. }
  1303. function handleSetFont(fontName, fontRef) {
  1304. return self.loadFont(fontName, fontRef, resources).then(function (translated) {
  1305. textState.font = translated.font;
  1306. textState.fontMatrix = translated.font.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1307. });
  1308. }
  1309. function buildTextContentItem(chars) {
  1310. var font = textState.font;
  1311. var textChunk = ensureTextContentItem();
  1312. var width = 0;
  1313. var height = 0;
  1314. var glyphs = font.charsToGlyphs(chars);
  1315. for (var i = 0; i < glyphs.length; i++) {
  1316. var glyph = glyphs[i];
  1317. var glyphWidth = null;
  1318. if (font.vertical && glyph.vmetric) {
  1319. glyphWidth = glyph.vmetric[0];
  1320. } else {
  1321. glyphWidth = glyph.width;
  1322. }
  1323. var glyphUnicode = glyph.unicode;
  1324. var NormalizedUnicodes = (0, _unicode.getNormalizedUnicodes)();
  1325. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  1326. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  1327. }
  1328. glyphUnicode = (0, _unicode.reverseIfRtl)(glyphUnicode);
  1329. var charSpacing = textState.charSpacing;
  1330. if (glyph.isSpace) {
  1331. var wordSpacing = textState.wordSpacing;
  1332. charSpacing += wordSpacing;
  1333. if (wordSpacing > 0) {
  1334. addFakeSpaces(wordSpacing, textChunk.str);
  1335. }
  1336. }
  1337. var tx = 0;
  1338. var ty = 0;
  1339. if (!font.vertical) {
  1340. var w0 = glyphWidth * textState.fontMatrix[0];
  1341. tx = (w0 * textState.fontSize + charSpacing) * textState.textHScale;
  1342. width += tx;
  1343. } else {
  1344. var w1 = glyphWidth * textState.fontMatrix[0];
  1345. ty = w1 * textState.fontSize + charSpacing;
  1346. height += ty;
  1347. }
  1348. textState.translateTextMatrix(tx, ty);
  1349. textChunk.str.push(glyphUnicode);
  1350. }
  1351. if (!font.vertical) {
  1352. textChunk.lastAdvanceWidth = width;
  1353. textChunk.width += width;
  1354. } else {
  1355. textChunk.lastAdvanceHeight = height;
  1356. textChunk.height += Math.abs(height);
  1357. }
  1358. return textChunk;
  1359. }
  1360. function addFakeSpaces(width, strBuf) {
  1361. if (width < textContentItem.fakeSpaceMin) {
  1362. return;
  1363. }
  1364. if (width < textContentItem.fakeMultiSpaceMin) {
  1365. strBuf.push(" ");
  1366. return;
  1367. }
  1368. var fakeSpaces = Math.round(width / textContentItem.spaceWidth);
  1369. while (fakeSpaces-- > 0) {
  1370. strBuf.push(" ");
  1371. }
  1372. }
  1373. function flushTextContentItem() {
  1374. if (!textContentItem.initialized) {
  1375. return;
  1376. }
  1377. if (!textContentItem.vertical) {
  1378. textContentItem.width *= textContentItem.textAdvanceScale;
  1379. } else {
  1380. textContentItem.height *= textContentItem.textAdvanceScale;
  1381. }
  1382. textContent.items.push(runBidiTransform(textContentItem));
  1383. textContentItem.initialized = false;
  1384. textContentItem.str.length = 0;
  1385. }
  1386. function enqueueChunk() {
  1387. const length = textContent.items.length;
  1388. if (length > 0) {
  1389. sink.enqueue(textContent, length);
  1390. textContent.items = [];
  1391. textContent.styles = Object.create(null);
  1392. }
  1393. }
  1394. var timeSlotManager = new TimeSlotManager();
  1395. return new Promise(function promiseBody(resolve, reject) {
  1396. const next = function (promise) {
  1397. enqueueChunk();
  1398. Promise.all([promise, sink.ready]).then(function () {
  1399. try {
  1400. promiseBody(resolve, reject);
  1401. } catch (ex) {
  1402. reject(ex);
  1403. }
  1404. }, reject);
  1405. };
  1406. task.ensureNotTerminated();
  1407. timeSlotManager.reset();
  1408. var stop,
  1409. operation = {},
  1410. args = [];
  1411. while (!(stop = timeSlotManager.check())) {
  1412. args.length = 0;
  1413. operation.args = args;
  1414. if (!preprocessor.read(operation)) {
  1415. break;
  1416. }
  1417. textState = stateManager.state;
  1418. var fn = operation.fn;
  1419. args = operation.args;
  1420. var advance, diff;
  1421. switch (fn | 0) {
  1422. case _util.OPS.setFont:
  1423. var fontNameArg = args[0].name,
  1424. fontSizeArg = args[1];
  1425. if (textState.font && fontNameArg === textState.fontName && fontSizeArg === textState.fontSize) {
  1426. break;
  1427. }
  1428. flushTextContentItem();
  1429. textState.fontName = fontNameArg;
  1430. textState.fontSize = fontSizeArg;
  1431. next(handleSetFont(fontNameArg, null));
  1432. return;
  1433. case _util.OPS.setTextRise:
  1434. flushTextContentItem();
  1435. textState.textRise = args[0];
  1436. break;
  1437. case _util.OPS.setHScale:
  1438. flushTextContentItem();
  1439. textState.textHScale = args[0] / 100;
  1440. break;
  1441. case _util.OPS.setLeading:
  1442. flushTextContentItem();
  1443. textState.leading = args[0];
  1444. break;
  1445. case _util.OPS.moveText:
  1446. var isSameTextLine = !textState.font ? false : (textState.font.vertical ? args[0] : args[1]) === 0;
  1447. advance = args[0] - args[1];
  1448. if (combineTextItems && isSameTextLine && textContentItem.initialized && advance > 0 && advance <= textContentItem.fakeMultiSpaceMax) {
  1449. textState.translateTextLineMatrix(args[0], args[1]);
  1450. textContentItem.width += args[0] - textContentItem.lastAdvanceWidth;
  1451. textContentItem.height += args[1] - textContentItem.lastAdvanceHeight;
  1452. diff = args[0] - textContentItem.lastAdvanceWidth - (args[1] - textContentItem.lastAdvanceHeight);
  1453. addFakeSpaces(diff, textContentItem.str);
  1454. break;
  1455. }
  1456. flushTextContentItem();
  1457. textState.translateTextLineMatrix(args[0], args[1]);
  1458. textState.textMatrix = textState.textLineMatrix.slice();
  1459. break;
  1460. case _util.OPS.setLeadingMoveText:
  1461. flushTextContentItem();
  1462. textState.leading = -args[1];
  1463. textState.translateTextLineMatrix(args[0], args[1]);
  1464. textState.textMatrix = textState.textLineMatrix.slice();
  1465. break;
  1466. case _util.OPS.nextLine:
  1467. flushTextContentItem();
  1468. textState.carriageReturn();
  1469. break;
  1470. case _util.OPS.setTextMatrix:
  1471. advance = textState.calcTextLineMatrixAdvance(args[0], args[1], args[2], args[3], args[4], args[5]);
  1472. if (combineTextItems && advance !== null && textContentItem.initialized && advance.value > 0 && advance.value <= textContentItem.fakeMultiSpaceMax) {
  1473. textState.translateTextLineMatrix(advance.width, advance.height);
  1474. textContentItem.width += advance.width - textContentItem.lastAdvanceWidth;
  1475. textContentItem.height += advance.height - textContentItem.lastAdvanceHeight;
  1476. diff = advance.width - textContentItem.lastAdvanceWidth - (advance.height - textContentItem.lastAdvanceHeight);
  1477. addFakeSpaces(diff, textContentItem.str);
  1478. break;
  1479. }
  1480. flushTextContentItem();
  1481. textState.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  1482. textState.setTextLineMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  1483. break;
  1484. case _util.OPS.setCharSpacing:
  1485. textState.charSpacing = args[0];
  1486. break;
  1487. case _util.OPS.setWordSpacing:
  1488. textState.wordSpacing = args[0];
  1489. break;
  1490. case _util.OPS.beginText:
  1491. flushTextContentItem();
  1492. textState.textMatrix = _util.IDENTITY_MATRIX.slice();
  1493. textState.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  1494. break;
  1495. case _util.OPS.showSpacedText:
  1496. if (!stateManager.state.font) {
  1497. self.ensureStateFont(stateManager.state);
  1498. continue;
  1499. }
  1500. var items = args[0];
  1501. var offset;
  1502. for (var j = 0, jj = items.length; j < jj; j++) {
  1503. if (typeof items[j] === "string") {
  1504. buildTextContentItem(items[j]);
  1505. } else if ((0, _util.isNum)(items[j])) {
  1506. ensureTextContentItem();
  1507. advance = items[j] * textState.fontSize / 1000;
  1508. var breakTextRun = false;
  1509. if (textState.font.vertical) {
  1510. offset = advance;
  1511. textState.translateTextMatrix(0, offset);
  1512. breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax;
  1513. if (!breakTextRun) {
  1514. textContentItem.height += offset;
  1515. }
  1516. } else {
  1517. advance = -advance;
  1518. offset = advance * textState.textHScale;
  1519. textState.translateTextMatrix(offset, 0);
  1520. breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax;
  1521. if (!breakTextRun) {
  1522. textContentItem.width += offset;
  1523. }
  1524. }
  1525. if (breakTextRun) {
  1526. flushTextContentItem();
  1527. } else if (advance > 0) {
  1528. addFakeSpaces(advance, textContentItem.str);
  1529. }
  1530. }
  1531. }
  1532. break;
  1533. case _util.OPS.showText:
  1534. if (!stateManager.state.font) {
  1535. self.ensureStateFont(stateManager.state);
  1536. continue;
  1537. }
  1538. buildTextContentItem(args[0]);
  1539. break;
  1540. case _util.OPS.nextLineShowText:
  1541. if (!stateManager.state.font) {
  1542. self.ensureStateFont(stateManager.state);
  1543. continue;
  1544. }
  1545. flushTextContentItem();
  1546. textState.carriageReturn();
  1547. buildTextContentItem(args[0]);
  1548. break;
  1549. case _util.OPS.nextLineSetSpacingShowText:
  1550. if (!stateManager.state.font) {
  1551. self.ensureStateFont(stateManager.state);
  1552. continue;
  1553. }
  1554. flushTextContentItem();
  1555. textState.wordSpacing = args[0];
  1556. textState.charSpacing = args[1];
  1557. textState.carriageReturn();
  1558. buildTextContentItem(args[2]);
  1559. break;
  1560. case _util.OPS.paintXObject:
  1561. flushTextContentItem();
  1562. if (!xobjs) {
  1563. xobjs = resources.get("XObject") || _primitives.Dict.empty;
  1564. }
  1565. var name = args[0].name;
  1566. if (name && skipEmptyXObjs[name] !== undefined) {
  1567. break;
  1568. }
  1569. next(new Promise(function (resolveXObject, rejectXObject) {
  1570. if (!name) {
  1571. throw new _util.FormatError("XObject must be referred to by name.");
  1572. }
  1573. const xobj = xobjs.get(name);
  1574. if (!xobj) {
  1575. resolveXObject();
  1576. return;
  1577. }
  1578. if (!(0, _primitives.isStream)(xobj)) {
  1579. throw new _util.FormatError("XObject should be a stream");
  1580. }
  1581. const type = xobj.dict.get("Subtype");
  1582. if (!(0, _primitives.isName)(type)) {
  1583. throw new _util.FormatError("XObject should have a Name subtype");
  1584. }
  1585. if (type.name !== "Form") {
  1586. skipEmptyXObjs[name] = true;
  1587. resolveXObject();
  1588. return;
  1589. }
  1590. const currentState = stateManager.state.clone();
  1591. const xObjStateManager = new StateManager(currentState);
  1592. const matrix = xobj.dict.getArray("Matrix");
  1593. if (Array.isArray(matrix) && matrix.length === 6) {
  1594. xObjStateManager.transform(matrix);
  1595. }
  1596. enqueueChunk();
  1597. const sinkWrapper = {
  1598. enqueueInvoked: false,
  1599. enqueue(chunk, size) {
  1600. this.enqueueInvoked = true;
  1601. sink.enqueue(chunk, size);
  1602. },
  1603. get desiredSize() {
  1604. return sink.desiredSize;
  1605. },
  1606. get ready() {
  1607. return sink.ready;
  1608. }
  1609. };
  1610. self.getTextContent({
  1611. stream: xobj,
  1612. task,
  1613. resources: xobj.dict.get("Resources") || resources,
  1614. stateManager: xObjStateManager,
  1615. normalizeWhitespace,
  1616. combineTextItems,
  1617. sink: sinkWrapper,
  1618. seenStyles
  1619. }).then(function () {
  1620. if (!sinkWrapper.enqueueInvoked) {
  1621. skipEmptyXObjs[name] = true;
  1622. }
  1623. resolveXObject();
  1624. }, rejectXObject);
  1625. }).catch(function (reason) {
  1626. if (reason instanceof _util.AbortException) {
  1627. return;
  1628. }
  1629. if (self.options.ignoreErrors) {
  1630. (0, _util.warn)(`getTextContent - ignoring XObject: "${reason}".`);
  1631. return;
  1632. }
  1633. throw reason;
  1634. }));
  1635. return;
  1636. case _util.OPS.setGState:
  1637. flushTextContentItem();
  1638. var dictName = args[0];
  1639. var extGState = resources.get("ExtGState");
  1640. if (!(0, _primitives.isDict)(extGState) || !(0, _primitives.isName)(dictName)) {
  1641. break;
  1642. }
  1643. var gState = extGState.get(dictName.name);
  1644. if (!(0, _primitives.isDict)(gState)) {
  1645. break;
  1646. }
  1647. var gStateFont = gState.get("Font");
  1648. if (gStateFont) {
  1649. textState.fontName = null;
  1650. textState.fontSize = gStateFont[1];
  1651. next(handleSetFont(null, gStateFont[0]));
  1652. return;
  1653. }
  1654. break;
  1655. }
  1656. if (textContent.items.length >= sink.desiredSize) {
  1657. stop = true;
  1658. break;
  1659. }
  1660. }
  1661. if (stop) {
  1662. next(deferred);
  1663. return;
  1664. }
  1665. flushTextContentItem();
  1666. enqueueChunk();
  1667. resolve();
  1668. }).catch(reason => {
  1669. if (reason instanceof _util.AbortException) {
  1670. return;
  1671. }
  1672. if (this.options.ignoreErrors) {
  1673. (0, _util.warn)(`getTextContent - ignoring errors during "${task.name}" ` + `task: "${reason}".`);
  1674. flushTextContentItem();
  1675. enqueueChunk();
  1676. return;
  1677. }
  1678. throw reason;
  1679. });
  1680. },
  1681. extractDataStructures: function PartialEvaluator_extractDataStructures(dict, baseDict, properties) {
  1682. const xref = this.xref;
  1683. let cidToGidBytes;
  1684. var toUnicode = dict.get("ToUnicode") || baseDict.get("ToUnicode");
  1685. var toUnicodePromise = toUnicode ? this.readToUnicode(toUnicode) : Promise.resolve(undefined);
  1686. if (properties.composite) {
  1687. var cidSystemInfo = dict.get("CIDSystemInfo");
  1688. if ((0, _primitives.isDict)(cidSystemInfo)) {
  1689. properties.cidSystemInfo = {
  1690. registry: (0, _util.stringToPDFString)(cidSystemInfo.get("Registry")),
  1691. ordering: (0, _util.stringToPDFString)(cidSystemInfo.get("Ordering")),
  1692. supplement: cidSystemInfo.get("Supplement")
  1693. };
  1694. }
  1695. var cidToGidMap = dict.get("CIDToGIDMap");
  1696. if ((0, _primitives.isStream)(cidToGidMap)) {
  1697. cidToGidBytes = cidToGidMap.getBytes();
  1698. }
  1699. }
  1700. var differences = [];
  1701. var baseEncodingName = null;
  1702. var encoding;
  1703. if (dict.has("Encoding")) {
  1704. encoding = dict.get("Encoding");
  1705. if ((0, _primitives.isDict)(encoding)) {
  1706. baseEncodingName = encoding.get("BaseEncoding");
  1707. baseEncodingName = (0, _primitives.isName)(baseEncodingName) ? baseEncodingName.name : null;
  1708. if (encoding.has("Differences")) {
  1709. var diffEncoding = encoding.get("Differences");
  1710. var index = 0;
  1711. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  1712. var data = xref.fetchIfRef(diffEncoding[j]);
  1713. if ((0, _util.isNum)(data)) {
  1714. index = data;
  1715. } else if ((0, _primitives.isName)(data)) {
  1716. differences[index++] = data.name;
  1717. } else {
  1718. throw new _util.FormatError(`Invalid entry in 'Differences' array: ${data}`);
  1719. }
  1720. }
  1721. }
  1722. } else if ((0, _primitives.isName)(encoding)) {
  1723. baseEncodingName = encoding.name;
  1724. } else {
  1725. throw new _util.FormatError("Encoding is not a Name nor a Dict");
  1726. }
  1727. if (baseEncodingName !== "MacRomanEncoding" && baseEncodingName !== "MacExpertEncoding" && baseEncodingName !== "WinAnsiEncoding") {
  1728. baseEncodingName = null;
  1729. }
  1730. }
  1731. if (baseEncodingName) {
  1732. properties.defaultEncoding = (0, _encodings.getEncoding)(baseEncodingName).slice();
  1733. } else {
  1734. var isSymbolicFont = !!(properties.flags & _fonts.FontFlags.Symbolic);
  1735. var isNonsymbolicFont = !!(properties.flags & _fonts.FontFlags.Nonsymbolic);
  1736. encoding = _encodings.StandardEncoding;
  1737. if (properties.type === "TrueType" && !isNonsymbolicFont) {
  1738. encoding = _encodings.WinAnsiEncoding;
  1739. }
  1740. if (isSymbolicFont) {
  1741. encoding = _encodings.MacRomanEncoding;
  1742. if (!properties.file) {
  1743. if (/Symbol/i.test(properties.name)) {
  1744. encoding = _encodings.SymbolSetEncoding;
  1745. } else if (/Dingbats|Wingdings/i.test(properties.name)) {
  1746. encoding = _encodings.ZapfDingbatsEncoding;
  1747. }
  1748. }
  1749. }
  1750. properties.defaultEncoding = encoding;
  1751. }
  1752. properties.differences = differences;
  1753. properties.baseEncodingName = baseEncodingName;
  1754. properties.hasEncoding = !!baseEncodingName || differences.length > 0;
  1755. properties.dict = dict;
  1756. return toUnicodePromise.then(toUnicode => {
  1757. properties.toUnicode = toUnicode;
  1758. return this.buildToUnicode(properties);
  1759. }).then(toUnicode => {
  1760. properties.toUnicode = toUnicode;
  1761. if (cidToGidBytes) {
  1762. properties.cidToGidMap = this.readCidToGidMap(cidToGidBytes, toUnicode);
  1763. }
  1764. return properties;
  1765. });
  1766. },
  1767. _buildSimpleFontToUnicode(properties, forceGlyphs = false) {
  1768. (0, _util.assert)(!properties.composite, "Must be a simple font.");
  1769. const toUnicode = [];
  1770. const encoding = properties.defaultEncoding.slice();
  1771. const baseEncodingName = properties.baseEncodingName;
  1772. const differences = properties.differences;
  1773. for (const charcode in differences) {
  1774. const glyphName = differences[charcode];
  1775. if (glyphName === ".notdef") {
  1776. continue;
  1777. }
  1778. encoding[charcode] = glyphName;
  1779. }
  1780. const glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  1781. for (const charcode in encoding) {
  1782. let glyphName = encoding[charcode];
  1783. if (glyphName === "") {
  1784. continue;
  1785. } else if (glyphsUnicodeMap[glyphName] === undefined) {
  1786. let code = 0;
  1787. switch (glyphName[0]) {
  1788. case "G":
  1789. if (glyphName.length === 3) {
  1790. code = parseInt(glyphName.substring(1), 16);
  1791. }
  1792. break;
  1793. case "g":
  1794. if (glyphName.length === 5) {
  1795. code = parseInt(glyphName.substring(1), 16);
  1796. }
  1797. break;
  1798. case "C":
  1799. case "c":
  1800. if (glyphName.length >= 3 && glyphName.length <= 4) {
  1801. const codeStr = glyphName.substring(1);
  1802. if (forceGlyphs) {
  1803. code = parseInt(codeStr, 16);
  1804. break;
  1805. }
  1806. code = +codeStr;
  1807. if (Number.isNaN(code) && Number.isInteger(parseInt(codeStr, 16))) {
  1808. return this._buildSimpleFontToUnicode(properties, true);
  1809. }
  1810. }
  1811. break;
  1812. default:
  1813. const unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
  1814. if (unicode !== -1) {
  1815. code = unicode;
  1816. }
  1817. }
  1818. if (code > 0 && Number.isInteger(code)) {
  1819. if (baseEncodingName && code === +charcode) {
  1820. const baseEncoding = (0, _encodings.getEncoding)(baseEncodingName);
  1821. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  1822. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1823. continue;
  1824. }
  1825. }
  1826. toUnicode[charcode] = String.fromCodePoint(code);
  1827. }
  1828. continue;
  1829. }
  1830. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1831. }
  1832. return new _fonts.ToUnicodeMap(toUnicode);
  1833. },
  1834. buildToUnicode(properties) {
  1835. properties.hasIncludedToUnicodeMap = !!properties.toUnicode && properties.toUnicode.length > 0;
  1836. if (properties.hasIncludedToUnicodeMap) {
  1837. if (!properties.composite && properties.hasEncoding) {
  1838. properties.fallbackToUnicode = this._buildSimpleFontToUnicode(properties);
  1839. }
  1840. return Promise.resolve(properties.toUnicode);
  1841. }
  1842. if (!properties.composite) {
  1843. return Promise.resolve(this._buildSimpleFontToUnicode(properties));
  1844. }
  1845. 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"))) {
  1846. const registry = properties.cidSystemInfo.registry;
  1847. const ordering = properties.cidSystemInfo.ordering;
  1848. const ucs2CMapName = _primitives.Name.get(registry + "-" + ordering + "-UCS2");
  1849. return _cmap.CMapFactory.create({
  1850. encoding: ucs2CMapName,
  1851. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1852. useCMap: null
  1853. }).then(function (ucs2CMap) {
  1854. const cMap = properties.cMap;
  1855. const toUnicode = [];
  1856. cMap.forEach(function (charcode, cid) {
  1857. if (cid > 0xffff) {
  1858. throw new _util.FormatError("Max size of CID is 65,535");
  1859. }
  1860. const ucs2 = ucs2CMap.lookup(cid);
  1861. if (ucs2) {
  1862. toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) + ucs2.charCodeAt(1));
  1863. }
  1864. });
  1865. return new _fonts.ToUnicodeMap(toUnicode);
  1866. });
  1867. }
  1868. return Promise.resolve(new _fonts.IdentityToUnicodeMap(properties.firstChar, properties.lastChar));
  1869. },
  1870. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  1871. var cmapObj = toUnicode;
  1872. if ((0, _primitives.isName)(cmapObj)) {
  1873. return _cmap.CMapFactory.create({
  1874. encoding: cmapObj,
  1875. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1876. useCMap: null
  1877. }).then(function (cmap) {
  1878. if (cmap instanceof _cmap.IdentityCMap) {
  1879. return new _fonts.IdentityToUnicodeMap(0, 0xffff);
  1880. }
  1881. return new _fonts.ToUnicodeMap(cmap.getMap());
  1882. });
  1883. } else if ((0, _primitives.isStream)(cmapObj)) {
  1884. return _cmap.CMapFactory.create({
  1885. encoding: cmapObj,
  1886. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1887. useCMap: null
  1888. }).then(function (cmap) {
  1889. if (cmap instanceof _cmap.IdentityCMap) {
  1890. return new _fonts.IdentityToUnicodeMap(0, 0xffff);
  1891. }
  1892. var map = new Array(cmap.length);
  1893. cmap.forEach(function (charCode, token) {
  1894. var str = [];
  1895. for (var k = 0; k < token.length; k += 2) {
  1896. var w1 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1897. if ((w1 & 0xf800) !== 0xd800) {
  1898. str.push(w1);
  1899. continue;
  1900. }
  1901. k += 2;
  1902. var w2 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1903. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  1904. }
  1905. map[charCode] = String.fromCodePoint.apply(String, str);
  1906. });
  1907. return new _fonts.ToUnicodeMap(map);
  1908. }, reason => {
  1909. if (reason instanceof _util.AbortException) {
  1910. return null;
  1911. }
  1912. if (this.options.ignoreErrors) {
  1913. this.handler.send("UnsupportedFeature", {
  1914. featureId: _util.UNSUPPORTED_FEATURES.font
  1915. });
  1916. (0, _util.warn)(`readToUnicode - ignoring ToUnicode data: "${reason}".`);
  1917. return null;
  1918. }
  1919. throw reason;
  1920. });
  1921. }
  1922. return Promise.resolve(null);
  1923. },
  1924. readCidToGidMap(glyphsData, toUnicode) {
  1925. var result = [];
  1926. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  1927. var glyphID = glyphsData[j++] << 8 | glyphsData[j];
  1928. const code = j >> 1;
  1929. if (glyphID === 0 && !toUnicode.has(code)) {
  1930. continue;
  1931. }
  1932. result[code] = glyphID;
  1933. }
  1934. return result;
  1935. },
  1936. extractWidths: function PartialEvaluator_extractWidths(dict, descriptor, properties) {
  1937. var xref = this.xref;
  1938. var glyphsWidths = [];
  1939. var defaultWidth = 0;
  1940. var glyphsVMetrics = [];
  1941. var defaultVMetrics;
  1942. var i, ii, j, jj, start, code, widths;
  1943. if (properties.composite) {
  1944. defaultWidth = dict.has("DW") ? dict.get("DW") : 1000;
  1945. widths = dict.get("W");
  1946. if (widths) {
  1947. for (i = 0, ii = widths.length; i < ii; i++) {
  1948. start = xref.fetchIfRef(widths[i++]);
  1949. code = xref.fetchIfRef(widths[i]);
  1950. if (Array.isArray(code)) {
  1951. for (j = 0, jj = code.length; j < jj; j++) {
  1952. glyphsWidths[start++] = xref.fetchIfRef(code[j]);
  1953. }
  1954. } else {
  1955. var width = xref.fetchIfRef(widths[++i]);
  1956. for (j = start; j <= code; j++) {
  1957. glyphsWidths[j] = width;
  1958. }
  1959. }
  1960. }
  1961. }
  1962. if (properties.vertical) {
  1963. var vmetrics = dict.getArray("DW2") || [880, -1000];
  1964. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  1965. vmetrics = dict.get("W2");
  1966. if (vmetrics) {
  1967. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  1968. start = xref.fetchIfRef(vmetrics[i++]);
  1969. code = xref.fetchIfRef(vmetrics[i]);
  1970. if (Array.isArray(code)) {
  1971. for (j = 0, jj = code.length; j < jj; j++) {
  1972. glyphsVMetrics[start++] = [xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j])];
  1973. }
  1974. } else {
  1975. var vmetric = [xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i])];
  1976. for (j = start; j <= code; j++) {
  1977. glyphsVMetrics[j] = vmetric;
  1978. }
  1979. }
  1980. }
  1981. }
  1982. }
  1983. } else {
  1984. var firstChar = properties.firstChar;
  1985. widths = dict.get("Widths");
  1986. if (widths) {
  1987. j = firstChar;
  1988. for (i = 0, ii = widths.length; i < ii; i++) {
  1989. glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
  1990. }
  1991. defaultWidth = parseFloat(descriptor.get("MissingWidth")) || 0;
  1992. } else {
  1993. var baseFontName = dict.get("BaseFont");
  1994. if ((0, _primitives.isName)(baseFontName)) {
  1995. var metrics = this.getBaseFontMetrics(baseFontName.name);
  1996. glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
  1997. defaultWidth = metrics.defaultWidth;
  1998. }
  1999. }
  2000. }
  2001. var isMonospace = true;
  2002. var firstWidth = defaultWidth;
  2003. for (var glyph in glyphsWidths) {
  2004. var glyphWidth = glyphsWidths[glyph];
  2005. if (!glyphWidth) {
  2006. continue;
  2007. }
  2008. if (!firstWidth) {
  2009. firstWidth = glyphWidth;
  2010. continue;
  2011. }
  2012. if (firstWidth !== glyphWidth) {
  2013. isMonospace = false;
  2014. break;
  2015. }
  2016. }
  2017. if (isMonospace) {
  2018. properties.flags |= _fonts.FontFlags.FixedPitch;
  2019. }
  2020. properties.defaultWidth = defaultWidth;
  2021. properties.widths = glyphsWidths;
  2022. properties.defaultVMetrics = defaultVMetrics;
  2023. properties.vmetrics = glyphsVMetrics;
  2024. },
  2025. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  2026. var fontNameWoStyle = baseFontName.split("-")[0];
  2027. return fontNameWoStyle in (0, _standard_fonts.getSerifFonts)() || fontNameWoStyle.search(/serif/gi) !== -1;
  2028. },
  2029. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  2030. var defaultWidth = 0;
  2031. var widths = [];
  2032. var monospace = false;
  2033. var stdFontMap = (0, _standard_fonts.getStdFontMap)();
  2034. var lookupName = stdFontMap[name] || name;
  2035. var Metrics = (0, _metrics.getMetrics)();
  2036. if (!(lookupName in Metrics)) {
  2037. if (this.isSerifFont(name)) {
  2038. lookupName = "Times-Roman";
  2039. } else {
  2040. lookupName = "Helvetica";
  2041. }
  2042. }
  2043. var glyphWidths = Metrics[lookupName];
  2044. if ((0, _util.isNum)(glyphWidths)) {
  2045. defaultWidth = glyphWidths;
  2046. monospace = true;
  2047. } else {
  2048. widths = glyphWidths();
  2049. }
  2050. return {
  2051. defaultWidth,
  2052. monospace,
  2053. widths
  2054. };
  2055. },
  2056. buildCharCodeToWidth: function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName, properties) {
  2057. var widths = Object.create(null);
  2058. var differences = properties.differences;
  2059. var encoding = properties.defaultEncoding;
  2060. for (var charCode = 0; charCode < 256; charCode++) {
  2061. if (charCode in differences && widthsByGlyphName[differences[charCode]]) {
  2062. widths[charCode] = widthsByGlyphName[differences[charCode]];
  2063. continue;
  2064. }
  2065. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  2066. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  2067. continue;
  2068. }
  2069. }
  2070. return widths;
  2071. },
  2072. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict) {
  2073. var baseDict = dict;
  2074. var type = dict.get("Subtype");
  2075. if (!(0, _primitives.isName)(type)) {
  2076. throw new _util.FormatError("invalid font Subtype");
  2077. }
  2078. var composite = false;
  2079. var uint8array;
  2080. if (type.name === "Type0") {
  2081. var df = dict.get("DescendantFonts");
  2082. if (!df) {
  2083. throw new _util.FormatError("Descendant fonts are not specified");
  2084. }
  2085. dict = Array.isArray(df) ? this.xref.fetchIfRef(df[0]) : df;
  2086. type = dict.get("Subtype");
  2087. if (!(0, _primitives.isName)(type)) {
  2088. throw new _util.FormatError("invalid font Subtype");
  2089. }
  2090. composite = true;
  2091. }
  2092. var descriptor = dict.get("FontDescriptor");
  2093. if (descriptor) {
  2094. var hash = new _murmurhash.MurmurHash3_64();
  2095. var encoding = baseDict.getRaw("Encoding");
  2096. if ((0, _primitives.isName)(encoding)) {
  2097. hash.update(encoding.name);
  2098. } else if ((0, _primitives.isRef)(encoding)) {
  2099. hash.update(encoding.toString());
  2100. } else if ((0, _primitives.isDict)(encoding)) {
  2101. var keys = encoding.getKeys();
  2102. for (var i = 0, ii = keys.length; i < ii; i++) {
  2103. var entry = encoding.getRaw(keys[i]);
  2104. if ((0, _primitives.isName)(entry)) {
  2105. hash.update(entry.name);
  2106. } else if ((0, _primitives.isRef)(entry)) {
  2107. hash.update(entry.toString());
  2108. } else if (Array.isArray(entry)) {
  2109. var diffLength = entry.length,
  2110. diffBuf = new Array(diffLength);
  2111. for (var j = 0; j < diffLength; j++) {
  2112. var diffEntry = entry[j];
  2113. if ((0, _primitives.isName)(diffEntry)) {
  2114. diffBuf[j] = diffEntry.name;
  2115. } else if ((0, _util.isNum)(diffEntry) || (0, _primitives.isRef)(diffEntry)) {
  2116. diffBuf[j] = diffEntry.toString();
  2117. }
  2118. }
  2119. hash.update(diffBuf.join());
  2120. }
  2121. }
  2122. }
  2123. const firstChar = dict.get("FirstChar") || 0;
  2124. const lastChar = dict.get("LastChar") || (composite ? 0xffff : 0xff);
  2125. hash.update(`${firstChar}-${lastChar}`);
  2126. var toUnicode = dict.get("ToUnicode") || baseDict.get("ToUnicode");
  2127. if ((0, _primitives.isStream)(toUnicode)) {
  2128. var stream = toUnicode.str || toUnicode;
  2129. uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
  2130. hash.update(uint8array);
  2131. } else if ((0, _primitives.isName)(toUnicode)) {
  2132. hash.update(toUnicode.name);
  2133. }
  2134. var widths = dict.get("Widths") || baseDict.get("Widths");
  2135. if (widths) {
  2136. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  2137. hash.update(uint8array);
  2138. }
  2139. }
  2140. return {
  2141. descriptor,
  2142. dict,
  2143. baseDict,
  2144. composite,
  2145. type: type.name,
  2146. hash: hash ? hash.hexdigest() : ""
  2147. };
  2148. },
  2149. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
  2150. var baseDict = preEvaluatedFont.baseDict;
  2151. var dict = preEvaluatedFont.dict;
  2152. var composite = preEvaluatedFont.composite;
  2153. var descriptor = preEvaluatedFont.descriptor;
  2154. var type = preEvaluatedFont.type;
  2155. var maxCharIndex = composite ? 0xffff : 0xff;
  2156. var properties;
  2157. const firstChar = dict.get("FirstChar") || 0;
  2158. const lastChar = dict.get("LastChar") || maxCharIndex;
  2159. if (!descriptor) {
  2160. if (type === "Type3") {
  2161. descriptor = new _primitives.Dict(null);
  2162. descriptor.set("FontName", _primitives.Name.get(type));
  2163. descriptor.set("FontBBox", dict.getArray("FontBBox") || [0, 0, 0, 0]);
  2164. } else {
  2165. var baseFontName = dict.get("BaseFont");
  2166. if (!(0, _primitives.isName)(baseFontName)) {
  2167. throw new _util.FormatError("Base font is not specified");
  2168. }
  2169. baseFontName = baseFontName.name.replace(/[,_]/g, "-");
  2170. var metrics = this.getBaseFontMetrics(baseFontName);
  2171. var fontNameWoStyle = baseFontName.split("-")[0];
  2172. var flags = (this.isSerifFont(fontNameWoStyle) ? _fonts.FontFlags.Serif : 0) | (metrics.monospace ? _fonts.FontFlags.FixedPitch : 0) | ((0, _standard_fonts.getSymbolsFonts)()[fontNameWoStyle] ? _fonts.FontFlags.Symbolic : _fonts.FontFlags.Nonsymbolic);
  2173. properties = {
  2174. type,
  2175. name: baseFontName,
  2176. widths: metrics.widths,
  2177. defaultWidth: metrics.defaultWidth,
  2178. flags,
  2179. firstChar,
  2180. lastChar
  2181. };
  2182. const widths = dict.get("Widths");
  2183. return this.extractDataStructures(dict, dict, properties).then(properties => {
  2184. if (widths) {
  2185. const glyphWidths = [];
  2186. let j = firstChar;
  2187. for (let i = 0, ii = widths.length; i < ii; i++) {
  2188. glyphWidths[j++] = this.xref.fetchIfRef(widths[i]);
  2189. }
  2190. properties.widths = glyphWidths;
  2191. } else {
  2192. properties.widths = this.buildCharCodeToWidth(metrics.widths, properties);
  2193. }
  2194. return new _fonts.Font(baseFontName, null, properties);
  2195. });
  2196. }
  2197. }
  2198. var fontName = descriptor.get("FontName");
  2199. var baseFont = dict.get("BaseFont");
  2200. if ((0, _util.isString)(fontName)) {
  2201. fontName = _primitives.Name.get(fontName);
  2202. }
  2203. if ((0, _util.isString)(baseFont)) {
  2204. baseFont = _primitives.Name.get(baseFont);
  2205. }
  2206. if (type !== "Type3") {
  2207. var fontNameStr = fontName && fontName.name;
  2208. var baseFontStr = baseFont && baseFont.name;
  2209. if (fontNameStr !== baseFontStr) {
  2210. (0, _util.info)(`The FontDescriptor\'s FontName is "${fontNameStr}" but ` + `should be the same as the Font\'s BaseFont "${baseFontStr}".`);
  2211. if (fontNameStr && baseFontStr && baseFontStr.startsWith(fontNameStr)) {
  2212. fontName = baseFont;
  2213. }
  2214. }
  2215. }
  2216. fontName = fontName || baseFont;
  2217. if (!(0, _primitives.isName)(fontName)) {
  2218. throw new _util.FormatError("invalid font name");
  2219. }
  2220. var fontFile = descriptor.get("FontFile", "FontFile2", "FontFile3");
  2221. if (fontFile) {
  2222. if (fontFile.dict) {
  2223. var subtype = fontFile.dict.get("Subtype");
  2224. if (subtype) {
  2225. subtype = subtype.name;
  2226. }
  2227. var length1 = fontFile.dict.get("Length1");
  2228. var length2 = fontFile.dict.get("Length2");
  2229. var length3 = fontFile.dict.get("Length3");
  2230. }
  2231. }
  2232. properties = {
  2233. type,
  2234. name: fontName.name,
  2235. subtype,
  2236. file: fontFile,
  2237. length1,
  2238. length2,
  2239. length3,
  2240. loadedName: baseDict.loadedName,
  2241. composite,
  2242. wideChars: composite,
  2243. fixedPitch: false,
  2244. fontMatrix: dict.getArray("FontMatrix") || _util.FONT_IDENTITY_MATRIX,
  2245. firstChar: firstChar || 0,
  2246. lastChar: lastChar || maxCharIndex,
  2247. bbox: descriptor.getArray("FontBBox"),
  2248. ascent: descriptor.get("Ascent"),
  2249. descent: descriptor.get("Descent"),
  2250. xHeight: descriptor.get("XHeight"),
  2251. capHeight: descriptor.get("CapHeight"),
  2252. flags: descriptor.get("Flags"),
  2253. italicAngle: descriptor.get("ItalicAngle"),
  2254. isType3Font: false
  2255. };
  2256. var cMapPromise;
  2257. if (composite) {
  2258. var cidEncoding = baseDict.get("Encoding");
  2259. if ((0, _primitives.isName)(cidEncoding)) {
  2260. properties.cidEncoding = cidEncoding.name;
  2261. }
  2262. cMapPromise = _cmap.CMapFactory.create({
  2263. encoding: cidEncoding,
  2264. fetchBuiltInCMap: this.fetchBuiltInCMap,
  2265. useCMap: null
  2266. }).then(function (cMap) {
  2267. properties.cMap = cMap;
  2268. properties.vertical = properties.cMap.vertical;
  2269. });
  2270. } else {
  2271. cMapPromise = Promise.resolve(undefined);
  2272. }
  2273. return cMapPromise.then(() => {
  2274. return this.extractDataStructures(dict, baseDict, properties);
  2275. }).then(properties => {
  2276. this.extractWidths(dict, descriptor, properties);
  2277. if (type === "Type3") {
  2278. properties.isType3Font = true;
  2279. }
  2280. return new _fonts.Font(fontName.name, fontFile, properties);
  2281. });
  2282. }
  2283. };
  2284. PartialEvaluator.buildFontPaths = function (font, glyphs, handler) {
  2285. function buildPath(fontChar) {
  2286. if (font.renderer.hasBuiltPath(fontChar)) {
  2287. return;
  2288. }
  2289. handler.send("commonobj", [`${font.loadedName}_path_${fontChar}`, "FontPath", font.renderer.getPathJs(fontChar)]);
  2290. }
  2291. for (const glyph of glyphs) {
  2292. buildPath(glyph.fontChar);
  2293. const accent = glyph.accent;
  2294. if (accent && accent.fontChar) {
  2295. buildPath(accent.fontChar);
  2296. }
  2297. }
  2298. };
  2299. PartialEvaluator.getFallbackFontDict = function () {
  2300. if (this._fallbackFontDict) {
  2301. return this._fallbackFontDict;
  2302. }
  2303. const dict = new _primitives.Dict();
  2304. dict.set("BaseFont", _primitives.Name.get("PDFJS-FallbackFont"));
  2305. dict.set("Type", _primitives.Name.get("FallbackType"));
  2306. dict.set("Subtype", _primitives.Name.get("FallbackType"));
  2307. dict.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
  2308. return this._fallbackFontDict = dict;
  2309. };
  2310. return PartialEvaluator;
  2311. }();
  2312. exports.PartialEvaluator = PartialEvaluator;
  2313. var TranslatedFont = function TranslatedFontClosure() {
  2314. function TranslatedFont(loadedName, font, dict) {
  2315. this.loadedName = loadedName;
  2316. this.font = font;
  2317. this.dict = dict;
  2318. this.type3Loaded = null;
  2319. this.sent = false;
  2320. }
  2321. TranslatedFont.prototype = {
  2322. send(handler) {
  2323. if (this.sent) {
  2324. return;
  2325. }
  2326. this.sent = true;
  2327. handler.send("commonobj", [this.loadedName, "Font", this.font.exportData()]);
  2328. },
  2329. fallback(handler) {
  2330. if (!this.font.data) {
  2331. return;
  2332. }
  2333. this.font.disableFontFace = true;
  2334. const glyphs = this.font.glyphCacheValues;
  2335. PartialEvaluator.buildFontPaths(this.font, glyphs, handler);
  2336. },
  2337. loadType3Data(evaluator, resources, parentOperatorList, task) {
  2338. if (!this.font.isType3Font) {
  2339. throw new Error("Must be a Type3 font.");
  2340. }
  2341. if (this.type3Loaded) {
  2342. return this.type3Loaded;
  2343. }
  2344. var type3Options = Object.create(evaluator.options);
  2345. type3Options.ignoreErrors = false;
  2346. type3Options.nativeImageDecoderSupport = _util.NativeImageDecoding.NONE;
  2347. var type3Evaluator = evaluator.clone(type3Options);
  2348. type3Evaluator.parsingType3Font = true;
  2349. var translatedFont = this.font;
  2350. var loadCharProcsPromise = Promise.resolve();
  2351. var charProcs = this.dict.get("CharProcs");
  2352. var fontResources = this.dict.get("Resources") || resources;
  2353. var charProcKeys = charProcs.getKeys();
  2354. var charProcOperatorList = Object.create(null);
  2355. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  2356. const key = charProcKeys[i];
  2357. loadCharProcsPromise = loadCharProcsPromise.then(function () {
  2358. var glyphStream = charProcs.get(key);
  2359. var operatorList = new _operator_list.OperatorList();
  2360. return type3Evaluator.getOperatorList({
  2361. stream: glyphStream,
  2362. task,
  2363. resources: fontResources,
  2364. operatorList
  2365. }).then(function () {
  2366. charProcOperatorList[key] = operatorList.getIR();
  2367. parentOperatorList.addDependencies(operatorList.dependencies);
  2368. }).catch(function (reason) {
  2369. (0, _util.warn)(`Type3 font resource "${key}" is not available.`);
  2370. var operatorList = new _operator_list.OperatorList();
  2371. charProcOperatorList[key] = operatorList.getIR();
  2372. });
  2373. });
  2374. }
  2375. this.type3Loaded = loadCharProcsPromise.then(function () {
  2376. translatedFont.charProcOperatorList = charProcOperatorList;
  2377. });
  2378. return this.type3Loaded;
  2379. }
  2380. };
  2381. return TranslatedFont;
  2382. }();
  2383. var StateManager = function StateManagerClosure() {
  2384. function StateManager(initialState) {
  2385. this.state = initialState;
  2386. this.stateStack = [];
  2387. }
  2388. StateManager.prototype = {
  2389. save() {
  2390. var old = this.state;
  2391. this.stateStack.push(this.state);
  2392. this.state = old.clone();
  2393. },
  2394. restore() {
  2395. var prev = this.stateStack.pop();
  2396. if (prev) {
  2397. this.state = prev;
  2398. }
  2399. },
  2400. transform(args) {
  2401. this.state.ctm = _util.Util.transform(this.state.ctm, args);
  2402. }
  2403. };
  2404. return StateManager;
  2405. }();
  2406. var TextState = function TextStateClosure() {
  2407. function TextState() {
  2408. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2409. this.fontName = null;
  2410. this.fontSize = 0;
  2411. this.font = null;
  2412. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  2413. this.textMatrix = _util.IDENTITY_MATRIX.slice();
  2414. this.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  2415. this.charSpacing = 0;
  2416. this.wordSpacing = 0;
  2417. this.leading = 0;
  2418. this.textHScale = 1;
  2419. this.textRise = 0;
  2420. }
  2421. TextState.prototype = {
  2422. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2423. var m = this.textMatrix;
  2424. m[0] = a;
  2425. m[1] = b;
  2426. m[2] = c;
  2427. m[3] = d;
  2428. m[4] = e;
  2429. m[5] = f;
  2430. },
  2431. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2432. var m = this.textLineMatrix;
  2433. m[0] = a;
  2434. m[1] = b;
  2435. m[2] = c;
  2436. m[3] = d;
  2437. m[4] = e;
  2438. m[5] = f;
  2439. },
  2440. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  2441. var m = this.textMatrix;
  2442. m[4] = m[0] * x + m[2] * y + m[4];
  2443. m[5] = m[1] * x + m[3] * y + m[5];
  2444. },
  2445. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  2446. var m = this.textLineMatrix;
  2447. m[4] = m[0] * x + m[2] * y + m[4];
  2448. m[5] = m[1] * x + m[3] * y + m[5];
  2449. },
  2450. calcTextLineMatrixAdvance: function TextState_calcTextLineMatrixAdvance(a, b, c, d, e, f) {
  2451. var font = this.font;
  2452. if (!font) {
  2453. return null;
  2454. }
  2455. var m = this.textLineMatrix;
  2456. if (!(a === m[0] && b === m[1] && c === m[2] && d === m[3])) {
  2457. return null;
  2458. }
  2459. var txDiff = e - m[4],
  2460. tyDiff = f - m[5];
  2461. if (font.vertical && txDiff !== 0 || !font.vertical && tyDiff !== 0) {
  2462. return null;
  2463. }
  2464. var tx,
  2465. ty,
  2466. denominator = a * d - b * c;
  2467. if (font.vertical) {
  2468. tx = -tyDiff * c / denominator;
  2469. ty = tyDiff * a / denominator;
  2470. } else {
  2471. tx = txDiff * d / denominator;
  2472. ty = -txDiff * b / denominator;
  2473. }
  2474. return {
  2475. width: tx,
  2476. height: ty,
  2477. value: font.vertical ? ty : tx
  2478. };
  2479. },
  2480. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  2481. var tsm = [this.fontSize * this.textHScale, 0, 0, this.fontSize, 0, this.textRise];
  2482. return _util.Util.transform(ctm, _util.Util.transform(this.textMatrix, tsm));
  2483. },
  2484. carriageReturn: function TextState_carriageReturn() {
  2485. this.translateTextLineMatrix(0, -this.leading);
  2486. this.textMatrix = this.textLineMatrix.slice();
  2487. },
  2488. clone: function TextState_clone() {
  2489. var clone = Object.create(this);
  2490. clone.textMatrix = this.textMatrix.slice();
  2491. clone.textLineMatrix = this.textLineMatrix.slice();
  2492. clone.fontMatrix = this.fontMatrix.slice();
  2493. return clone;
  2494. }
  2495. };
  2496. return TextState;
  2497. }();
  2498. var EvalState = function EvalStateClosure() {
  2499. function EvalState() {
  2500. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2501. this.font = null;
  2502. this.textRenderingMode = _util.TextRenderingMode.FILL;
  2503. this.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  2504. this.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  2505. }
  2506. EvalState.prototype = {
  2507. clone: function CanvasExtraState_clone() {
  2508. return Object.create(this);
  2509. }
  2510. };
  2511. return EvalState;
  2512. }();
  2513. var EvaluatorPreprocessor = function EvaluatorPreprocessorClosure() {
  2514. var getOPMap = (0, _core_utils.getLookupTableFactory)(function (t) {
  2515. t["w"] = {
  2516. id: _util.OPS.setLineWidth,
  2517. numArgs: 1,
  2518. variableArgs: false
  2519. };
  2520. t["J"] = {
  2521. id: _util.OPS.setLineCap,
  2522. numArgs: 1,
  2523. variableArgs: false
  2524. };
  2525. t["j"] = {
  2526. id: _util.OPS.setLineJoin,
  2527. numArgs: 1,
  2528. variableArgs: false
  2529. };
  2530. t["M"] = {
  2531. id: _util.OPS.setMiterLimit,
  2532. numArgs: 1,
  2533. variableArgs: false
  2534. };
  2535. t["d"] = {
  2536. id: _util.OPS.setDash,
  2537. numArgs: 2,
  2538. variableArgs: false
  2539. };
  2540. t["ri"] = {
  2541. id: _util.OPS.setRenderingIntent,
  2542. numArgs: 1,
  2543. variableArgs: false
  2544. };
  2545. t["i"] = {
  2546. id: _util.OPS.setFlatness,
  2547. numArgs: 1,
  2548. variableArgs: false
  2549. };
  2550. t["gs"] = {
  2551. id: _util.OPS.setGState,
  2552. numArgs: 1,
  2553. variableArgs: false
  2554. };
  2555. t["q"] = {
  2556. id: _util.OPS.save,
  2557. numArgs: 0,
  2558. variableArgs: false
  2559. };
  2560. t["Q"] = {
  2561. id: _util.OPS.restore,
  2562. numArgs: 0,
  2563. variableArgs: false
  2564. };
  2565. t["cm"] = {
  2566. id: _util.OPS.transform,
  2567. numArgs: 6,
  2568. variableArgs: false
  2569. };
  2570. t["m"] = {
  2571. id: _util.OPS.moveTo,
  2572. numArgs: 2,
  2573. variableArgs: false
  2574. };
  2575. t["l"] = {
  2576. id: _util.OPS.lineTo,
  2577. numArgs: 2,
  2578. variableArgs: false
  2579. };
  2580. t["c"] = {
  2581. id: _util.OPS.curveTo,
  2582. numArgs: 6,
  2583. variableArgs: false
  2584. };
  2585. t["v"] = {
  2586. id: _util.OPS.curveTo2,
  2587. numArgs: 4,
  2588. variableArgs: false
  2589. };
  2590. t["y"] = {
  2591. id: _util.OPS.curveTo3,
  2592. numArgs: 4,
  2593. variableArgs: false
  2594. };
  2595. t["h"] = {
  2596. id: _util.OPS.closePath,
  2597. numArgs: 0,
  2598. variableArgs: false
  2599. };
  2600. t["re"] = {
  2601. id: _util.OPS.rectangle,
  2602. numArgs: 4,
  2603. variableArgs: false
  2604. };
  2605. t["S"] = {
  2606. id: _util.OPS.stroke,
  2607. numArgs: 0,
  2608. variableArgs: false
  2609. };
  2610. t["s"] = {
  2611. id: _util.OPS.closeStroke,
  2612. numArgs: 0,
  2613. variableArgs: false
  2614. };
  2615. t["f"] = {
  2616. id: _util.OPS.fill,
  2617. numArgs: 0,
  2618. variableArgs: false
  2619. };
  2620. t["F"] = {
  2621. id: _util.OPS.fill,
  2622. numArgs: 0,
  2623. variableArgs: false
  2624. };
  2625. t["f*"] = {
  2626. id: _util.OPS.eoFill,
  2627. numArgs: 0,
  2628. variableArgs: false
  2629. };
  2630. t["B"] = {
  2631. id: _util.OPS.fillStroke,
  2632. numArgs: 0,
  2633. variableArgs: false
  2634. };
  2635. t["B*"] = {
  2636. id: _util.OPS.eoFillStroke,
  2637. numArgs: 0,
  2638. variableArgs: false
  2639. };
  2640. t["b"] = {
  2641. id: _util.OPS.closeFillStroke,
  2642. numArgs: 0,
  2643. variableArgs: false
  2644. };
  2645. t["b*"] = {
  2646. id: _util.OPS.closeEOFillStroke,
  2647. numArgs: 0,
  2648. variableArgs: false
  2649. };
  2650. t["n"] = {
  2651. id: _util.OPS.endPath,
  2652. numArgs: 0,
  2653. variableArgs: false
  2654. };
  2655. t["W"] = {
  2656. id: _util.OPS.clip,
  2657. numArgs: 0,
  2658. variableArgs: false
  2659. };
  2660. t["W*"] = {
  2661. id: _util.OPS.eoClip,
  2662. numArgs: 0,
  2663. variableArgs: false
  2664. };
  2665. t["BT"] = {
  2666. id: _util.OPS.beginText,
  2667. numArgs: 0,
  2668. variableArgs: false
  2669. };
  2670. t["ET"] = {
  2671. id: _util.OPS.endText,
  2672. numArgs: 0,
  2673. variableArgs: false
  2674. };
  2675. t["Tc"] = {
  2676. id: _util.OPS.setCharSpacing,
  2677. numArgs: 1,
  2678. variableArgs: false
  2679. };
  2680. t["Tw"] = {
  2681. id: _util.OPS.setWordSpacing,
  2682. numArgs: 1,
  2683. variableArgs: false
  2684. };
  2685. t["Tz"] = {
  2686. id: _util.OPS.setHScale,
  2687. numArgs: 1,
  2688. variableArgs: false
  2689. };
  2690. t["TL"] = {
  2691. id: _util.OPS.setLeading,
  2692. numArgs: 1,
  2693. variableArgs: false
  2694. };
  2695. t["Tf"] = {
  2696. id: _util.OPS.setFont,
  2697. numArgs: 2,
  2698. variableArgs: false
  2699. };
  2700. t["Tr"] = {
  2701. id: _util.OPS.setTextRenderingMode,
  2702. numArgs: 1,
  2703. variableArgs: false
  2704. };
  2705. t["Ts"] = {
  2706. id: _util.OPS.setTextRise,
  2707. numArgs: 1,
  2708. variableArgs: false
  2709. };
  2710. t["Td"] = {
  2711. id: _util.OPS.moveText,
  2712. numArgs: 2,
  2713. variableArgs: false
  2714. };
  2715. t["TD"] = {
  2716. id: _util.OPS.setLeadingMoveText,
  2717. numArgs: 2,
  2718. variableArgs: false
  2719. };
  2720. t["Tm"] = {
  2721. id: _util.OPS.setTextMatrix,
  2722. numArgs: 6,
  2723. variableArgs: false
  2724. };
  2725. t["T*"] = {
  2726. id: _util.OPS.nextLine,
  2727. numArgs: 0,
  2728. variableArgs: false
  2729. };
  2730. t["Tj"] = {
  2731. id: _util.OPS.showText,
  2732. numArgs: 1,
  2733. variableArgs: false
  2734. };
  2735. t["TJ"] = {
  2736. id: _util.OPS.showSpacedText,
  2737. numArgs: 1,
  2738. variableArgs: false
  2739. };
  2740. t["'"] = {
  2741. id: _util.OPS.nextLineShowText,
  2742. numArgs: 1,
  2743. variableArgs: false
  2744. };
  2745. t['"'] = {
  2746. id: _util.OPS.nextLineSetSpacingShowText,
  2747. numArgs: 3,
  2748. variableArgs: false
  2749. };
  2750. t["d0"] = {
  2751. id: _util.OPS.setCharWidth,
  2752. numArgs: 2,
  2753. variableArgs: false
  2754. };
  2755. t["d1"] = {
  2756. id: _util.OPS.setCharWidthAndBounds,
  2757. numArgs: 6,
  2758. variableArgs: false
  2759. };
  2760. t["CS"] = {
  2761. id: _util.OPS.setStrokeColorSpace,
  2762. numArgs: 1,
  2763. variableArgs: false
  2764. };
  2765. t["cs"] = {
  2766. id: _util.OPS.setFillColorSpace,
  2767. numArgs: 1,
  2768. variableArgs: false
  2769. };
  2770. t["SC"] = {
  2771. id: _util.OPS.setStrokeColor,
  2772. numArgs: 4,
  2773. variableArgs: true
  2774. };
  2775. t["SCN"] = {
  2776. id: _util.OPS.setStrokeColorN,
  2777. numArgs: 33,
  2778. variableArgs: true
  2779. };
  2780. t["sc"] = {
  2781. id: _util.OPS.setFillColor,
  2782. numArgs: 4,
  2783. variableArgs: true
  2784. };
  2785. t["scn"] = {
  2786. id: _util.OPS.setFillColorN,
  2787. numArgs: 33,
  2788. variableArgs: true
  2789. };
  2790. t["G"] = {
  2791. id: _util.OPS.setStrokeGray,
  2792. numArgs: 1,
  2793. variableArgs: false
  2794. };
  2795. t["g"] = {
  2796. id: _util.OPS.setFillGray,
  2797. numArgs: 1,
  2798. variableArgs: false
  2799. };
  2800. t["RG"] = {
  2801. id: _util.OPS.setStrokeRGBColor,
  2802. numArgs: 3,
  2803. variableArgs: false
  2804. };
  2805. t["rg"] = {
  2806. id: _util.OPS.setFillRGBColor,
  2807. numArgs: 3,
  2808. variableArgs: false
  2809. };
  2810. t["K"] = {
  2811. id: _util.OPS.setStrokeCMYKColor,
  2812. numArgs: 4,
  2813. variableArgs: false
  2814. };
  2815. t["k"] = {
  2816. id: _util.OPS.setFillCMYKColor,
  2817. numArgs: 4,
  2818. variableArgs: false
  2819. };
  2820. t["sh"] = {
  2821. id: _util.OPS.shadingFill,
  2822. numArgs: 1,
  2823. variableArgs: false
  2824. };
  2825. t["BI"] = {
  2826. id: _util.OPS.beginInlineImage,
  2827. numArgs: 0,
  2828. variableArgs: false
  2829. };
  2830. t["ID"] = {
  2831. id: _util.OPS.beginImageData,
  2832. numArgs: 0,
  2833. variableArgs: false
  2834. };
  2835. t["EI"] = {
  2836. id: _util.OPS.endInlineImage,
  2837. numArgs: 1,
  2838. variableArgs: false
  2839. };
  2840. t["Do"] = {
  2841. id: _util.OPS.paintXObject,
  2842. numArgs: 1,
  2843. variableArgs: false
  2844. };
  2845. t["MP"] = {
  2846. id: _util.OPS.markPoint,
  2847. numArgs: 1,
  2848. variableArgs: false
  2849. };
  2850. t["DP"] = {
  2851. id: _util.OPS.markPointProps,
  2852. numArgs: 2,
  2853. variableArgs: false
  2854. };
  2855. t["BMC"] = {
  2856. id: _util.OPS.beginMarkedContent,
  2857. numArgs: 1,
  2858. variableArgs: false
  2859. };
  2860. t["BDC"] = {
  2861. id: _util.OPS.beginMarkedContentProps,
  2862. numArgs: 2,
  2863. variableArgs: false
  2864. };
  2865. t["EMC"] = {
  2866. id: _util.OPS.endMarkedContent,
  2867. numArgs: 0,
  2868. variableArgs: false
  2869. };
  2870. t["BX"] = {
  2871. id: _util.OPS.beginCompat,
  2872. numArgs: 0,
  2873. variableArgs: false
  2874. };
  2875. t["EX"] = {
  2876. id: _util.OPS.endCompat,
  2877. numArgs: 0,
  2878. variableArgs: false
  2879. };
  2880. t["BM"] = null;
  2881. t["BD"] = null;
  2882. t["true"] = null;
  2883. t["fa"] = null;
  2884. t["fal"] = null;
  2885. t["fals"] = null;
  2886. t["false"] = null;
  2887. t["nu"] = null;
  2888. t["nul"] = null;
  2889. t["null"] = null;
  2890. });
  2891. const MAX_INVALID_PATH_OPS = 20;
  2892. function EvaluatorPreprocessor(stream, xref, stateManager) {
  2893. this.opMap = getOPMap();
  2894. this.parser = new _parser.Parser({
  2895. lexer: new _parser.Lexer(stream, this.opMap),
  2896. xref
  2897. });
  2898. this.stateManager = stateManager;
  2899. this.nonProcessedArgs = [];
  2900. this._numInvalidPathOPS = 0;
  2901. }
  2902. EvaluatorPreprocessor.prototype = {
  2903. get savedStatesDepth() {
  2904. return this.stateManager.stateStack.length;
  2905. },
  2906. read: function EvaluatorPreprocessor_read(operation) {
  2907. var args = operation.args;
  2908. while (true) {
  2909. var obj = this.parser.getObj();
  2910. if (obj instanceof _primitives.Cmd) {
  2911. var cmd = obj.cmd;
  2912. var opSpec = this.opMap[cmd];
  2913. if (!opSpec) {
  2914. (0, _util.warn)(`Unknown command "${cmd}".`);
  2915. continue;
  2916. }
  2917. var fn = opSpec.id;
  2918. var numArgs = opSpec.numArgs;
  2919. var argsLength = args !== null ? args.length : 0;
  2920. if (!opSpec.variableArgs) {
  2921. if (argsLength !== numArgs) {
  2922. var nonProcessedArgs = this.nonProcessedArgs;
  2923. while (argsLength > numArgs) {
  2924. nonProcessedArgs.push(args.shift());
  2925. argsLength--;
  2926. }
  2927. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  2928. if (args === null) {
  2929. args = [];
  2930. }
  2931. args.unshift(nonProcessedArgs.pop());
  2932. argsLength++;
  2933. }
  2934. }
  2935. if (argsLength < numArgs) {
  2936. const partialMsg = `command ${cmd}: expected ${numArgs} args, ` + `but received ${argsLength} args.`;
  2937. if (fn >= _util.OPS.moveTo && fn <= _util.OPS.endPath && ++this._numInvalidPathOPS > MAX_INVALID_PATH_OPS) {
  2938. throw new _util.FormatError(`Invalid ${partialMsg}`);
  2939. }
  2940. (0, _util.warn)(`Skipping ${partialMsg}`);
  2941. if (args !== null) {
  2942. args.length = 0;
  2943. }
  2944. continue;
  2945. }
  2946. } else if (argsLength > numArgs) {
  2947. (0, _util.info)(`Command ${cmd}: expected [0, ${numArgs}] args, ` + `but received ${argsLength} args.`);
  2948. }
  2949. this.preprocessCommand(fn, args);
  2950. operation.fn = fn;
  2951. operation.args = args;
  2952. return true;
  2953. }
  2954. if (obj === _primitives.EOF) {
  2955. return false;
  2956. }
  2957. if (obj !== null) {
  2958. if (args === null) {
  2959. args = [];
  2960. }
  2961. args.push(obj);
  2962. if (args.length > 33) {
  2963. throw new _util.FormatError("Too many arguments");
  2964. }
  2965. }
  2966. }
  2967. },
  2968. preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  2969. switch (fn | 0) {
  2970. case _util.OPS.save:
  2971. this.stateManager.save();
  2972. break;
  2973. case _util.OPS.restore:
  2974. this.stateManager.restore();
  2975. break;
  2976. case _util.OPS.transform:
  2977. this.stateManager.transform(args);
  2978. break;
  2979. }
  2980. }
  2981. };
  2982. return EvaluatorPreprocessor;
  2983. }();