evaluator.js 107 KB

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