evaluator.js 106 KB

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