2
0

evaluator.js 99 KB

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