evaluator.js 108 KB

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