evaluator.js 110 KB

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