2
0

evaluator.js 104 KB

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