evaluator.js 110 KB

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