2
0

evaluator.js 91 KB

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