evaluator.js 98 KB

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