canvas.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.CanvasGraphics = void 0;
  27. var _util = require("../shared/util.js");
  28. var _pattern_helper = require("./pattern_helper.js");
  29. const MIN_FONT_SIZE = 16;
  30. const MAX_FONT_SIZE = 100;
  31. const MAX_GROUP_SIZE = 4096;
  32. const COMPILE_TYPE3_GLYPHS = true;
  33. const MAX_SIZE_TO_COMPILE = 1000;
  34. const FULL_CHUNK_HEIGHT = 16;
  35. function addContextCurrentTransform(ctx) {
  36. if (!ctx.mozCurrentTransform) {
  37. ctx._originalSave = ctx.save;
  38. ctx._originalRestore = ctx.restore;
  39. ctx._originalRotate = ctx.rotate;
  40. ctx._originalScale = ctx.scale;
  41. ctx._originalTranslate = ctx.translate;
  42. ctx._originalTransform = ctx.transform;
  43. ctx._originalSetTransform = ctx.setTransform;
  44. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  45. ctx._transformStack = [];
  46. Object.defineProperty(ctx, "mozCurrentTransform", {
  47. get: function getCurrentTransform() {
  48. return this._transformMatrix;
  49. }
  50. });
  51. Object.defineProperty(ctx, "mozCurrentTransformInverse", {
  52. get: function getCurrentTransformInverse() {
  53. const m = this._transformMatrix;
  54. const a = m[0],
  55. b = m[1],
  56. c = m[2],
  57. d = m[3],
  58. e = m[4],
  59. f = m[5];
  60. const ad_bc = a * d - b * c;
  61. const bc_ad = b * c - a * d;
  62. return [d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc];
  63. }
  64. });
  65. ctx.save = function ctxSave() {
  66. const old = this._transformMatrix;
  67. this._transformStack.push(old);
  68. this._transformMatrix = old.slice(0, 6);
  69. this._originalSave();
  70. };
  71. ctx.restore = function ctxRestore() {
  72. const prev = this._transformStack.pop();
  73. if (prev) {
  74. this._transformMatrix = prev;
  75. this._originalRestore();
  76. }
  77. };
  78. ctx.translate = function ctxTranslate(x, y) {
  79. const m = this._transformMatrix;
  80. m[4] = m[0] * x + m[2] * y + m[4];
  81. m[5] = m[1] * x + m[3] * y + m[5];
  82. this._originalTranslate(x, y);
  83. };
  84. ctx.scale = function ctxScale(x, y) {
  85. const m = this._transformMatrix;
  86. m[0] = m[0] * x;
  87. m[1] = m[1] * x;
  88. m[2] = m[2] * y;
  89. m[3] = m[3] * y;
  90. this._originalScale(x, y);
  91. };
  92. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  93. const m = this._transformMatrix;
  94. this._transformMatrix = [m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5]];
  95. ctx._originalTransform(a, b, c, d, e, f);
  96. };
  97. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  98. this._transformMatrix = [a, b, c, d, e, f];
  99. ctx._originalSetTransform(a, b, c, d, e, f);
  100. };
  101. ctx.rotate = function ctxRotate(angle) {
  102. const cosValue = Math.cos(angle);
  103. const sinValue = Math.sin(angle);
  104. const m = this._transformMatrix;
  105. this._transformMatrix = [m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * -sinValue + m[2] * cosValue, m[1] * -sinValue + m[3] * cosValue, m[4], m[5]];
  106. this._originalRotate(angle);
  107. };
  108. }
  109. }
  110. const CachedCanvases = function CachedCanvasesClosure() {
  111. function CachedCanvases(canvasFactory) {
  112. this.canvasFactory = canvasFactory;
  113. this.cache = Object.create(null);
  114. }
  115. CachedCanvases.prototype = {
  116. getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
  117. let canvasEntry;
  118. if (this.cache[id] !== undefined) {
  119. canvasEntry = this.cache[id];
  120. this.canvasFactory.reset(canvasEntry, width, height);
  121. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  122. } else {
  123. canvasEntry = this.canvasFactory.create(width, height);
  124. this.cache[id] = canvasEntry;
  125. }
  126. if (trackTransform) {
  127. addContextCurrentTransform(canvasEntry.context);
  128. }
  129. return canvasEntry;
  130. },
  131. clear() {
  132. for (const id in this.cache) {
  133. const canvasEntry = this.cache[id];
  134. this.canvasFactory.destroy(canvasEntry);
  135. delete this.cache[id];
  136. }
  137. }
  138. };
  139. return CachedCanvases;
  140. }();
  141. function compileType3Glyph(imgData) {
  142. const POINT_TO_PROCESS_LIMIT = 1000;
  143. const width = imgData.width,
  144. height = imgData.height,
  145. width1 = width + 1;
  146. let i, ii, j, j0;
  147. const points = new Uint8Array(width1 * (height + 1));
  148. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  149. const lineSize = width + 7 & ~7,
  150. data0 = imgData.data;
  151. const data = new Uint8Array(lineSize * height);
  152. let pos = 0;
  153. for (i = 0, ii = data0.length; i < ii; i++) {
  154. const elem = data0[i];
  155. let mask = 128;
  156. while (mask > 0) {
  157. data[pos++] = elem & mask ? 0 : 255;
  158. mask >>= 1;
  159. }
  160. }
  161. let count = 0;
  162. pos = 0;
  163. if (data[pos] !== 0) {
  164. points[0] = 1;
  165. ++count;
  166. }
  167. for (j = 1; j < width; j++) {
  168. if (data[pos] !== data[pos + 1]) {
  169. points[j] = data[pos] ? 2 : 1;
  170. ++count;
  171. }
  172. pos++;
  173. }
  174. if (data[pos] !== 0) {
  175. points[j] = 2;
  176. ++count;
  177. }
  178. for (i = 1; i < height; i++) {
  179. pos = i * lineSize;
  180. j0 = i * width1;
  181. if (data[pos - lineSize] !== data[pos]) {
  182. points[j0] = data[pos] ? 1 : 8;
  183. ++count;
  184. }
  185. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  186. for (j = 1; j < width; j++) {
  187. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  188. if (POINT_TYPES[sum]) {
  189. points[j0 + j] = POINT_TYPES[sum];
  190. ++count;
  191. }
  192. pos++;
  193. }
  194. if (data[pos - lineSize] !== data[pos]) {
  195. points[j0 + j] = data[pos] ? 2 : 4;
  196. ++count;
  197. }
  198. if (count > POINT_TO_PROCESS_LIMIT) {
  199. return null;
  200. }
  201. }
  202. pos = lineSize * (height - 1);
  203. j0 = i * width1;
  204. if (data[pos] !== 0) {
  205. points[j0] = 8;
  206. ++count;
  207. }
  208. for (j = 1; j < width; j++) {
  209. if (data[pos] !== data[pos + 1]) {
  210. points[j0 + j] = data[pos] ? 4 : 8;
  211. ++count;
  212. }
  213. pos++;
  214. }
  215. if (data[pos] !== 0) {
  216. points[j0 + j] = 4;
  217. ++count;
  218. }
  219. if (count > POINT_TO_PROCESS_LIMIT) {
  220. return null;
  221. }
  222. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  223. const outlines = [];
  224. for (i = 0; count && i <= height; i++) {
  225. let p = i * width1;
  226. const end = p + width;
  227. while (p < end && !points[p]) {
  228. p++;
  229. }
  230. if (p === end) {
  231. continue;
  232. }
  233. const coords = [p % width1, i];
  234. const p0 = p;
  235. let type = points[p];
  236. do {
  237. const step = steps[type];
  238. do {
  239. p += step;
  240. } while (!points[p]);
  241. const pp = points[p];
  242. if (pp !== 5 && pp !== 10) {
  243. type = pp;
  244. points[p] = 0;
  245. } else {
  246. type = pp & 0x33 * type >> 4;
  247. points[p] &= type >> 2 | type << 2;
  248. }
  249. coords.push(p % width1);
  250. coords.push(p / width1 | 0);
  251. if (!points[p]) {
  252. --count;
  253. }
  254. } while (p0 !== p);
  255. outlines.push(coords);
  256. --i;
  257. }
  258. const drawOutline = function (c) {
  259. c.save();
  260. c.scale(1 / width, -1 / height);
  261. c.translate(0, -height);
  262. c.beginPath();
  263. for (let k = 0, kk = outlines.length; k < kk; k++) {
  264. const o = outlines[k];
  265. c.moveTo(o[0], o[1]);
  266. for (let l = 2, ll = o.length; l < ll; l += 2) {
  267. c.lineTo(o[l], o[l + 1]);
  268. }
  269. }
  270. c.fill();
  271. c.beginPath();
  272. c.restore();
  273. };
  274. return drawOutline;
  275. }
  276. const CanvasExtraState = function CanvasExtraStateClosure() {
  277. function CanvasExtraState() {
  278. this.alphaIsShape = false;
  279. this.fontSize = 0;
  280. this.fontSizeScale = 1;
  281. this.textMatrix = _util.IDENTITY_MATRIX;
  282. this.textMatrixScale = 1;
  283. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  284. this.leading = 0;
  285. this.x = 0;
  286. this.y = 0;
  287. this.lineX = 0;
  288. this.lineY = 0;
  289. this.charSpacing = 0;
  290. this.wordSpacing = 0;
  291. this.textHScale = 1;
  292. this.textRenderingMode = _util.TextRenderingMode.FILL;
  293. this.textRise = 0;
  294. this.fillColor = "#000000";
  295. this.strokeColor = "#000000";
  296. this.patternFill = false;
  297. this.fillAlpha = 1;
  298. this.strokeAlpha = 1;
  299. this.lineWidth = 1;
  300. this.activeSMask = null;
  301. this.resumeSMaskCtx = null;
  302. this.transferMaps = null;
  303. }
  304. CanvasExtraState.prototype = {
  305. clone: function CanvasExtraState_clone() {
  306. return Object.create(this);
  307. },
  308. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  309. this.x = x;
  310. this.y = y;
  311. }
  312. };
  313. return CanvasExtraState;
  314. }();
  315. const CanvasGraphics = function CanvasGraphicsClosure() {
  316. const EXECUTION_TIME = 15;
  317. const EXECUTION_STEPS = 10;
  318. function CanvasGraphics(canvasCtx, commonObjs, objs, canvasFactory, webGLContext, imageLayer, optionalContentConfig) {
  319. this.ctx = canvasCtx;
  320. this.current = new CanvasExtraState();
  321. this.stateStack = [];
  322. this.pendingClip = null;
  323. this.pendingEOFill = false;
  324. this.res = null;
  325. this.xobjs = null;
  326. this.commonObjs = commonObjs;
  327. this.objs = objs;
  328. this.canvasFactory = canvasFactory;
  329. this.webGLContext = webGLContext;
  330. this.imageLayer = imageLayer;
  331. this.groupStack = [];
  332. this.processingType3 = null;
  333. this.baseTransform = null;
  334. this.baseTransformStack = [];
  335. this.groupLevel = 0;
  336. this.smaskStack = [];
  337. this.smaskCounter = 0;
  338. this.tempSMask = null;
  339. this.contentVisible = true;
  340. this.markedContentStack = [];
  341. this.optionalContentConfig = optionalContentConfig;
  342. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  343. if (canvasCtx) {
  344. addContextCurrentTransform(canvasCtx);
  345. }
  346. this._cachedGetSinglePixelWidth = null;
  347. }
  348. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  349. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  350. ctx.putImageData(imgData, 0, 0);
  351. return;
  352. }
  353. const height = imgData.height,
  354. width = imgData.width;
  355. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  356. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  357. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  358. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  359. let srcPos = 0,
  360. destPos;
  361. const src = imgData.data;
  362. const dest = chunkImgData.data;
  363. let i, j, thisChunkHeight, elemsInThisChunk;
  364. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  365. if (transferMaps) {
  366. switch (transferMaps.length) {
  367. case 1:
  368. transferMapRed = transferMaps[0];
  369. transferMapGreen = transferMaps[0];
  370. transferMapBlue = transferMaps[0];
  371. transferMapGray = transferMaps[0];
  372. break;
  373. case 4:
  374. transferMapRed = transferMaps[0];
  375. transferMapGreen = transferMaps[1];
  376. transferMapBlue = transferMaps[2];
  377. transferMapGray = transferMaps[3];
  378. break;
  379. }
  380. }
  381. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  382. const srcLength = src.byteLength;
  383. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  384. const dest32DataLength = dest32.length;
  385. const fullSrcDiff = width + 7 >> 3;
  386. let white = 0xffffffff;
  387. let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff;
  388. if (transferMapGray) {
  389. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  390. [white, black] = [black, white];
  391. }
  392. }
  393. for (i = 0; i < totalChunks; i++) {
  394. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  395. destPos = 0;
  396. for (j = 0; j < thisChunkHeight; j++) {
  397. const srcDiff = srcLength - srcPos;
  398. let k = 0;
  399. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  400. const kEndUnrolled = kEnd & ~7;
  401. let mask = 0;
  402. let srcByte = 0;
  403. for (; k < kEndUnrolled; k += 8) {
  404. srcByte = src[srcPos++];
  405. dest32[destPos++] = srcByte & 128 ? white : black;
  406. dest32[destPos++] = srcByte & 64 ? white : black;
  407. dest32[destPos++] = srcByte & 32 ? white : black;
  408. dest32[destPos++] = srcByte & 16 ? white : black;
  409. dest32[destPos++] = srcByte & 8 ? white : black;
  410. dest32[destPos++] = srcByte & 4 ? white : black;
  411. dest32[destPos++] = srcByte & 2 ? white : black;
  412. dest32[destPos++] = srcByte & 1 ? white : black;
  413. }
  414. for (; k < kEnd; k++) {
  415. if (mask === 0) {
  416. srcByte = src[srcPos++];
  417. mask = 128;
  418. }
  419. dest32[destPos++] = srcByte & mask ? white : black;
  420. mask >>= 1;
  421. }
  422. }
  423. while (destPos < dest32DataLength) {
  424. dest32[destPos++] = 0;
  425. }
  426. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  427. }
  428. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  429. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  430. j = 0;
  431. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  432. for (i = 0; i < fullChunks; i++) {
  433. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  434. srcPos += elemsInThisChunk;
  435. if (hasTransferMaps) {
  436. for (let k = 0; k < elemsInThisChunk; k += 4) {
  437. if (transferMapRed) {
  438. dest[k + 0] = transferMapRed[dest[k + 0]];
  439. }
  440. if (transferMapGreen) {
  441. dest[k + 1] = transferMapGreen[dest[k + 1]];
  442. }
  443. if (transferMapBlue) {
  444. dest[k + 2] = transferMapBlue[dest[k + 2]];
  445. }
  446. }
  447. }
  448. ctx.putImageData(chunkImgData, 0, j);
  449. j += FULL_CHUNK_HEIGHT;
  450. }
  451. if (i < totalChunks) {
  452. elemsInThisChunk = width * partialChunkHeight * 4;
  453. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  454. if (hasTransferMaps) {
  455. for (let k = 0; k < elemsInThisChunk; k += 4) {
  456. if (transferMapRed) {
  457. dest[k + 0] = transferMapRed[dest[k + 0]];
  458. }
  459. if (transferMapGreen) {
  460. dest[k + 1] = transferMapGreen[dest[k + 1]];
  461. }
  462. if (transferMapBlue) {
  463. dest[k + 2] = transferMapBlue[dest[k + 2]];
  464. }
  465. }
  466. }
  467. ctx.putImageData(chunkImgData, 0, j);
  468. }
  469. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  470. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  471. thisChunkHeight = FULL_CHUNK_HEIGHT;
  472. elemsInThisChunk = width * thisChunkHeight;
  473. for (i = 0; i < totalChunks; i++) {
  474. if (i >= fullChunks) {
  475. thisChunkHeight = partialChunkHeight;
  476. elemsInThisChunk = width * thisChunkHeight;
  477. }
  478. destPos = 0;
  479. for (j = elemsInThisChunk; j--;) {
  480. dest[destPos++] = src[srcPos++];
  481. dest[destPos++] = src[srcPos++];
  482. dest[destPos++] = src[srcPos++];
  483. dest[destPos++] = 255;
  484. }
  485. if (hasTransferMaps) {
  486. for (let k = 0; k < destPos; k += 4) {
  487. if (transferMapRed) {
  488. dest[k + 0] = transferMapRed[dest[k + 0]];
  489. }
  490. if (transferMapGreen) {
  491. dest[k + 1] = transferMapGreen[dest[k + 1]];
  492. }
  493. if (transferMapBlue) {
  494. dest[k + 2] = transferMapBlue[dest[k + 2]];
  495. }
  496. }
  497. }
  498. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  499. }
  500. } else {
  501. throw new Error(`bad image kind: ${imgData.kind}`);
  502. }
  503. }
  504. function putBinaryImageMask(ctx, imgData) {
  505. const height = imgData.height,
  506. width = imgData.width;
  507. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  508. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  509. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  510. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  511. let srcPos = 0;
  512. const src = imgData.data;
  513. const dest = chunkImgData.data;
  514. for (let i = 0; i < totalChunks; i++) {
  515. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  516. let destPos = 3;
  517. for (let j = 0; j < thisChunkHeight; j++) {
  518. let elem,
  519. mask = 0;
  520. for (let k = 0; k < width; k++) {
  521. if (!mask) {
  522. elem = src[srcPos++];
  523. mask = 128;
  524. }
  525. dest[destPos] = elem & mask ? 0 : 255;
  526. destPos += 4;
  527. mask >>= 1;
  528. }
  529. }
  530. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  531. }
  532. }
  533. function copyCtxState(sourceCtx, destCtx) {
  534. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  535. for (let i = 0, ii = properties.length; i < ii; i++) {
  536. const property = properties[i];
  537. if (sourceCtx[property] !== undefined) {
  538. destCtx[property] = sourceCtx[property];
  539. }
  540. }
  541. if (sourceCtx.setLineDash !== undefined) {
  542. destCtx.setLineDash(sourceCtx.getLineDash());
  543. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  544. }
  545. }
  546. function resetCtxToDefault(ctx) {
  547. ctx.strokeStyle = "#000000";
  548. ctx.fillStyle = "#000000";
  549. ctx.fillRule = "nonzero";
  550. ctx.globalAlpha = 1;
  551. ctx.lineWidth = 1;
  552. ctx.lineCap = "butt";
  553. ctx.lineJoin = "miter";
  554. ctx.miterLimit = 10;
  555. ctx.globalCompositeOperation = "source-over";
  556. ctx.font = "10px sans-serif";
  557. if (ctx.setLineDash !== undefined) {
  558. ctx.setLineDash([]);
  559. ctx.lineDashOffset = 0;
  560. }
  561. }
  562. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  563. const length = bytes.length;
  564. for (let i = 3; i < length; i += 4) {
  565. const alpha = bytes[i];
  566. if (alpha === 0) {
  567. bytes[i - 3] = r0;
  568. bytes[i - 2] = g0;
  569. bytes[i - 1] = b0;
  570. } else if (alpha < 255) {
  571. const alpha_ = 255 - alpha;
  572. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  573. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  574. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  575. }
  576. }
  577. }
  578. function composeSMaskAlpha(maskData, layerData, transferMap) {
  579. const length = maskData.length;
  580. const scale = 1 / 255;
  581. for (let i = 3; i < length; i += 4) {
  582. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  583. layerData[i] = layerData[i] * alpha * scale | 0;
  584. }
  585. }
  586. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  587. const length = maskData.length;
  588. for (let i = 3; i < length; i += 4) {
  589. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  590. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  591. }
  592. }
  593. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  594. const hasBackdrop = !!backdrop;
  595. const r0 = hasBackdrop ? backdrop[0] : 0;
  596. const g0 = hasBackdrop ? backdrop[1] : 0;
  597. const b0 = hasBackdrop ? backdrop[2] : 0;
  598. let composeFn;
  599. if (subtype === "Luminosity") {
  600. composeFn = composeSMaskLuminosity;
  601. } else {
  602. composeFn = composeSMaskAlpha;
  603. }
  604. const PIXELS_TO_PROCESS = 1048576;
  605. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  606. for (let row = 0; row < height; row += chunkSize) {
  607. const chunkHeight = Math.min(chunkSize, height - row);
  608. const maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  609. const layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  610. if (hasBackdrop) {
  611. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  612. }
  613. composeFn(maskData.data, layerData.data, transferMap);
  614. maskCtx.putImageData(layerData, 0, row);
  615. }
  616. }
  617. function composeSMask(ctx, smask, layerCtx, webGLContext) {
  618. const mask = smask.canvas;
  619. const maskCtx = smask.context;
  620. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  621. const backdrop = smask.backdrop || null;
  622. if (!smask.transferMap && webGLContext.isEnabled) {
  623. const composed = webGLContext.composeSMask({
  624. layer: layerCtx.canvas,
  625. mask,
  626. properties: {
  627. subtype: smask.subtype,
  628. backdrop
  629. }
  630. });
  631. ctx.setTransform(1, 0, 0, 1, 0, 0);
  632. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  633. return;
  634. }
  635. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
  636. ctx.drawImage(mask, 0, 0);
  637. }
  638. const LINE_CAP_STYLES = ["butt", "round", "square"];
  639. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  640. const NORMAL_CLIP = {};
  641. const EO_CLIP = {};
  642. CanvasGraphics.prototype = {
  643. beginDrawing({
  644. transform,
  645. viewport,
  646. transparency = false,
  647. background = null
  648. }) {
  649. const width = this.ctx.canvas.width;
  650. const height = this.ctx.canvas.height;
  651. this.ctx.save();
  652. this.ctx.fillStyle = background || "rgb(255, 255, 255)";
  653. this.ctx.fillRect(0, 0, width, height);
  654. this.ctx.restore();
  655. if (transparency) {
  656. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
  657. this.compositeCtx = this.ctx;
  658. this.transparentCanvas = transparentCanvas.canvas;
  659. this.ctx = transparentCanvas.context;
  660. this.ctx.save();
  661. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  662. }
  663. this.ctx.save();
  664. resetCtxToDefault(this.ctx);
  665. if (transform) {
  666. this.ctx.transform.apply(this.ctx, transform);
  667. }
  668. this.ctx.transform.apply(this.ctx, viewport.transform);
  669. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  670. this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]);
  671. if (this.imageLayer) {
  672. this.imageLayer.beginLayout();
  673. }
  674. },
  675. executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  676. const argsArray = operatorList.argsArray;
  677. const fnArray = operatorList.fnArray;
  678. let i = executionStartIdx || 0;
  679. const argsArrayLen = argsArray.length;
  680. if (argsArrayLen === i) {
  681. return i;
  682. }
  683. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  684. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  685. let steps = 0;
  686. const commonObjs = this.commonObjs;
  687. const objs = this.objs;
  688. let fnId;
  689. while (true) {
  690. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  691. stepper.breakIt(i, continueCallback);
  692. return i;
  693. }
  694. fnId = fnArray[i];
  695. if (fnId !== _util.OPS.dependency) {
  696. this[fnId].apply(this, argsArray[i]);
  697. } else {
  698. for (const depObjId of argsArray[i]) {
  699. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  700. if (!objsPool.has(depObjId)) {
  701. objsPool.get(depObjId, continueCallback);
  702. return i;
  703. }
  704. }
  705. }
  706. i++;
  707. if (i === argsArrayLen) {
  708. return i;
  709. }
  710. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  711. if (Date.now() > endTime) {
  712. continueCallback();
  713. return i;
  714. }
  715. steps = 0;
  716. }
  717. }
  718. },
  719. endDrawing: function CanvasGraphics_endDrawing() {
  720. while (this.stateStack.length || this.current.activeSMask !== null) {
  721. this.restore();
  722. }
  723. this.ctx.restore();
  724. if (this.transparentCanvas) {
  725. this.ctx = this.compositeCtx;
  726. this.ctx.save();
  727. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  728. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  729. this.ctx.restore();
  730. this.transparentCanvas = null;
  731. }
  732. this.cachedCanvases.clear();
  733. this.webGLContext.clear();
  734. if (this.imageLayer) {
  735. this.imageLayer.endLayout();
  736. }
  737. },
  738. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  739. this.current.lineWidth = width;
  740. this.ctx.lineWidth = width;
  741. },
  742. setLineCap: function CanvasGraphics_setLineCap(style) {
  743. this.ctx.lineCap = LINE_CAP_STYLES[style];
  744. },
  745. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  746. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  747. },
  748. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  749. this.ctx.miterLimit = limit;
  750. },
  751. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  752. const ctx = this.ctx;
  753. if (ctx.setLineDash !== undefined) {
  754. ctx.setLineDash(dashArray);
  755. ctx.lineDashOffset = dashPhase;
  756. }
  757. },
  758. setRenderingIntent(intent) {},
  759. setFlatness(flatness) {},
  760. setGState: function CanvasGraphics_setGState(states) {
  761. for (let i = 0, ii = states.length; i < ii; i++) {
  762. const state = states[i];
  763. const key = state[0];
  764. const value = state[1];
  765. switch (key) {
  766. case "LW":
  767. this.setLineWidth(value);
  768. break;
  769. case "LC":
  770. this.setLineCap(value);
  771. break;
  772. case "LJ":
  773. this.setLineJoin(value);
  774. break;
  775. case "ML":
  776. this.setMiterLimit(value);
  777. break;
  778. case "D":
  779. this.setDash(value[0], value[1]);
  780. break;
  781. case "RI":
  782. this.setRenderingIntent(value);
  783. break;
  784. case "FL":
  785. this.setFlatness(value);
  786. break;
  787. case "Font":
  788. this.setFont(value[0], value[1]);
  789. break;
  790. case "CA":
  791. this.current.strokeAlpha = state[1];
  792. break;
  793. case "ca":
  794. this.current.fillAlpha = state[1];
  795. this.ctx.globalAlpha = state[1];
  796. break;
  797. case "BM":
  798. this.ctx.globalCompositeOperation = value;
  799. break;
  800. case "SMask":
  801. if (this.current.activeSMask) {
  802. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  803. this.suspendSMaskGroup();
  804. } else {
  805. this.endSMaskGroup();
  806. }
  807. }
  808. this.current.activeSMask = value ? this.tempSMask : null;
  809. if (this.current.activeSMask) {
  810. this.beginSMaskGroup();
  811. }
  812. this.tempSMask = null;
  813. break;
  814. case "TR":
  815. this.current.transferMaps = value;
  816. }
  817. }
  818. },
  819. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  820. const activeSMask = this.current.activeSMask;
  821. const drawnWidth = activeSMask.canvas.width;
  822. const drawnHeight = activeSMask.canvas.height;
  823. const cacheId = "smaskGroupAt" + this.groupLevel;
  824. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  825. const currentCtx = this.ctx;
  826. const currentTransform = currentCtx.mozCurrentTransform;
  827. this.ctx.save();
  828. const groupCtx = scratchCanvas.context;
  829. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  830. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  831. groupCtx.transform.apply(groupCtx, currentTransform);
  832. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  833. copyCtxState(currentCtx, groupCtx);
  834. this.ctx = groupCtx;
  835. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  836. this.groupStack.push(currentCtx);
  837. this.groupLevel++;
  838. },
  839. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  840. const groupCtx = this.ctx;
  841. this.groupLevel--;
  842. this.ctx = this.groupStack.pop();
  843. composeSMask(this.ctx, this.current.activeSMask, groupCtx, this.webGLContext);
  844. this.ctx.restore();
  845. this.ctx.save();
  846. copyCtxState(groupCtx, this.ctx);
  847. this.current.resumeSMaskCtx = groupCtx;
  848. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  849. this.ctx.transform.apply(this.ctx, deltaTransform);
  850. groupCtx.save();
  851. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  852. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  853. groupCtx.restore();
  854. },
  855. resumeSMaskGroup: function CanvasGraphics_resumeSMaskGroup() {
  856. const groupCtx = this.current.resumeSMaskCtx;
  857. const currentCtx = this.ctx;
  858. this.ctx = groupCtx;
  859. this.groupStack.push(currentCtx);
  860. this.groupLevel++;
  861. },
  862. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  863. const groupCtx = this.ctx;
  864. this.groupLevel--;
  865. this.ctx = this.groupStack.pop();
  866. composeSMask(this.ctx, this.current.activeSMask, groupCtx, this.webGLContext);
  867. this.ctx.restore();
  868. copyCtxState(groupCtx, this.ctx);
  869. const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  870. this.ctx.transform.apply(this.ctx, deltaTransform);
  871. },
  872. save: function CanvasGraphics_save() {
  873. this.ctx.save();
  874. const old = this.current;
  875. this.stateStack.push(old);
  876. this.current = old.clone();
  877. this.current.resumeSMaskCtx = null;
  878. },
  879. restore: function CanvasGraphics_restore() {
  880. if (this.current.resumeSMaskCtx) {
  881. this.resumeSMaskGroup();
  882. }
  883. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  884. this.endSMaskGroup();
  885. }
  886. if (this.stateStack.length !== 0) {
  887. this.current = this.stateStack.pop();
  888. this.ctx.restore();
  889. this.pendingClip = null;
  890. this._cachedGetSinglePixelWidth = null;
  891. } else {
  892. this.current.activeSMask = null;
  893. }
  894. },
  895. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  896. this.ctx.transform(a, b, c, d, e, f);
  897. this._cachedGetSinglePixelWidth = null;
  898. },
  899. constructPath: function CanvasGraphics_constructPath(ops, args) {
  900. const ctx = this.ctx;
  901. const current = this.current;
  902. let x = current.x,
  903. y = current.y;
  904. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  905. switch (ops[i] | 0) {
  906. case _util.OPS.rectangle:
  907. x = args[j++];
  908. y = args[j++];
  909. const width = args[j++];
  910. const height = args[j++];
  911. const xw = x + width;
  912. const yh = y + height;
  913. ctx.moveTo(x, y);
  914. if (width === 0 || height === 0) {
  915. ctx.lineTo(xw, yh);
  916. } else {
  917. ctx.lineTo(xw, y);
  918. ctx.lineTo(xw, yh);
  919. ctx.lineTo(x, yh);
  920. }
  921. ctx.closePath();
  922. break;
  923. case _util.OPS.moveTo:
  924. x = args[j++];
  925. y = args[j++];
  926. ctx.moveTo(x, y);
  927. break;
  928. case _util.OPS.lineTo:
  929. x = args[j++];
  930. y = args[j++];
  931. ctx.lineTo(x, y);
  932. break;
  933. case _util.OPS.curveTo:
  934. x = args[j + 4];
  935. y = args[j + 5];
  936. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  937. j += 6;
  938. break;
  939. case _util.OPS.curveTo2:
  940. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  941. x = args[j + 2];
  942. y = args[j + 3];
  943. j += 4;
  944. break;
  945. case _util.OPS.curveTo3:
  946. x = args[j + 2];
  947. y = args[j + 3];
  948. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  949. j += 4;
  950. break;
  951. case _util.OPS.closePath:
  952. ctx.closePath();
  953. break;
  954. }
  955. }
  956. current.setCurrentPoint(x, y);
  957. },
  958. closePath: function CanvasGraphics_closePath() {
  959. this.ctx.closePath();
  960. },
  961. stroke: function CanvasGraphics_stroke(consumePath) {
  962. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  963. const ctx = this.ctx;
  964. const strokeColor = this.current.strokeColor;
  965. ctx.globalAlpha = this.current.strokeAlpha;
  966. if (this.contentVisible) {
  967. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  968. ctx.save();
  969. const transform = ctx.mozCurrentTransform;
  970. const scale = _util.Util.singularValueDecompose2dScale(transform)[0];
  971. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  972. const lineWidth = this.getSinglePixelWidth();
  973. const scaledLineWidth = this.current.lineWidth * scale;
  974. if (lineWidth < 0 && -lineWidth >= scaledLineWidth) {
  975. ctx.resetTransform();
  976. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  977. } else {
  978. ctx.lineWidth = Math.max(lineWidth, scaledLineWidth);
  979. }
  980. ctx.stroke();
  981. ctx.restore();
  982. } else {
  983. const lineWidth = this.getSinglePixelWidth();
  984. if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) {
  985. ctx.save();
  986. ctx.resetTransform();
  987. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  988. ctx.stroke();
  989. ctx.restore();
  990. } else {
  991. ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
  992. ctx.stroke();
  993. }
  994. }
  995. }
  996. if (consumePath) {
  997. this.consumePath();
  998. }
  999. ctx.globalAlpha = this.current.fillAlpha;
  1000. },
  1001. closeStroke: function CanvasGraphics_closeStroke() {
  1002. this.closePath();
  1003. this.stroke();
  1004. },
  1005. fill: function CanvasGraphics_fill(consumePath) {
  1006. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  1007. const ctx = this.ctx;
  1008. const fillColor = this.current.fillColor;
  1009. const isPatternFill = this.current.patternFill;
  1010. let needRestore = false;
  1011. if (isPatternFill) {
  1012. ctx.save();
  1013. if (this.baseTransform) {
  1014. ctx.setTransform.apply(ctx, this.baseTransform);
  1015. }
  1016. ctx.fillStyle = fillColor.getPattern(ctx, this);
  1017. needRestore = true;
  1018. }
  1019. if (this.contentVisible) {
  1020. if (this.pendingEOFill) {
  1021. ctx.fill("evenodd");
  1022. this.pendingEOFill = false;
  1023. } else {
  1024. ctx.fill();
  1025. }
  1026. }
  1027. if (needRestore) {
  1028. ctx.restore();
  1029. }
  1030. if (consumePath) {
  1031. this.consumePath();
  1032. }
  1033. },
  1034. eoFill: function CanvasGraphics_eoFill() {
  1035. this.pendingEOFill = true;
  1036. this.fill();
  1037. },
  1038. fillStroke: function CanvasGraphics_fillStroke() {
  1039. this.fill(false);
  1040. this.stroke(false);
  1041. this.consumePath();
  1042. },
  1043. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  1044. this.pendingEOFill = true;
  1045. this.fillStroke();
  1046. },
  1047. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  1048. this.closePath();
  1049. this.fillStroke();
  1050. },
  1051. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  1052. this.pendingEOFill = true;
  1053. this.closePath();
  1054. this.fillStroke();
  1055. },
  1056. endPath: function CanvasGraphics_endPath() {
  1057. this.consumePath();
  1058. },
  1059. clip: function CanvasGraphics_clip() {
  1060. this.pendingClip = NORMAL_CLIP;
  1061. },
  1062. eoClip: function CanvasGraphics_eoClip() {
  1063. this.pendingClip = EO_CLIP;
  1064. },
  1065. beginText: function CanvasGraphics_beginText() {
  1066. this.current.textMatrix = _util.IDENTITY_MATRIX;
  1067. this.current.textMatrixScale = 1;
  1068. this.current.x = this.current.lineX = 0;
  1069. this.current.y = this.current.lineY = 0;
  1070. },
  1071. endText: function CanvasGraphics_endText() {
  1072. const paths = this.pendingTextPaths;
  1073. const ctx = this.ctx;
  1074. if (paths === undefined) {
  1075. ctx.beginPath();
  1076. return;
  1077. }
  1078. ctx.save();
  1079. ctx.beginPath();
  1080. for (let i = 0; i < paths.length; i++) {
  1081. const path = paths[i];
  1082. ctx.setTransform.apply(ctx, path.transform);
  1083. ctx.translate(path.x, path.y);
  1084. path.addToPath(ctx, path.fontSize);
  1085. }
  1086. ctx.restore();
  1087. ctx.clip();
  1088. ctx.beginPath();
  1089. delete this.pendingTextPaths;
  1090. },
  1091. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  1092. this.current.charSpacing = spacing;
  1093. },
  1094. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  1095. this.current.wordSpacing = spacing;
  1096. },
  1097. setHScale: function CanvasGraphics_setHScale(scale) {
  1098. this.current.textHScale = scale / 100;
  1099. },
  1100. setLeading: function CanvasGraphics_setLeading(leading) {
  1101. this.current.leading = -leading;
  1102. },
  1103. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  1104. const fontObj = this.commonObjs.get(fontRefName);
  1105. const current = this.current;
  1106. if (!fontObj) {
  1107. throw new Error(`Can't find font for ${fontRefName}`);
  1108. }
  1109. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1110. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  1111. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  1112. }
  1113. if (size < 0) {
  1114. size = -size;
  1115. current.fontDirection = -1;
  1116. } else {
  1117. current.fontDirection = 1;
  1118. }
  1119. this.current.font = fontObj;
  1120. this.current.fontSize = size;
  1121. if (fontObj.isType3Font) {
  1122. return;
  1123. }
  1124. const name = fontObj.loadedName || "sans-serif";
  1125. let bold = "normal";
  1126. if (fontObj.black) {
  1127. bold = "900";
  1128. } else if (fontObj.bold) {
  1129. bold = "bold";
  1130. }
  1131. const italic = fontObj.italic ? "italic" : "normal";
  1132. const typeface = `"${name}", ${fontObj.fallbackName}`;
  1133. let browserFontSize = size;
  1134. if (size < MIN_FONT_SIZE) {
  1135. browserFontSize = MIN_FONT_SIZE;
  1136. } else if (size > MAX_FONT_SIZE) {
  1137. browserFontSize = MAX_FONT_SIZE;
  1138. }
  1139. this.current.fontSizeScale = size / browserFontSize;
  1140. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  1141. },
  1142. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  1143. this.current.textRenderingMode = mode;
  1144. },
  1145. setTextRise: function CanvasGraphics_setTextRise(rise) {
  1146. this.current.textRise = rise;
  1147. },
  1148. moveText: function CanvasGraphics_moveText(x, y) {
  1149. this.current.x = this.current.lineX += x;
  1150. this.current.y = this.current.lineY += y;
  1151. },
  1152. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  1153. this.setLeading(-y);
  1154. this.moveText(x, y);
  1155. },
  1156. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  1157. this.current.textMatrix = [a, b, c, d, e, f];
  1158. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  1159. this.current.x = this.current.lineX = 0;
  1160. this.current.y = this.current.lineY = 0;
  1161. },
  1162. nextLine: function CanvasGraphics_nextLine() {
  1163. this.moveText(0, this.current.leading);
  1164. },
  1165. paintChar(character, x, y, patternTransform, resetLineWidthToOne) {
  1166. const ctx = this.ctx;
  1167. const current = this.current;
  1168. const font = current.font;
  1169. const textRenderingMode = current.textRenderingMode;
  1170. const fontSize = current.fontSize / current.fontSizeScale;
  1171. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1172. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  1173. const patternFill = current.patternFill && !font.missingFile;
  1174. let addToPath;
  1175. if (font.disableFontFace || isAddToPathSet || patternFill) {
  1176. addToPath = font.getPathGenerator(this.commonObjs, character);
  1177. }
  1178. if (font.disableFontFace || patternFill) {
  1179. ctx.save();
  1180. ctx.translate(x, y);
  1181. ctx.beginPath();
  1182. addToPath(ctx, fontSize);
  1183. if (patternTransform) {
  1184. ctx.setTransform.apply(ctx, patternTransform);
  1185. }
  1186. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1187. ctx.fill();
  1188. }
  1189. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1190. if (resetLineWidthToOne) {
  1191. ctx.resetTransform();
  1192. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  1193. }
  1194. ctx.stroke();
  1195. }
  1196. ctx.restore();
  1197. } else {
  1198. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1199. ctx.fillText(character, x, y);
  1200. }
  1201. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1202. if (resetLineWidthToOne) {
  1203. ctx.save();
  1204. ctx.moveTo(x, y);
  1205. ctx.resetTransform();
  1206. ctx.lineWidth = Math.round(this._combinedScaleFactor);
  1207. ctx.strokeText(character, 0, 0);
  1208. ctx.restore();
  1209. } else {
  1210. ctx.strokeText(character, x, y);
  1211. }
  1212. }
  1213. }
  1214. if (isAddToPathSet) {
  1215. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  1216. paths.push({
  1217. transform: ctx.mozCurrentTransform,
  1218. x,
  1219. y,
  1220. fontSize,
  1221. addToPath
  1222. });
  1223. }
  1224. },
  1225. get isFontSubpixelAAEnabled() {
  1226. const {
  1227. context: ctx
  1228. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  1229. ctx.scale(1.5, 1);
  1230. ctx.fillText("I", 0, 10);
  1231. const data = ctx.getImageData(0, 0, 10, 10).data;
  1232. let enabled = false;
  1233. for (let i = 3; i < data.length; i += 4) {
  1234. if (data[i] > 0 && data[i] < 255) {
  1235. enabled = true;
  1236. break;
  1237. }
  1238. }
  1239. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  1240. },
  1241. showText: function CanvasGraphics_showText(glyphs) {
  1242. const current = this.current;
  1243. const font = current.font;
  1244. if (font.isType3Font) {
  1245. return this.showType3Text(glyphs);
  1246. }
  1247. const fontSize = current.fontSize;
  1248. if (fontSize === 0) {
  1249. return undefined;
  1250. }
  1251. const ctx = this.ctx;
  1252. const fontSizeScale = current.fontSizeScale;
  1253. const charSpacing = current.charSpacing;
  1254. const wordSpacing = current.wordSpacing;
  1255. const fontDirection = current.fontDirection;
  1256. const textHScale = current.textHScale * fontDirection;
  1257. const glyphsLength = glyphs.length;
  1258. const vertical = font.vertical;
  1259. const spacingDir = vertical ? 1 : -1;
  1260. const defaultVMetrics = font.defaultVMetrics;
  1261. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  1262. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  1263. ctx.save();
  1264. let patternTransform;
  1265. if (current.patternFill) {
  1266. ctx.save();
  1267. const pattern = current.fillColor.getPattern(ctx, this);
  1268. patternTransform = ctx.mozCurrentTransform;
  1269. ctx.restore();
  1270. ctx.fillStyle = pattern;
  1271. }
  1272. ctx.transform.apply(ctx, current.textMatrix);
  1273. ctx.translate(current.x, current.y + current.textRise);
  1274. if (fontDirection > 0) {
  1275. ctx.scale(textHScale, -1);
  1276. } else {
  1277. ctx.scale(textHScale, 1);
  1278. }
  1279. let lineWidth = current.lineWidth;
  1280. let resetLineWidthToOne = false;
  1281. const scale = current.textMatrixScale;
  1282. if (scale === 0 || lineWidth === 0) {
  1283. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1284. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1285. this._cachedGetSinglePixelWidth = null;
  1286. lineWidth = this.getSinglePixelWidth();
  1287. resetLineWidthToOne = lineWidth < 0;
  1288. }
  1289. } else {
  1290. lineWidth /= scale;
  1291. }
  1292. if (fontSizeScale !== 1.0) {
  1293. ctx.scale(fontSizeScale, fontSizeScale);
  1294. lineWidth /= fontSizeScale;
  1295. }
  1296. ctx.lineWidth = lineWidth;
  1297. let x = 0,
  1298. i;
  1299. for (i = 0; i < glyphsLength; ++i) {
  1300. const glyph = glyphs[i];
  1301. if ((0, _util.isNum)(glyph)) {
  1302. x += spacingDir * glyph * fontSize / 1000;
  1303. continue;
  1304. }
  1305. let restoreNeeded = false;
  1306. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1307. const character = glyph.fontChar;
  1308. const accent = glyph.accent;
  1309. let scaledX, scaledY;
  1310. let width = glyph.width;
  1311. if (vertical) {
  1312. const vmetric = glyph.vmetric || defaultVMetrics;
  1313. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  1314. const vy = vmetric[2] * widthAdvanceScale;
  1315. width = vmetric ? -vmetric[0] : width;
  1316. scaledX = vx / fontSizeScale;
  1317. scaledY = (x + vy) / fontSizeScale;
  1318. } else {
  1319. scaledX = x / fontSizeScale;
  1320. scaledY = 0;
  1321. }
  1322. if (font.remeasure && width > 0) {
  1323. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  1324. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  1325. const characterScaleX = width / measuredWidth;
  1326. restoreNeeded = true;
  1327. ctx.save();
  1328. ctx.scale(characterScaleX, 1);
  1329. scaledX /= characterScaleX;
  1330. } else if (width !== measuredWidth) {
  1331. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  1332. }
  1333. }
  1334. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  1335. if (simpleFillText && !accent) {
  1336. ctx.fillText(character, scaledX, scaledY);
  1337. } else {
  1338. this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne);
  1339. if (accent) {
  1340. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  1341. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  1342. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne);
  1343. }
  1344. }
  1345. }
  1346. let charWidth;
  1347. if (vertical) {
  1348. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  1349. } else {
  1350. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  1351. }
  1352. x += charWidth;
  1353. if (restoreNeeded) {
  1354. ctx.restore();
  1355. }
  1356. }
  1357. if (vertical) {
  1358. current.y -= x;
  1359. } else {
  1360. current.x += x * textHScale;
  1361. }
  1362. ctx.restore();
  1363. },
  1364. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  1365. const ctx = this.ctx;
  1366. const current = this.current;
  1367. const font = current.font;
  1368. const fontSize = current.fontSize;
  1369. const fontDirection = current.fontDirection;
  1370. const spacingDir = font.vertical ? 1 : -1;
  1371. const charSpacing = current.charSpacing;
  1372. const wordSpacing = current.wordSpacing;
  1373. const textHScale = current.textHScale * fontDirection;
  1374. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1375. const glyphsLength = glyphs.length;
  1376. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  1377. let i, glyph, width, spacingLength;
  1378. if (isTextInvisible || fontSize === 0) {
  1379. return;
  1380. }
  1381. this._cachedGetSinglePixelWidth = null;
  1382. ctx.save();
  1383. ctx.transform.apply(ctx, current.textMatrix);
  1384. ctx.translate(current.x, current.y);
  1385. ctx.scale(textHScale, fontDirection);
  1386. for (i = 0; i < glyphsLength; ++i) {
  1387. glyph = glyphs[i];
  1388. if ((0, _util.isNum)(glyph)) {
  1389. spacingLength = spacingDir * glyph * fontSize / 1000;
  1390. this.ctx.translate(spacingLength, 0);
  1391. current.x += spacingLength * textHScale;
  1392. continue;
  1393. }
  1394. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1395. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  1396. if (!operatorList) {
  1397. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  1398. continue;
  1399. }
  1400. if (this.contentVisible) {
  1401. this.processingType3 = glyph;
  1402. this.save();
  1403. ctx.scale(fontSize, fontSize);
  1404. ctx.transform.apply(ctx, fontMatrix);
  1405. this.executeOperatorList(operatorList);
  1406. this.restore();
  1407. }
  1408. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  1409. width = transformed[0] * fontSize + spacing;
  1410. ctx.translate(width, 0);
  1411. current.x += width * textHScale;
  1412. }
  1413. ctx.restore();
  1414. this.processingType3 = null;
  1415. },
  1416. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {},
  1417. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  1418. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  1419. this.clip();
  1420. this.endPath();
  1421. },
  1422. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  1423. let pattern;
  1424. if (IR[0] === "TilingPattern") {
  1425. const color = IR[1];
  1426. const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  1427. const canvasGraphicsFactory = {
  1428. createCanvasGraphics: ctx => {
  1429. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.webGLContext);
  1430. }
  1431. };
  1432. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  1433. } else {
  1434. pattern = (0, _pattern_helper.getShadingPatternFromIR)(IR);
  1435. }
  1436. return pattern;
  1437. },
  1438. setStrokeColorN: function CanvasGraphics_setStrokeColorN() {
  1439. this.current.strokeColor = this.getColorN_Pattern(arguments);
  1440. },
  1441. setFillColorN: function CanvasGraphics_setFillColorN() {
  1442. this.current.fillColor = this.getColorN_Pattern(arguments);
  1443. this.current.patternFill = true;
  1444. },
  1445. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  1446. const color = _util.Util.makeHexColor(r, g, b);
  1447. this.ctx.strokeStyle = color;
  1448. this.current.strokeColor = color;
  1449. },
  1450. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  1451. const color = _util.Util.makeHexColor(r, g, b);
  1452. this.ctx.fillStyle = color;
  1453. this.current.fillColor = color;
  1454. this.current.patternFill = false;
  1455. },
  1456. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  1457. if (!this.contentVisible) {
  1458. return;
  1459. }
  1460. const ctx = this.ctx;
  1461. this.save();
  1462. const pattern = (0, _pattern_helper.getShadingPatternFromIR)(patternIR);
  1463. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  1464. const inv = ctx.mozCurrentTransformInverse;
  1465. if (inv) {
  1466. const canvas = ctx.canvas;
  1467. const width = canvas.width;
  1468. const height = canvas.height;
  1469. const bl = _util.Util.applyTransform([0, 0], inv);
  1470. const br = _util.Util.applyTransform([0, height], inv);
  1471. const ul = _util.Util.applyTransform([width, 0], inv);
  1472. const ur = _util.Util.applyTransform([width, height], inv);
  1473. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  1474. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  1475. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  1476. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  1477. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  1478. } else {
  1479. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  1480. }
  1481. this.restore();
  1482. },
  1483. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  1484. (0, _util.unreachable)("Should not call beginInlineImage");
  1485. },
  1486. beginImageData: function CanvasGraphics_beginImageData() {
  1487. (0, _util.unreachable)("Should not call beginImageData");
  1488. },
  1489. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
  1490. if (!this.contentVisible) {
  1491. return;
  1492. }
  1493. this.save();
  1494. this.baseTransformStack.push(this.baseTransform);
  1495. if (Array.isArray(matrix) && matrix.length === 6) {
  1496. this.transform.apply(this, matrix);
  1497. }
  1498. this.baseTransform = this.ctx.mozCurrentTransform;
  1499. if (bbox) {
  1500. const width = bbox[2] - bbox[0];
  1501. const height = bbox[3] - bbox[1];
  1502. this.ctx.rect(bbox[0], bbox[1], width, height);
  1503. this.clip();
  1504. this.endPath();
  1505. }
  1506. },
  1507. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  1508. if (!this.contentVisible) {
  1509. return;
  1510. }
  1511. this.restore();
  1512. this.baseTransform = this.baseTransformStack.pop();
  1513. },
  1514. beginGroup: function CanvasGraphics_beginGroup(group) {
  1515. if (!this.contentVisible) {
  1516. return;
  1517. }
  1518. this.save();
  1519. const currentCtx = this.ctx;
  1520. if (!group.isolated) {
  1521. (0, _util.info)("TODO: Support non-isolated groups.");
  1522. }
  1523. if (group.knockout) {
  1524. (0, _util.warn)("Knockout groups not supported.");
  1525. }
  1526. const currentTransform = currentCtx.mozCurrentTransform;
  1527. if (group.matrix) {
  1528. currentCtx.transform.apply(currentCtx, group.matrix);
  1529. }
  1530. if (!group.bbox) {
  1531. throw new Error("Bounding box is required.");
  1532. }
  1533. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  1534. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  1535. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  1536. const offsetX = Math.floor(bounds[0]);
  1537. const offsetY = Math.floor(bounds[1]);
  1538. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  1539. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  1540. let scaleX = 1,
  1541. scaleY = 1;
  1542. if (drawnWidth > MAX_GROUP_SIZE) {
  1543. scaleX = drawnWidth / MAX_GROUP_SIZE;
  1544. drawnWidth = MAX_GROUP_SIZE;
  1545. }
  1546. if (drawnHeight > MAX_GROUP_SIZE) {
  1547. scaleY = drawnHeight / MAX_GROUP_SIZE;
  1548. drawnHeight = MAX_GROUP_SIZE;
  1549. }
  1550. let cacheId = "groupAt" + this.groupLevel;
  1551. if (group.smask) {
  1552. cacheId += "_smask_" + this.smaskCounter++ % 2;
  1553. }
  1554. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  1555. const groupCtx = scratchCanvas.context;
  1556. groupCtx.scale(1 / scaleX, 1 / scaleY);
  1557. groupCtx.translate(-offsetX, -offsetY);
  1558. groupCtx.transform.apply(groupCtx, currentTransform);
  1559. if (group.smask) {
  1560. this.smaskStack.push({
  1561. canvas: scratchCanvas.canvas,
  1562. context: groupCtx,
  1563. offsetX,
  1564. offsetY,
  1565. scaleX,
  1566. scaleY,
  1567. subtype: group.smask.subtype,
  1568. backdrop: group.smask.backdrop,
  1569. transferMap: group.smask.transferMap || null,
  1570. startTransformInverse: null
  1571. });
  1572. } else {
  1573. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  1574. currentCtx.translate(offsetX, offsetY);
  1575. currentCtx.scale(scaleX, scaleY);
  1576. }
  1577. copyCtxState(currentCtx, groupCtx);
  1578. this.ctx = groupCtx;
  1579. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  1580. this.groupStack.push(currentCtx);
  1581. this.groupLevel++;
  1582. this.current.activeSMask = null;
  1583. },
  1584. endGroup: function CanvasGraphics_endGroup(group) {
  1585. if (!this.contentVisible) {
  1586. return;
  1587. }
  1588. this.groupLevel--;
  1589. const groupCtx = this.ctx;
  1590. this.ctx = this.groupStack.pop();
  1591. if (this.ctx.imageSmoothingEnabled !== undefined) {
  1592. this.ctx.imageSmoothingEnabled = false;
  1593. } else {
  1594. this.ctx.mozImageSmoothingEnabled = false;
  1595. }
  1596. if (group.smask) {
  1597. this.tempSMask = this.smaskStack.pop();
  1598. } else {
  1599. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  1600. }
  1601. this.restore();
  1602. },
  1603. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  1604. this.save();
  1605. if (this.baseTransform) {
  1606. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  1607. }
  1608. },
  1609. endAnnotations: function CanvasGraphics_endAnnotations() {
  1610. this.restore();
  1611. },
  1612. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
  1613. this.save();
  1614. resetCtxToDefault(this.ctx);
  1615. this.current = new CanvasExtraState();
  1616. if (Array.isArray(rect) && rect.length === 4) {
  1617. const width = rect[2] - rect[0];
  1618. const height = rect[3] - rect[1];
  1619. this.ctx.rect(rect[0], rect[1], width, height);
  1620. this.clip();
  1621. this.endPath();
  1622. }
  1623. this.transform.apply(this, transform);
  1624. this.transform.apply(this, matrix);
  1625. },
  1626. endAnnotation: function CanvasGraphics_endAnnotation() {
  1627. this.restore();
  1628. },
  1629. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  1630. if (!this.contentVisible) {
  1631. return;
  1632. }
  1633. const ctx = this.ctx;
  1634. const width = img.width,
  1635. height = img.height;
  1636. const fillColor = this.current.fillColor;
  1637. const isPatternFill = this.current.patternFill;
  1638. const glyph = this.processingType3;
  1639. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  1640. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  1641. glyph.compiled = compileType3Glyph({
  1642. data: img.data,
  1643. width,
  1644. height
  1645. });
  1646. } else {
  1647. glyph.compiled = null;
  1648. }
  1649. }
  1650. if (glyph?.compiled) {
  1651. glyph.compiled(ctx);
  1652. return;
  1653. }
  1654. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  1655. const maskCtx = maskCanvas.context;
  1656. maskCtx.save();
  1657. putBinaryImageMask(maskCtx, img);
  1658. maskCtx.globalCompositeOperation = "source-in";
  1659. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  1660. maskCtx.fillRect(0, 0, width, height);
  1661. maskCtx.restore();
  1662. this.paintInlineImageXObject(maskCanvas.canvas);
  1663. },
  1664. paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  1665. if (!this.contentVisible) {
  1666. return;
  1667. }
  1668. const width = imgData.width;
  1669. const height = imgData.height;
  1670. const fillColor = this.current.fillColor;
  1671. const isPatternFill = this.current.patternFill;
  1672. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  1673. const maskCtx = maskCanvas.context;
  1674. maskCtx.save();
  1675. putBinaryImageMask(maskCtx, imgData);
  1676. maskCtx.globalCompositeOperation = "source-in";
  1677. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  1678. maskCtx.fillRect(0, 0, width, height);
  1679. maskCtx.restore();
  1680. const ctx = this.ctx;
  1681. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  1682. ctx.save();
  1683. ctx.transform(scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]);
  1684. ctx.scale(1, -1);
  1685. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  1686. ctx.restore();
  1687. }
  1688. },
  1689. paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  1690. if (!this.contentVisible) {
  1691. return;
  1692. }
  1693. const ctx = this.ctx;
  1694. const fillColor = this.current.fillColor;
  1695. const isPatternFill = this.current.patternFill;
  1696. for (let i = 0, ii = images.length; i < ii; i++) {
  1697. const image = images[i];
  1698. const width = image.width,
  1699. height = image.height;
  1700. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  1701. const maskCtx = maskCanvas.context;
  1702. maskCtx.save();
  1703. putBinaryImageMask(maskCtx, image);
  1704. maskCtx.globalCompositeOperation = "source-in";
  1705. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  1706. maskCtx.fillRect(0, 0, width, height);
  1707. maskCtx.restore();
  1708. ctx.save();
  1709. ctx.transform.apply(ctx, image.transform);
  1710. ctx.scale(1, -1);
  1711. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  1712. ctx.restore();
  1713. }
  1714. },
  1715. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  1716. if (!this.contentVisible) {
  1717. return;
  1718. }
  1719. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  1720. if (!imgData) {
  1721. (0, _util.warn)("Dependent image isn't ready yet");
  1722. return;
  1723. }
  1724. this.paintInlineImageXObject(imgData);
  1725. },
  1726. paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  1727. if (!this.contentVisible) {
  1728. return;
  1729. }
  1730. const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
  1731. if (!imgData) {
  1732. (0, _util.warn)("Dependent image isn't ready yet");
  1733. return;
  1734. }
  1735. const width = imgData.width;
  1736. const height = imgData.height;
  1737. const map = [];
  1738. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  1739. map.push({
  1740. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  1741. x: 0,
  1742. y: 0,
  1743. w: width,
  1744. h: height
  1745. });
  1746. }
  1747. this.paintInlineImageXObjectGroup(imgData, map);
  1748. },
  1749. paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
  1750. if (!this.contentVisible) {
  1751. return;
  1752. }
  1753. const width = imgData.width;
  1754. const height = imgData.height;
  1755. const ctx = this.ctx;
  1756. this.save();
  1757. ctx.scale(1 / width, -1 / height);
  1758. const currentTransform = ctx.mozCurrentTransformInverse;
  1759. const a = currentTransform[0],
  1760. b = currentTransform[1];
  1761. let widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  1762. const c = currentTransform[2],
  1763. d = currentTransform[3];
  1764. let heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  1765. let imgToPaint, tmpCanvas, tmpCtx;
  1766. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  1767. imgToPaint = imgData;
  1768. } else {
  1769. tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  1770. tmpCtx = tmpCanvas.context;
  1771. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  1772. imgToPaint = tmpCanvas.canvas;
  1773. }
  1774. let paintWidth = width,
  1775. paintHeight = height;
  1776. let tmpCanvasId = "prescale1";
  1777. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  1778. let newWidth = paintWidth,
  1779. newHeight = paintHeight;
  1780. if (widthScale > 2 && paintWidth > 1) {
  1781. newWidth = Math.ceil(paintWidth / 2);
  1782. widthScale /= paintWidth / newWidth;
  1783. }
  1784. if (heightScale > 2 && paintHeight > 1) {
  1785. newHeight = Math.ceil(paintHeight / 2);
  1786. heightScale /= paintHeight / newHeight;
  1787. }
  1788. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  1789. tmpCtx = tmpCanvas.context;
  1790. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  1791. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  1792. imgToPaint = tmpCanvas.canvas;
  1793. paintWidth = newWidth;
  1794. paintHeight = newHeight;
  1795. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  1796. }
  1797. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  1798. if (this.imageLayer) {
  1799. const position = this.getCanvasPosition(0, -height);
  1800. this.imageLayer.appendImage({
  1801. imgData,
  1802. left: position[0],
  1803. top: position[1],
  1804. width: width / currentTransform[0],
  1805. height: height / currentTransform[3]
  1806. });
  1807. }
  1808. this.restore();
  1809. },
  1810. paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  1811. if (!this.contentVisible) {
  1812. return;
  1813. }
  1814. const ctx = this.ctx;
  1815. const w = imgData.width;
  1816. const h = imgData.height;
  1817. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  1818. const tmpCtx = tmpCanvas.context;
  1819. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  1820. for (let i = 0, ii = map.length; i < ii; i++) {
  1821. const entry = map[i];
  1822. ctx.save();
  1823. ctx.transform.apply(ctx, entry.transform);
  1824. ctx.scale(1, -1);
  1825. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  1826. if (this.imageLayer) {
  1827. const position = this.getCanvasPosition(entry.x, entry.y);
  1828. this.imageLayer.appendImage({
  1829. imgData,
  1830. left: position[0],
  1831. top: position[1],
  1832. width: w,
  1833. height: h
  1834. });
  1835. }
  1836. ctx.restore();
  1837. }
  1838. },
  1839. paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
  1840. if (!this.contentVisible) {
  1841. return;
  1842. }
  1843. this.ctx.fillRect(0, 0, 1, 1);
  1844. },
  1845. markPoint: function CanvasGraphics_markPoint(tag) {},
  1846. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {},
  1847. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  1848. this.markedContentStack.push({
  1849. visible: true
  1850. });
  1851. },
  1852. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {
  1853. if (tag === "OC") {
  1854. this.markedContentStack.push({
  1855. visible: this.optionalContentConfig.isVisible(properties)
  1856. });
  1857. } else {
  1858. this.markedContentStack.push({
  1859. visible: true
  1860. });
  1861. }
  1862. this.contentVisible = this.isContentVisible();
  1863. },
  1864. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  1865. this.markedContentStack.pop();
  1866. this.contentVisible = this.isContentVisible();
  1867. },
  1868. beginCompat: function CanvasGraphics_beginCompat() {},
  1869. endCompat: function CanvasGraphics_endCompat() {},
  1870. consumePath: function CanvasGraphics_consumePath() {
  1871. const ctx = this.ctx;
  1872. if (this.pendingClip) {
  1873. if (this.pendingClip === EO_CLIP) {
  1874. ctx.clip("evenodd");
  1875. } else {
  1876. ctx.clip();
  1877. }
  1878. this.pendingClip = null;
  1879. }
  1880. ctx.beginPath();
  1881. },
  1882. getSinglePixelWidth() {
  1883. if (this._cachedGetSinglePixelWidth === null) {
  1884. const m = this.ctx.mozCurrentTransform;
  1885. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  1886. const sqNorm1 = m[0] ** 2 + m[2] ** 2;
  1887. const sqNorm2 = m[1] ** 2 + m[3] ** 2;
  1888. const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet;
  1889. if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) {
  1890. this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight);
  1891. } else if (absDet > Number.EPSILON) {
  1892. this._cachedGetSinglePixelWidth = pixelHeight * 1.0000001;
  1893. } else {
  1894. this._cachedGetSinglePixelWidth = 1;
  1895. }
  1896. }
  1897. return this._cachedGetSinglePixelWidth;
  1898. },
  1899. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  1900. const transform = this.ctx.mozCurrentTransform;
  1901. return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
  1902. },
  1903. isContentVisible: function CanvasGraphics_isContentVisible() {
  1904. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  1905. if (!this.markedContentStack[i].visible) {
  1906. return false;
  1907. }
  1908. }
  1909. return true;
  1910. }
  1911. };
  1912. for (const op in _util.OPS) {
  1913. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  1914. }
  1915. return CanvasGraphics;
  1916. }();
  1917. exports.CanvasGraphics = CanvasGraphics;