evaluator.js 108 KB

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