evaluator.js 129 KB

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