evaluator.js 102 KB

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