evaluator.js 103 KB

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