evaluator.js 104 KB

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