evaluator.js 106 KB

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