evaluator.js 98 KB

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