evaluator.js 108 KB

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