canvas.js 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  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.CanvasGraphics = void 0;
  27. var _util = require("../shared/util.js");
  28. var _display_utils = require("./display_utils.js");
  29. var _pattern_helper = require("./pattern_helper.js");
  30. var _image_utils = require("../shared/image_utils.js");
  31. var _is_node = require("../shared/is_node.js");
  32. const MIN_FONT_SIZE = 16;
  33. const MAX_FONT_SIZE = 100;
  34. const MAX_GROUP_SIZE = 4096;
  35. const EXECUTION_TIME = 15;
  36. const EXECUTION_STEPS = 10;
  37. const MAX_SIZE_TO_COMPILE = _is_node.isNodeJS && typeof Path2D === "undefined" ? -1 : 1000;
  38. const FULL_CHUNK_HEIGHT = 16;
  39. function mirrorContextOperations(ctx, destCtx) {
  40. if (ctx._removeMirroring) {
  41. throw new Error("Context is already forwarding operations.");
  42. }
  43. ctx.__originalSave = ctx.save;
  44. ctx.__originalRestore = ctx.restore;
  45. ctx.__originalRotate = ctx.rotate;
  46. ctx.__originalScale = ctx.scale;
  47. ctx.__originalTranslate = ctx.translate;
  48. ctx.__originalTransform = ctx.transform;
  49. ctx.__originalSetTransform = ctx.setTransform;
  50. ctx.__originalResetTransform = ctx.resetTransform;
  51. ctx.__originalClip = ctx.clip;
  52. ctx.__originalMoveTo = ctx.moveTo;
  53. ctx.__originalLineTo = ctx.lineTo;
  54. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  55. ctx.__originalRect = ctx.rect;
  56. ctx.__originalClosePath = ctx.closePath;
  57. ctx.__originalBeginPath = ctx.beginPath;
  58. ctx._removeMirroring = () => {
  59. ctx.save = ctx.__originalSave;
  60. ctx.restore = ctx.__originalRestore;
  61. ctx.rotate = ctx.__originalRotate;
  62. ctx.scale = ctx.__originalScale;
  63. ctx.translate = ctx.__originalTranslate;
  64. ctx.transform = ctx.__originalTransform;
  65. ctx.setTransform = ctx.__originalSetTransform;
  66. ctx.resetTransform = ctx.__originalResetTransform;
  67. ctx.clip = ctx.__originalClip;
  68. ctx.moveTo = ctx.__originalMoveTo;
  69. ctx.lineTo = ctx.__originalLineTo;
  70. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  71. ctx.rect = ctx.__originalRect;
  72. ctx.closePath = ctx.__originalClosePath;
  73. ctx.beginPath = ctx.__originalBeginPath;
  74. delete ctx._removeMirroring;
  75. };
  76. ctx.save = function ctxSave() {
  77. destCtx.save();
  78. this.__originalSave();
  79. };
  80. ctx.restore = function ctxRestore() {
  81. destCtx.restore();
  82. this.__originalRestore();
  83. };
  84. ctx.translate = function ctxTranslate(x, y) {
  85. destCtx.translate(x, y);
  86. this.__originalTranslate(x, y);
  87. };
  88. ctx.scale = function ctxScale(x, y) {
  89. destCtx.scale(x, y);
  90. this.__originalScale(x, y);
  91. };
  92. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  93. destCtx.transform(a, b, c, d, e, f);
  94. this.__originalTransform(a, b, c, d, e, f);
  95. };
  96. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  97. destCtx.setTransform(a, b, c, d, e, f);
  98. this.__originalSetTransform(a, b, c, d, e, f);
  99. };
  100. ctx.resetTransform = function ctxResetTransform() {
  101. destCtx.resetTransform();
  102. this.__originalResetTransform();
  103. };
  104. ctx.rotate = function ctxRotate(angle) {
  105. destCtx.rotate(angle);
  106. this.__originalRotate(angle);
  107. };
  108. ctx.clip = function ctxRotate(rule) {
  109. destCtx.clip(rule);
  110. this.__originalClip(rule);
  111. };
  112. ctx.moveTo = function (x, y) {
  113. destCtx.moveTo(x, y);
  114. this.__originalMoveTo(x, y);
  115. };
  116. ctx.lineTo = function (x, y) {
  117. destCtx.lineTo(x, y);
  118. this.__originalLineTo(x, y);
  119. };
  120. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  121. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  122. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  123. };
  124. ctx.rect = function (x, y, width, height) {
  125. destCtx.rect(x, y, width, height);
  126. this.__originalRect(x, y, width, height);
  127. };
  128. ctx.closePath = function () {
  129. destCtx.closePath();
  130. this.__originalClosePath();
  131. };
  132. ctx.beginPath = function () {
  133. destCtx.beginPath();
  134. this.__originalBeginPath();
  135. };
  136. }
  137. class CachedCanvases {
  138. constructor(canvasFactory) {
  139. this.canvasFactory = canvasFactory;
  140. this.cache = Object.create(null);
  141. }
  142. getCanvas(id, width, height) {
  143. let canvasEntry;
  144. if (this.cache[id] !== undefined) {
  145. canvasEntry = this.cache[id];
  146. this.canvasFactory.reset(canvasEntry, width, height);
  147. } else {
  148. canvasEntry = this.canvasFactory.create(width, height);
  149. this.cache[id] = canvasEntry;
  150. }
  151. return canvasEntry;
  152. }
  153. delete(id) {
  154. delete this.cache[id];
  155. }
  156. clear() {
  157. for (const id in this.cache) {
  158. const canvasEntry = this.cache[id];
  159. this.canvasFactory.destroy(canvasEntry);
  160. delete this.cache[id];
  161. }
  162. }
  163. }
  164. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  165. const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
  166. if (b === 0 && c === 0) {
  167. const tlX = destX * a + tx;
  168. const rTlX = Math.round(tlX);
  169. const tlY = destY * d + ty;
  170. const rTlY = Math.round(tlY);
  171. const brX = (destX + destW) * a + tx;
  172. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  173. const brY = (destY + destH) * d + ty;
  174. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  175. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  176. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  177. ctx.setTransform(a, b, c, d, tx, ty);
  178. return [rWidth, rHeight];
  179. }
  180. if (a === 0 && d === 0) {
  181. const tlX = destY * c + tx;
  182. const rTlX = Math.round(tlX);
  183. const tlY = destX * b + ty;
  184. const rTlY = Math.round(tlY);
  185. const brX = (destY + destH) * c + tx;
  186. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  187. const brY = (destX + destW) * b + ty;
  188. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  189. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  190. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  191. ctx.setTransform(a, b, c, d, tx, ty);
  192. return [rHeight, rWidth];
  193. }
  194. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  195. const scaleX = Math.hypot(a, b);
  196. const scaleY = Math.hypot(c, d);
  197. return [scaleX * destW, scaleY * destH];
  198. }
  199. function compileType3Glyph(imgData) {
  200. const {
  201. width,
  202. height
  203. } = imgData;
  204. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  205. return null;
  206. }
  207. const POINT_TO_PROCESS_LIMIT = 1000;
  208. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  209. const width1 = width + 1;
  210. let points = new Uint8Array(width1 * (height + 1));
  211. let i, j, j0;
  212. const lineSize = width + 7 & ~7;
  213. let data = new Uint8Array(lineSize * height),
  214. pos = 0;
  215. for (const elem of imgData.data) {
  216. let mask = 128;
  217. while (mask > 0) {
  218. data[pos++] = elem & mask ? 0 : 255;
  219. mask >>= 1;
  220. }
  221. }
  222. let count = 0;
  223. pos = 0;
  224. if (data[pos] !== 0) {
  225. points[0] = 1;
  226. ++count;
  227. }
  228. for (j = 1; j < width; j++) {
  229. if (data[pos] !== data[pos + 1]) {
  230. points[j] = data[pos] ? 2 : 1;
  231. ++count;
  232. }
  233. pos++;
  234. }
  235. if (data[pos] !== 0) {
  236. points[j] = 2;
  237. ++count;
  238. }
  239. for (i = 1; i < height; i++) {
  240. pos = i * lineSize;
  241. j0 = i * width1;
  242. if (data[pos - lineSize] !== data[pos]) {
  243. points[j0] = data[pos] ? 1 : 8;
  244. ++count;
  245. }
  246. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  247. for (j = 1; j < width; j++) {
  248. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  249. if (POINT_TYPES[sum]) {
  250. points[j0 + j] = POINT_TYPES[sum];
  251. ++count;
  252. }
  253. pos++;
  254. }
  255. if (data[pos - lineSize] !== data[pos]) {
  256. points[j0 + j] = data[pos] ? 2 : 4;
  257. ++count;
  258. }
  259. if (count > POINT_TO_PROCESS_LIMIT) {
  260. return null;
  261. }
  262. }
  263. pos = lineSize * (height - 1);
  264. j0 = i * width1;
  265. if (data[pos] !== 0) {
  266. points[j0] = 8;
  267. ++count;
  268. }
  269. for (j = 1; j < width; j++) {
  270. if (data[pos] !== data[pos + 1]) {
  271. points[j0 + j] = data[pos] ? 4 : 8;
  272. ++count;
  273. }
  274. pos++;
  275. }
  276. if (data[pos] !== 0) {
  277. points[j0 + j] = 4;
  278. ++count;
  279. }
  280. if (count > POINT_TO_PROCESS_LIMIT) {
  281. return null;
  282. }
  283. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  284. const path = new Path2D();
  285. for (i = 0; count && i <= height; i++) {
  286. let p = i * width1;
  287. const end = p + width;
  288. while (p < end && !points[p]) {
  289. p++;
  290. }
  291. if (p === end) {
  292. continue;
  293. }
  294. path.moveTo(p % width1, i);
  295. const p0 = p;
  296. let type = points[p];
  297. do {
  298. const step = steps[type];
  299. do {
  300. p += step;
  301. } while (!points[p]);
  302. const pp = points[p];
  303. if (pp !== 5 && pp !== 10) {
  304. type = pp;
  305. points[p] = 0;
  306. } else {
  307. type = pp & 0x33 * type >> 4;
  308. points[p] &= type >> 2 | type << 2;
  309. }
  310. path.lineTo(p % width1, p / width1 | 0);
  311. if (!points[p]) {
  312. --count;
  313. }
  314. } while (p0 !== p);
  315. --i;
  316. }
  317. data = null;
  318. points = null;
  319. const drawOutline = function (c) {
  320. c.save();
  321. c.scale(1 / width, -1 / height);
  322. c.translate(0, -height);
  323. c.fill(path);
  324. c.beginPath();
  325. c.restore();
  326. };
  327. return drawOutline;
  328. }
  329. class CanvasExtraState {
  330. constructor(width, height) {
  331. this.alphaIsShape = false;
  332. this.fontSize = 0;
  333. this.fontSizeScale = 1;
  334. this.textMatrix = _util.IDENTITY_MATRIX;
  335. this.textMatrixScale = 1;
  336. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  337. this.leading = 0;
  338. this.x = 0;
  339. this.y = 0;
  340. this.lineX = 0;
  341. this.lineY = 0;
  342. this.charSpacing = 0;
  343. this.wordSpacing = 0;
  344. this.textHScale = 1;
  345. this.textRenderingMode = _util.TextRenderingMode.FILL;
  346. this.textRise = 0;
  347. this.fillColor = "#000000";
  348. this.strokeColor = "#000000";
  349. this.patternFill = false;
  350. this.fillAlpha = 1;
  351. this.strokeAlpha = 1;
  352. this.lineWidth = 1;
  353. this.activeSMask = null;
  354. this.transferMaps = null;
  355. this.startNewPathAndClipBox([0, 0, width, height]);
  356. }
  357. clone() {
  358. const clone = Object.create(this);
  359. clone.clipBox = this.clipBox.slice();
  360. return clone;
  361. }
  362. setCurrentPoint(x, y) {
  363. this.x = x;
  364. this.y = y;
  365. }
  366. updatePathMinMax(transform, x, y) {
  367. [x, y] = _util.Util.applyTransform([x, y], transform);
  368. this.minX = Math.min(this.minX, x);
  369. this.minY = Math.min(this.minY, y);
  370. this.maxX = Math.max(this.maxX, x);
  371. this.maxY = Math.max(this.maxY, y);
  372. }
  373. updateRectMinMax(transform, rect) {
  374. const p1 = _util.Util.applyTransform(rect, transform);
  375. const p2 = _util.Util.applyTransform(rect.slice(2), transform);
  376. this.minX = Math.min(this.minX, p1[0], p2[0]);
  377. this.minY = Math.min(this.minY, p1[1], p2[1]);
  378. this.maxX = Math.max(this.maxX, p1[0], p2[0]);
  379. this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  380. }
  381. updateScalingPathMinMax(transform, minMax) {
  382. _util.Util.scaleMinMax(transform, minMax);
  383. this.minX = Math.min(this.minX, minMax[0]);
  384. this.maxX = Math.max(this.maxX, minMax[1]);
  385. this.minY = Math.min(this.minY, minMax[2]);
  386. this.maxY = Math.max(this.maxY, minMax[3]);
  387. }
  388. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  389. const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
  390. if (minMax) {
  391. minMax[0] = Math.min(minMax[0], box[0], box[2]);
  392. minMax[1] = Math.max(minMax[1], box[0], box[2]);
  393. minMax[2] = Math.min(minMax[2], box[1], box[3]);
  394. minMax[3] = Math.max(minMax[3], box[1], box[3]);
  395. return;
  396. }
  397. this.updateRectMinMax(transform, box);
  398. }
  399. getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  400. const box = [this.minX, this.minY, this.maxX, this.maxY];
  401. if (pathType === _pattern_helper.PathType.STROKE) {
  402. if (!transform) {
  403. (0, _util.unreachable)("Stroke bounding box must include transform.");
  404. }
  405. const scale = _util.Util.singularValueDecompose2dScale(transform);
  406. const xStrokePad = scale[0] * this.lineWidth / 2;
  407. const yStrokePad = scale[1] * this.lineWidth / 2;
  408. box[0] -= xStrokePad;
  409. box[1] -= yStrokePad;
  410. box[2] += xStrokePad;
  411. box[3] += yStrokePad;
  412. }
  413. return box;
  414. }
  415. updateClipFromPath() {
  416. const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
  417. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  418. }
  419. isEmptyClip() {
  420. return this.minX === Infinity;
  421. }
  422. startNewPathAndClipBox(box) {
  423. this.clipBox = box;
  424. this.minX = Infinity;
  425. this.minY = Infinity;
  426. this.maxX = 0;
  427. this.maxY = 0;
  428. }
  429. getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  430. return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  431. }
  432. }
  433. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  434. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  435. ctx.putImageData(imgData, 0, 0);
  436. return;
  437. }
  438. const height = imgData.height,
  439. width = imgData.width;
  440. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  441. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  442. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  443. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  444. let srcPos = 0,
  445. destPos;
  446. const src = imgData.data;
  447. const dest = chunkImgData.data;
  448. let i, j, thisChunkHeight, elemsInThisChunk;
  449. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  450. if (transferMaps) {
  451. switch (transferMaps.length) {
  452. case 1:
  453. transferMapRed = transferMaps[0];
  454. transferMapGreen = transferMaps[0];
  455. transferMapBlue = transferMaps[0];
  456. transferMapGray = transferMaps[0];
  457. break;
  458. case 4:
  459. transferMapRed = transferMaps[0];
  460. transferMapGreen = transferMaps[1];
  461. transferMapBlue = transferMaps[2];
  462. transferMapGray = transferMaps[3];
  463. break;
  464. }
  465. }
  466. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  467. const srcLength = src.byteLength;
  468. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  469. const dest32DataLength = dest32.length;
  470. const fullSrcDiff = width + 7 >> 3;
  471. let white = 0xffffffff;
  472. let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  473. if (transferMapGray) {
  474. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  475. [white, black] = [black, white];
  476. }
  477. }
  478. for (i = 0; i < totalChunks; i++) {
  479. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  480. destPos = 0;
  481. for (j = 0; j < thisChunkHeight; j++) {
  482. const srcDiff = srcLength - srcPos;
  483. let k = 0;
  484. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  485. const kEndUnrolled = kEnd & ~7;
  486. let mask = 0;
  487. let srcByte = 0;
  488. for (; k < kEndUnrolled; k += 8) {
  489. srcByte = src[srcPos++];
  490. dest32[destPos++] = srcByte & 128 ? white : black;
  491. dest32[destPos++] = srcByte & 64 ? white : black;
  492. dest32[destPos++] = srcByte & 32 ? white : black;
  493. dest32[destPos++] = srcByte & 16 ? white : black;
  494. dest32[destPos++] = srcByte & 8 ? white : black;
  495. dest32[destPos++] = srcByte & 4 ? white : black;
  496. dest32[destPos++] = srcByte & 2 ? white : black;
  497. dest32[destPos++] = srcByte & 1 ? white : black;
  498. }
  499. for (; k < kEnd; k++) {
  500. if (mask === 0) {
  501. srcByte = src[srcPos++];
  502. mask = 128;
  503. }
  504. dest32[destPos++] = srcByte & mask ? white : black;
  505. mask >>= 1;
  506. }
  507. }
  508. while (destPos < dest32DataLength) {
  509. dest32[destPos++] = 0;
  510. }
  511. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  512. }
  513. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  514. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  515. j = 0;
  516. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  517. for (i = 0; i < fullChunks; i++) {
  518. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  519. srcPos += elemsInThisChunk;
  520. if (hasTransferMaps) {
  521. for (let k = 0; k < elemsInThisChunk; k += 4) {
  522. if (transferMapRed) {
  523. dest[k + 0] = transferMapRed[dest[k + 0]];
  524. }
  525. if (transferMapGreen) {
  526. dest[k + 1] = transferMapGreen[dest[k + 1]];
  527. }
  528. if (transferMapBlue) {
  529. dest[k + 2] = transferMapBlue[dest[k + 2]];
  530. }
  531. }
  532. }
  533. ctx.putImageData(chunkImgData, 0, j);
  534. j += FULL_CHUNK_HEIGHT;
  535. }
  536. if (i < totalChunks) {
  537. elemsInThisChunk = width * partialChunkHeight * 4;
  538. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  539. if (hasTransferMaps) {
  540. for (let k = 0; k < elemsInThisChunk; k += 4) {
  541. if (transferMapRed) {
  542. dest[k + 0] = transferMapRed[dest[k + 0]];
  543. }
  544. if (transferMapGreen) {
  545. dest[k + 1] = transferMapGreen[dest[k + 1]];
  546. }
  547. if (transferMapBlue) {
  548. dest[k + 2] = transferMapBlue[dest[k + 2]];
  549. }
  550. }
  551. }
  552. ctx.putImageData(chunkImgData, 0, j);
  553. }
  554. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  555. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  556. thisChunkHeight = FULL_CHUNK_HEIGHT;
  557. elemsInThisChunk = width * thisChunkHeight;
  558. for (i = 0; i < totalChunks; i++) {
  559. if (i >= fullChunks) {
  560. thisChunkHeight = partialChunkHeight;
  561. elemsInThisChunk = width * thisChunkHeight;
  562. }
  563. destPos = 0;
  564. for (j = elemsInThisChunk; j--;) {
  565. dest[destPos++] = src[srcPos++];
  566. dest[destPos++] = src[srcPos++];
  567. dest[destPos++] = src[srcPos++];
  568. dest[destPos++] = 255;
  569. }
  570. if (hasTransferMaps) {
  571. for (let k = 0; k < destPos; k += 4) {
  572. if (transferMapRed) {
  573. dest[k + 0] = transferMapRed[dest[k + 0]];
  574. }
  575. if (transferMapGreen) {
  576. dest[k + 1] = transferMapGreen[dest[k + 1]];
  577. }
  578. if (transferMapBlue) {
  579. dest[k + 2] = transferMapBlue[dest[k + 2]];
  580. }
  581. }
  582. }
  583. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  584. }
  585. } else {
  586. throw new Error(`bad image kind: ${imgData.kind}`);
  587. }
  588. }
  589. function putBinaryImageMask(ctx, imgData) {
  590. if (imgData.bitmap) {
  591. ctx.drawImage(imgData.bitmap, 0, 0);
  592. return;
  593. }
  594. const height = imgData.height,
  595. width = imgData.width;
  596. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  597. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  598. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  599. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  600. let srcPos = 0;
  601. const src = imgData.data;
  602. const dest = chunkImgData.data;
  603. for (let i = 0; i < totalChunks; i++) {
  604. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  605. ({
  606. srcPos
  607. } = (0, _image_utils.applyMaskImageData)({
  608. src,
  609. srcPos,
  610. dest,
  611. width,
  612. height: thisChunkHeight
  613. }));
  614. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  615. }
  616. }
  617. function copyCtxState(sourceCtx, destCtx) {
  618. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  619. for (const property of properties) {
  620. if (sourceCtx[property] !== undefined) {
  621. destCtx[property] = sourceCtx[property];
  622. }
  623. }
  624. if (sourceCtx.setLineDash !== undefined) {
  625. destCtx.setLineDash(sourceCtx.getLineDash());
  626. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  627. }
  628. }
  629. function resetCtxToDefault(ctx, foregroundColor) {
  630. ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
  631. ctx.fillRule = "nonzero";
  632. ctx.globalAlpha = 1;
  633. ctx.lineWidth = 1;
  634. ctx.lineCap = "butt";
  635. ctx.lineJoin = "miter";
  636. ctx.miterLimit = 10;
  637. ctx.globalCompositeOperation = "source-over";
  638. ctx.font = "10px sans-serif";
  639. if (ctx.setLineDash !== undefined) {
  640. ctx.setLineDash([]);
  641. ctx.lineDashOffset = 0;
  642. }
  643. }
  644. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  645. const length = bytes.length;
  646. for (let i = 3; i < length; i += 4) {
  647. const alpha = bytes[i];
  648. if (alpha === 0) {
  649. bytes[i - 3] = r0;
  650. bytes[i - 2] = g0;
  651. bytes[i - 1] = b0;
  652. } else if (alpha < 255) {
  653. const alpha_ = 255 - alpha;
  654. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  655. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  656. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  657. }
  658. }
  659. }
  660. function composeSMaskAlpha(maskData, layerData, transferMap) {
  661. const length = maskData.length;
  662. const scale = 1 / 255;
  663. for (let i = 3; i < length; i += 4) {
  664. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  665. layerData[i] = layerData[i] * alpha * scale | 0;
  666. }
  667. }
  668. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  669. const length = maskData.length;
  670. for (let i = 3; i < length; i += 4) {
  671. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  672. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  673. }
  674. }
  675. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  676. const hasBackdrop = !!backdrop;
  677. const r0 = hasBackdrop ? backdrop[0] : 0;
  678. const g0 = hasBackdrop ? backdrop[1] : 0;
  679. const b0 = hasBackdrop ? backdrop[2] : 0;
  680. let composeFn;
  681. if (subtype === "Luminosity") {
  682. composeFn = composeSMaskLuminosity;
  683. } else {
  684. composeFn = composeSMaskAlpha;
  685. }
  686. const PIXELS_TO_PROCESS = 1048576;
  687. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  688. for (let row = 0; row < height; row += chunkSize) {
  689. const chunkHeight = Math.min(chunkSize, height - row);
  690. const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
  691. const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
  692. if (hasBackdrop) {
  693. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  694. }
  695. composeFn(maskData.data, layerData.data, transferMap);
  696. layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  697. }
  698. }
  699. function composeSMask(ctx, smask, layerCtx, layerBox) {
  700. const layerOffsetX = layerBox[0];
  701. const layerOffsetY = layerBox[1];
  702. const layerWidth = layerBox[2] - layerOffsetX;
  703. const layerHeight = layerBox[3] - layerOffsetY;
  704. if (layerWidth === 0 || layerHeight === 0) {
  705. return;
  706. }
  707. genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  708. ctx.save();
  709. ctx.globalAlpha = 1;
  710. ctx.globalCompositeOperation = "source-over";
  711. ctx.setTransform(1, 0, 0, 1, 0, 0);
  712. ctx.drawImage(layerCtx.canvas, 0, 0);
  713. ctx.restore();
  714. }
  715. function getImageSmoothingEnabled(transform, interpolate) {
  716. const scale = _util.Util.singularValueDecompose2dScale(transform);
  717. scale[0] = Math.fround(scale[0]);
  718. scale[1] = Math.fround(scale[1]);
  719. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  720. if (interpolate !== undefined) {
  721. return interpolate;
  722. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  723. return true;
  724. }
  725. return false;
  726. }
  727. const LINE_CAP_STYLES = ["butt", "round", "square"];
  728. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  729. const NORMAL_CLIP = {};
  730. const EO_CLIP = {};
  731. class CanvasGraphics {
  732. constructor(canvasCtx, commonObjs, objs, canvasFactory, optionalContentConfig, annotationCanvasMap, pageColors) {
  733. this.ctx = canvasCtx;
  734. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  735. this.stateStack = [];
  736. this.pendingClip = null;
  737. this.pendingEOFill = false;
  738. this.res = null;
  739. this.xobjs = null;
  740. this.commonObjs = commonObjs;
  741. this.objs = objs;
  742. this.canvasFactory = canvasFactory;
  743. this.groupStack = [];
  744. this.processingType3 = null;
  745. this.baseTransform = null;
  746. this.baseTransformStack = [];
  747. this.groupLevel = 0;
  748. this.smaskStack = [];
  749. this.smaskCounter = 0;
  750. this.tempSMask = null;
  751. this.suspendedCtx = null;
  752. this.contentVisible = true;
  753. this.markedContentStack = [];
  754. this.optionalContentConfig = optionalContentConfig;
  755. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  756. this.cachedPatterns = new Map();
  757. this.annotationCanvasMap = annotationCanvasMap;
  758. this.viewportScale = 1;
  759. this.outputScaleX = 1;
  760. this.outputScaleY = 1;
  761. this.backgroundColor = pageColors?.background || null;
  762. this.foregroundColor = pageColors?.foreground || null;
  763. this._cachedScaleForStroking = null;
  764. this._cachedGetSinglePixelWidth = null;
  765. this._cachedBitmapsMap = new Map();
  766. }
  767. getObject(data, fallback = null) {
  768. if (typeof data === "string") {
  769. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  770. }
  771. return fallback;
  772. }
  773. beginDrawing({
  774. transform,
  775. viewport,
  776. transparency = false,
  777. background = null
  778. }) {
  779. const width = this.ctx.canvas.width;
  780. const height = this.ctx.canvas.height;
  781. const defaultBackgroundColor = background || "#ffffff";
  782. this.ctx.save();
  783. if (this.foregroundColor && this.backgroundColor) {
  784. this.ctx.fillStyle = this.foregroundColor;
  785. const fg = this.foregroundColor = this.ctx.fillStyle;
  786. this.ctx.fillStyle = this.backgroundColor;
  787. const bg = this.backgroundColor = this.ctx.fillStyle;
  788. let isValidDefaultBg = true;
  789. let defaultBg = defaultBackgroundColor;
  790. this.ctx.fillStyle = defaultBackgroundColor;
  791. defaultBg = this.ctx.fillStyle;
  792. isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
  793. if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
  794. this.foregroundColor = this.backgroundColor = null;
  795. } else {
  796. const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
  797. const newComp = x => {
  798. x /= 255;
  799. return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  800. };
  801. const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
  802. this.selectColor = (r, g, b) => {
  803. const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
  804. return Math.round(lumC) === lumB ? bg : fg;
  805. };
  806. }
  807. }
  808. this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
  809. this.ctx.fillRect(0, 0, width, height);
  810. this.ctx.restore();
  811. if (transparency) {
  812. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  813. this.compositeCtx = this.ctx;
  814. this.transparentCanvas = transparentCanvas.canvas;
  815. this.ctx = transparentCanvas.context;
  816. this.ctx.save();
  817. this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
  818. }
  819. this.ctx.save();
  820. resetCtxToDefault(this.ctx, this.foregroundColor);
  821. if (transform) {
  822. this.ctx.transform(...transform);
  823. this.outputScaleX = transform[0];
  824. this.outputScaleY = transform[0];
  825. }
  826. this.ctx.transform(...viewport.transform);
  827. this.viewportScale = viewport.scale;
  828. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  829. }
  830. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  831. const argsArray = operatorList.argsArray;
  832. const fnArray = operatorList.fnArray;
  833. let i = executionStartIdx || 0;
  834. const argsArrayLen = argsArray.length;
  835. if (argsArrayLen === i) {
  836. return i;
  837. }
  838. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  839. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  840. let steps = 0;
  841. const commonObjs = this.commonObjs;
  842. const objs = this.objs;
  843. let fnId;
  844. while (true) {
  845. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  846. stepper.breakIt(i, continueCallback);
  847. return i;
  848. }
  849. fnId = fnArray[i];
  850. if (fnId !== _util.OPS.dependency) {
  851. this[fnId].apply(this, argsArray[i]);
  852. } else {
  853. for (const depObjId of argsArray[i]) {
  854. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  855. if (!objsPool.has(depObjId)) {
  856. objsPool.get(depObjId, continueCallback);
  857. return i;
  858. }
  859. }
  860. }
  861. i++;
  862. if (i === argsArrayLen) {
  863. return i;
  864. }
  865. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  866. if (Date.now() > endTime) {
  867. continueCallback();
  868. return i;
  869. }
  870. steps = 0;
  871. }
  872. }
  873. }
  874. #restoreInitialState() {
  875. while (this.stateStack.length || this.inSMaskMode) {
  876. this.restore();
  877. }
  878. this.ctx.restore();
  879. if (this.transparentCanvas) {
  880. this.ctx = this.compositeCtx;
  881. this.ctx.save();
  882. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  883. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  884. this.ctx.restore();
  885. this.transparentCanvas = null;
  886. }
  887. }
  888. endDrawing() {
  889. this.#restoreInitialState();
  890. this.cachedCanvases.clear();
  891. this.cachedPatterns.clear();
  892. for (const cache of this._cachedBitmapsMap.values()) {
  893. for (const canvas of cache.values()) {
  894. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  895. canvas.width = canvas.height = 0;
  896. }
  897. }
  898. cache.clear();
  899. }
  900. this._cachedBitmapsMap.clear();
  901. }
  902. _scaleImage(img, inverseTransform) {
  903. const width = img.width;
  904. const height = img.height;
  905. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  906. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  907. let paintWidth = width,
  908. paintHeight = height;
  909. let tmpCanvasId = "prescale1";
  910. let tmpCanvas, tmpCtx;
  911. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  912. let newWidth = paintWidth,
  913. newHeight = paintHeight;
  914. if (widthScale > 2 && paintWidth > 1) {
  915. newWidth = Math.ceil(paintWidth / 2);
  916. widthScale /= paintWidth / newWidth;
  917. }
  918. if (heightScale > 2 && paintHeight > 1) {
  919. newHeight = Math.ceil(paintHeight / 2);
  920. heightScale /= paintHeight / newHeight;
  921. }
  922. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  923. tmpCtx = tmpCanvas.context;
  924. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  925. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  926. img = tmpCanvas.canvas;
  927. paintWidth = newWidth;
  928. paintHeight = newHeight;
  929. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  930. }
  931. return {
  932. img,
  933. paintWidth,
  934. paintHeight
  935. };
  936. }
  937. _createMaskCanvas(img) {
  938. const ctx = this.ctx;
  939. const {
  940. width,
  941. height
  942. } = img;
  943. const fillColor = this.current.fillColor;
  944. const isPatternFill = this.current.patternFill;
  945. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  946. let cache, cacheKey, scaled, maskCanvas;
  947. if ((img.bitmap || img.data) && img.count > 1) {
  948. const mainKey = img.bitmap || img.data.buffer;
  949. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  950. cache = this._cachedBitmapsMap.get(mainKey);
  951. if (!cache) {
  952. cache = new Map();
  953. this._cachedBitmapsMap.set(mainKey, cache);
  954. }
  955. const cachedImage = cache.get(cacheKey);
  956. if (cachedImage && !isPatternFill) {
  957. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  958. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  959. return {
  960. canvas: cachedImage,
  961. offsetX,
  962. offsetY
  963. };
  964. }
  965. scaled = cachedImage;
  966. }
  967. if (!scaled) {
  968. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  969. putBinaryImageMask(maskCanvas.context, img);
  970. }
  971. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  972. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  973. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  974. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  975. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  976. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  977. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  978. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  979. const fillCtx = fillCanvas.context;
  980. const offsetX = Math.min(cord1[0], cord2[0]);
  981. const offsetY = Math.min(cord1[1], cord2[1]);
  982. fillCtx.translate(-offsetX, -offsetY);
  983. fillCtx.transform(...maskToCanvas);
  984. if (!scaled) {
  985. scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
  986. scaled = scaled.img;
  987. if (cache && isPatternFill) {
  988. cache.set(cacheKey, scaled);
  989. }
  990. }
  991. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
  992. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  993. fillCtx.globalCompositeOperation = "source-in";
  994. const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  995. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  996. fillCtx.fillRect(0, 0, width, height);
  997. if (cache && !isPatternFill) {
  998. this.cachedCanvases.delete("fillCanvas");
  999. cache.set(cacheKey, fillCanvas.canvas);
  1000. }
  1001. return {
  1002. canvas: fillCanvas.canvas,
  1003. offsetX: Math.round(offsetX),
  1004. offsetY: Math.round(offsetY)
  1005. };
  1006. }
  1007. setLineWidth(width) {
  1008. if (width !== this.current.lineWidth) {
  1009. this._cachedScaleForStroking = null;
  1010. }
  1011. this.current.lineWidth = width;
  1012. this.ctx.lineWidth = width;
  1013. }
  1014. setLineCap(style) {
  1015. this.ctx.lineCap = LINE_CAP_STYLES[style];
  1016. }
  1017. setLineJoin(style) {
  1018. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  1019. }
  1020. setMiterLimit(limit) {
  1021. this.ctx.miterLimit = limit;
  1022. }
  1023. setDash(dashArray, dashPhase) {
  1024. const ctx = this.ctx;
  1025. if (ctx.setLineDash !== undefined) {
  1026. ctx.setLineDash(dashArray);
  1027. ctx.lineDashOffset = dashPhase;
  1028. }
  1029. }
  1030. setRenderingIntent(intent) {}
  1031. setFlatness(flatness) {}
  1032. setGState(states) {
  1033. for (const [key, value] of states) {
  1034. switch (key) {
  1035. case "LW":
  1036. this.setLineWidth(value);
  1037. break;
  1038. case "LC":
  1039. this.setLineCap(value);
  1040. break;
  1041. case "LJ":
  1042. this.setLineJoin(value);
  1043. break;
  1044. case "ML":
  1045. this.setMiterLimit(value);
  1046. break;
  1047. case "D":
  1048. this.setDash(value[0], value[1]);
  1049. break;
  1050. case "RI":
  1051. this.setRenderingIntent(value);
  1052. break;
  1053. case "FL":
  1054. this.setFlatness(value);
  1055. break;
  1056. case "Font":
  1057. this.setFont(value[0], value[1]);
  1058. break;
  1059. case "CA":
  1060. this.current.strokeAlpha = value;
  1061. break;
  1062. case "ca":
  1063. this.current.fillAlpha = value;
  1064. this.ctx.globalAlpha = value;
  1065. break;
  1066. case "BM":
  1067. this.ctx.globalCompositeOperation = value;
  1068. break;
  1069. case "SMask":
  1070. this.current.activeSMask = value ? this.tempSMask : null;
  1071. this.tempSMask = null;
  1072. this.checkSMaskState();
  1073. break;
  1074. case "TR":
  1075. this.current.transferMaps = value;
  1076. }
  1077. }
  1078. }
  1079. get inSMaskMode() {
  1080. return !!this.suspendedCtx;
  1081. }
  1082. checkSMaskState() {
  1083. const inSMaskMode = this.inSMaskMode;
  1084. if (this.current.activeSMask && !inSMaskMode) {
  1085. this.beginSMaskMode();
  1086. } else if (!this.current.activeSMask && inSMaskMode) {
  1087. this.endSMaskMode();
  1088. }
  1089. }
  1090. beginSMaskMode() {
  1091. if (this.inSMaskMode) {
  1092. throw new Error("beginSMaskMode called while already in smask mode");
  1093. }
  1094. const drawnWidth = this.ctx.canvas.width;
  1095. const drawnHeight = this.ctx.canvas.height;
  1096. const cacheId = "smaskGroupAt" + this.groupLevel;
  1097. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  1098. this.suspendedCtx = this.ctx;
  1099. this.ctx = scratchCanvas.context;
  1100. const ctx = this.ctx;
  1101. ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
  1102. copyCtxState(this.suspendedCtx, ctx);
  1103. mirrorContextOperations(ctx, this.suspendedCtx);
  1104. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  1105. }
  1106. endSMaskMode() {
  1107. if (!this.inSMaskMode) {
  1108. throw new Error("endSMaskMode called while not in smask mode");
  1109. }
  1110. this.ctx._removeMirroring();
  1111. copyCtxState(this.ctx, this.suspendedCtx);
  1112. this.ctx = this.suspendedCtx;
  1113. this.suspendedCtx = null;
  1114. }
  1115. compose(dirtyBox) {
  1116. if (!this.current.activeSMask) {
  1117. return;
  1118. }
  1119. if (!dirtyBox) {
  1120. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  1121. } else {
  1122. dirtyBox[0] = Math.floor(dirtyBox[0]);
  1123. dirtyBox[1] = Math.floor(dirtyBox[1]);
  1124. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  1125. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  1126. }
  1127. const smask = this.current.activeSMask;
  1128. const suspendedCtx = this.suspendedCtx;
  1129. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  1130. this.ctx.save();
  1131. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  1132. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  1133. this.ctx.restore();
  1134. }
  1135. save() {
  1136. if (this.inSMaskMode) {
  1137. copyCtxState(this.ctx, this.suspendedCtx);
  1138. this.suspendedCtx.save();
  1139. } else {
  1140. this.ctx.save();
  1141. }
  1142. const old = this.current;
  1143. this.stateStack.push(old);
  1144. this.current = old.clone();
  1145. }
  1146. restore() {
  1147. if (this.stateStack.length === 0 && this.inSMaskMode) {
  1148. this.endSMaskMode();
  1149. }
  1150. if (this.stateStack.length !== 0) {
  1151. this.current = this.stateStack.pop();
  1152. if (this.inSMaskMode) {
  1153. this.suspendedCtx.restore();
  1154. copyCtxState(this.suspendedCtx, this.ctx);
  1155. } else {
  1156. this.ctx.restore();
  1157. }
  1158. this.checkSMaskState();
  1159. this.pendingClip = null;
  1160. this._cachedScaleForStroking = null;
  1161. this._cachedGetSinglePixelWidth = null;
  1162. }
  1163. }
  1164. transform(a, b, c, d, e, f) {
  1165. this.ctx.transform(a, b, c, d, e, f);
  1166. this._cachedScaleForStroking = null;
  1167. this._cachedGetSinglePixelWidth = null;
  1168. }
  1169. constructPath(ops, args, minMax) {
  1170. const ctx = this.ctx;
  1171. const current = this.current;
  1172. let x = current.x,
  1173. y = current.y;
  1174. let startX, startY;
  1175. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  1176. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  1177. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  1178. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  1179. switch (ops[i] | 0) {
  1180. case _util.OPS.rectangle:
  1181. x = args[j++];
  1182. y = args[j++];
  1183. const width = args[j++];
  1184. const height = args[j++];
  1185. const xw = x + width;
  1186. const yh = y + height;
  1187. ctx.moveTo(x, y);
  1188. if (width === 0 || height === 0) {
  1189. ctx.lineTo(xw, yh);
  1190. } else {
  1191. ctx.lineTo(xw, y);
  1192. ctx.lineTo(xw, yh);
  1193. ctx.lineTo(x, yh);
  1194. }
  1195. if (!isScalingMatrix) {
  1196. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  1197. }
  1198. ctx.closePath();
  1199. break;
  1200. case _util.OPS.moveTo:
  1201. x = args[j++];
  1202. y = args[j++];
  1203. ctx.moveTo(x, y);
  1204. if (!isScalingMatrix) {
  1205. current.updatePathMinMax(currentTransform, x, y);
  1206. }
  1207. break;
  1208. case _util.OPS.lineTo:
  1209. x = args[j++];
  1210. y = args[j++];
  1211. ctx.lineTo(x, y);
  1212. if (!isScalingMatrix) {
  1213. current.updatePathMinMax(currentTransform, x, y);
  1214. }
  1215. break;
  1216. case _util.OPS.curveTo:
  1217. startX = x;
  1218. startY = y;
  1219. x = args[j + 4];
  1220. y = args[j + 5];
  1221. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  1222. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  1223. j += 6;
  1224. break;
  1225. case _util.OPS.curveTo2:
  1226. startX = x;
  1227. startY = y;
  1228. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  1229. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  1230. x = args[j + 2];
  1231. y = args[j + 3];
  1232. j += 4;
  1233. break;
  1234. case _util.OPS.curveTo3:
  1235. startX = x;
  1236. startY = y;
  1237. x = args[j + 2];
  1238. y = args[j + 3];
  1239. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  1240. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  1241. j += 4;
  1242. break;
  1243. case _util.OPS.closePath:
  1244. ctx.closePath();
  1245. break;
  1246. }
  1247. }
  1248. if (isScalingMatrix) {
  1249. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  1250. }
  1251. current.setCurrentPoint(x, y);
  1252. }
  1253. closePath() {
  1254. this.ctx.closePath();
  1255. }
  1256. stroke(consumePath) {
  1257. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  1258. const ctx = this.ctx;
  1259. const strokeColor = this.current.strokeColor;
  1260. ctx.globalAlpha = this.current.strokeAlpha;
  1261. if (this.contentVisible) {
  1262. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  1263. ctx.save();
  1264. ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
  1265. this.rescaleAndStroke(false);
  1266. ctx.restore();
  1267. } else {
  1268. this.rescaleAndStroke(true);
  1269. }
  1270. }
  1271. if (consumePath) {
  1272. this.consumePath(this.current.getClippedPathBoundingBox());
  1273. }
  1274. ctx.globalAlpha = this.current.fillAlpha;
  1275. }
  1276. closeStroke() {
  1277. this.closePath();
  1278. this.stroke();
  1279. }
  1280. fill(consumePath) {
  1281. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  1282. const ctx = this.ctx;
  1283. const fillColor = this.current.fillColor;
  1284. const isPatternFill = this.current.patternFill;
  1285. let needRestore = false;
  1286. if (isPatternFill) {
  1287. ctx.save();
  1288. ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  1289. needRestore = true;
  1290. }
  1291. const intersect = this.current.getClippedPathBoundingBox();
  1292. if (this.contentVisible && intersect !== null) {
  1293. if (this.pendingEOFill) {
  1294. ctx.fill("evenodd");
  1295. this.pendingEOFill = false;
  1296. } else {
  1297. ctx.fill();
  1298. }
  1299. }
  1300. if (needRestore) {
  1301. ctx.restore();
  1302. }
  1303. if (consumePath) {
  1304. this.consumePath(intersect);
  1305. }
  1306. }
  1307. eoFill() {
  1308. this.pendingEOFill = true;
  1309. this.fill();
  1310. }
  1311. fillStroke() {
  1312. this.fill(false);
  1313. this.stroke(false);
  1314. this.consumePath();
  1315. }
  1316. eoFillStroke() {
  1317. this.pendingEOFill = true;
  1318. this.fillStroke();
  1319. }
  1320. closeFillStroke() {
  1321. this.closePath();
  1322. this.fillStroke();
  1323. }
  1324. closeEOFillStroke() {
  1325. this.pendingEOFill = true;
  1326. this.closePath();
  1327. this.fillStroke();
  1328. }
  1329. endPath() {
  1330. this.consumePath();
  1331. }
  1332. clip() {
  1333. this.pendingClip = NORMAL_CLIP;
  1334. }
  1335. eoClip() {
  1336. this.pendingClip = EO_CLIP;
  1337. }
  1338. beginText() {
  1339. this.current.textMatrix = _util.IDENTITY_MATRIX;
  1340. this.current.textMatrixScale = 1;
  1341. this.current.x = this.current.lineX = 0;
  1342. this.current.y = this.current.lineY = 0;
  1343. }
  1344. endText() {
  1345. const paths = this.pendingTextPaths;
  1346. const ctx = this.ctx;
  1347. if (paths === undefined) {
  1348. ctx.beginPath();
  1349. return;
  1350. }
  1351. ctx.save();
  1352. ctx.beginPath();
  1353. for (const path of paths) {
  1354. ctx.setTransform(...path.transform);
  1355. ctx.translate(path.x, path.y);
  1356. path.addToPath(ctx, path.fontSize);
  1357. }
  1358. ctx.restore();
  1359. ctx.clip();
  1360. ctx.beginPath();
  1361. delete this.pendingTextPaths;
  1362. }
  1363. setCharSpacing(spacing) {
  1364. this.current.charSpacing = spacing;
  1365. }
  1366. setWordSpacing(spacing) {
  1367. this.current.wordSpacing = spacing;
  1368. }
  1369. setHScale(scale) {
  1370. this.current.textHScale = scale / 100;
  1371. }
  1372. setLeading(leading) {
  1373. this.current.leading = -leading;
  1374. }
  1375. setFont(fontRefName, size) {
  1376. const fontObj = this.commonObjs.get(fontRefName);
  1377. const current = this.current;
  1378. if (!fontObj) {
  1379. throw new Error(`Can't find font for ${fontRefName}`);
  1380. }
  1381. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1382. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  1383. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  1384. }
  1385. if (size < 0) {
  1386. size = -size;
  1387. current.fontDirection = -1;
  1388. } else {
  1389. current.fontDirection = 1;
  1390. }
  1391. this.current.font = fontObj;
  1392. this.current.fontSize = size;
  1393. if (fontObj.isType3Font) {
  1394. return;
  1395. }
  1396. const name = fontObj.loadedName || "sans-serif";
  1397. let bold = "normal";
  1398. if (fontObj.black) {
  1399. bold = "900";
  1400. } else if (fontObj.bold) {
  1401. bold = "bold";
  1402. }
  1403. const italic = fontObj.italic ? "italic" : "normal";
  1404. const typeface = `"${name}", ${fontObj.fallbackName}`;
  1405. let browserFontSize = size;
  1406. if (size < MIN_FONT_SIZE) {
  1407. browserFontSize = MIN_FONT_SIZE;
  1408. } else if (size > MAX_FONT_SIZE) {
  1409. browserFontSize = MAX_FONT_SIZE;
  1410. }
  1411. this.current.fontSizeScale = size / browserFontSize;
  1412. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  1413. }
  1414. setTextRenderingMode(mode) {
  1415. this.current.textRenderingMode = mode;
  1416. }
  1417. setTextRise(rise) {
  1418. this.current.textRise = rise;
  1419. }
  1420. moveText(x, y) {
  1421. this.current.x = this.current.lineX += x;
  1422. this.current.y = this.current.lineY += y;
  1423. }
  1424. setLeadingMoveText(x, y) {
  1425. this.setLeading(-y);
  1426. this.moveText(x, y);
  1427. }
  1428. setTextMatrix(a, b, c, d, e, f) {
  1429. this.current.textMatrix = [a, b, c, d, e, f];
  1430. this.current.textMatrixScale = Math.hypot(a, b);
  1431. this.current.x = this.current.lineX = 0;
  1432. this.current.y = this.current.lineY = 0;
  1433. }
  1434. nextLine() {
  1435. this.moveText(0, this.current.leading);
  1436. }
  1437. paintChar(character, x, y, patternTransform) {
  1438. const ctx = this.ctx;
  1439. const current = this.current;
  1440. const font = current.font;
  1441. const textRenderingMode = current.textRenderingMode;
  1442. const fontSize = current.fontSize / current.fontSizeScale;
  1443. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1444. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  1445. const patternFill = current.patternFill && !font.missingFile;
  1446. let addToPath;
  1447. if (font.disableFontFace || isAddToPathSet || patternFill) {
  1448. addToPath = font.getPathGenerator(this.commonObjs, character);
  1449. }
  1450. if (font.disableFontFace || patternFill) {
  1451. ctx.save();
  1452. ctx.translate(x, y);
  1453. ctx.beginPath();
  1454. addToPath(ctx, fontSize);
  1455. if (patternTransform) {
  1456. ctx.setTransform(...patternTransform);
  1457. }
  1458. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1459. ctx.fill();
  1460. }
  1461. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1462. ctx.stroke();
  1463. }
  1464. ctx.restore();
  1465. } else {
  1466. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1467. ctx.fillText(character, x, y);
  1468. }
  1469. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1470. ctx.strokeText(character, x, y);
  1471. }
  1472. }
  1473. if (isAddToPathSet) {
  1474. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  1475. paths.push({
  1476. transform: (0, _display_utils.getCurrentTransform)(ctx),
  1477. x,
  1478. y,
  1479. fontSize,
  1480. addToPath
  1481. });
  1482. }
  1483. }
  1484. get isFontSubpixelAAEnabled() {
  1485. const {
  1486. context: ctx
  1487. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  1488. ctx.scale(1.5, 1);
  1489. ctx.fillText("I", 0, 10);
  1490. const data = ctx.getImageData(0, 0, 10, 10).data;
  1491. let enabled = false;
  1492. for (let i = 3; i < data.length; i += 4) {
  1493. if (data[i] > 0 && data[i] < 255) {
  1494. enabled = true;
  1495. break;
  1496. }
  1497. }
  1498. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  1499. }
  1500. showText(glyphs) {
  1501. const current = this.current;
  1502. const font = current.font;
  1503. if (font.isType3Font) {
  1504. return this.showType3Text(glyphs);
  1505. }
  1506. const fontSize = current.fontSize;
  1507. if (fontSize === 0) {
  1508. return undefined;
  1509. }
  1510. const ctx = this.ctx;
  1511. const fontSizeScale = current.fontSizeScale;
  1512. const charSpacing = current.charSpacing;
  1513. const wordSpacing = current.wordSpacing;
  1514. const fontDirection = current.fontDirection;
  1515. const textHScale = current.textHScale * fontDirection;
  1516. const glyphsLength = glyphs.length;
  1517. const vertical = font.vertical;
  1518. const spacingDir = vertical ? 1 : -1;
  1519. const defaultVMetrics = font.defaultVMetrics;
  1520. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  1521. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  1522. ctx.save();
  1523. ctx.transform(...current.textMatrix);
  1524. ctx.translate(current.x, current.y + current.textRise);
  1525. if (fontDirection > 0) {
  1526. ctx.scale(textHScale, -1);
  1527. } else {
  1528. ctx.scale(textHScale, 1);
  1529. }
  1530. let patternTransform;
  1531. if (current.patternFill) {
  1532. ctx.save();
  1533. const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  1534. patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
  1535. ctx.restore();
  1536. ctx.fillStyle = pattern;
  1537. }
  1538. let lineWidth = current.lineWidth;
  1539. const scale = current.textMatrixScale;
  1540. if (scale === 0 || lineWidth === 0) {
  1541. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1542. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1543. lineWidth = this.getSinglePixelWidth();
  1544. }
  1545. } else {
  1546. lineWidth /= scale;
  1547. }
  1548. if (fontSizeScale !== 1.0) {
  1549. ctx.scale(fontSizeScale, fontSizeScale);
  1550. lineWidth /= fontSizeScale;
  1551. }
  1552. ctx.lineWidth = lineWidth;
  1553. let x = 0,
  1554. i;
  1555. for (i = 0; i < glyphsLength; ++i) {
  1556. const glyph = glyphs[i];
  1557. if (typeof glyph === "number") {
  1558. x += spacingDir * glyph * fontSize / 1000;
  1559. continue;
  1560. }
  1561. let restoreNeeded = false;
  1562. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1563. const character = glyph.fontChar;
  1564. const accent = glyph.accent;
  1565. let scaledX, scaledY;
  1566. let width = glyph.width;
  1567. if (vertical) {
  1568. const vmetric = glyph.vmetric || defaultVMetrics;
  1569. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  1570. const vy = vmetric[2] * widthAdvanceScale;
  1571. width = vmetric ? -vmetric[0] : width;
  1572. scaledX = vx / fontSizeScale;
  1573. scaledY = (x + vy) / fontSizeScale;
  1574. } else {
  1575. scaledX = x / fontSizeScale;
  1576. scaledY = 0;
  1577. }
  1578. if (font.remeasure && width > 0) {
  1579. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  1580. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  1581. const characterScaleX = width / measuredWidth;
  1582. restoreNeeded = true;
  1583. ctx.save();
  1584. ctx.scale(characterScaleX, 1);
  1585. scaledX /= characterScaleX;
  1586. } else if (width !== measuredWidth) {
  1587. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  1588. }
  1589. }
  1590. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  1591. if (simpleFillText && !accent) {
  1592. ctx.fillText(character, scaledX, scaledY);
  1593. } else {
  1594. this.paintChar(character, scaledX, scaledY, patternTransform);
  1595. if (accent) {
  1596. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  1597. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  1598. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  1599. }
  1600. }
  1601. }
  1602. let charWidth;
  1603. if (vertical) {
  1604. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  1605. } else {
  1606. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  1607. }
  1608. x += charWidth;
  1609. if (restoreNeeded) {
  1610. ctx.restore();
  1611. }
  1612. }
  1613. if (vertical) {
  1614. current.y -= x;
  1615. } else {
  1616. current.x += x * textHScale;
  1617. }
  1618. ctx.restore();
  1619. this.compose();
  1620. return undefined;
  1621. }
  1622. showType3Text(glyphs) {
  1623. const ctx = this.ctx;
  1624. const current = this.current;
  1625. const font = current.font;
  1626. const fontSize = current.fontSize;
  1627. const fontDirection = current.fontDirection;
  1628. const spacingDir = font.vertical ? 1 : -1;
  1629. const charSpacing = current.charSpacing;
  1630. const wordSpacing = current.wordSpacing;
  1631. const textHScale = current.textHScale * fontDirection;
  1632. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1633. const glyphsLength = glyphs.length;
  1634. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  1635. let i, glyph, width, spacingLength;
  1636. if (isTextInvisible || fontSize === 0) {
  1637. return;
  1638. }
  1639. this._cachedScaleForStroking = null;
  1640. this._cachedGetSinglePixelWidth = null;
  1641. ctx.save();
  1642. ctx.transform(...current.textMatrix);
  1643. ctx.translate(current.x, current.y);
  1644. ctx.scale(textHScale, fontDirection);
  1645. for (i = 0; i < glyphsLength; ++i) {
  1646. glyph = glyphs[i];
  1647. if (typeof glyph === "number") {
  1648. spacingLength = spacingDir * glyph * fontSize / 1000;
  1649. this.ctx.translate(spacingLength, 0);
  1650. current.x += spacingLength * textHScale;
  1651. continue;
  1652. }
  1653. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1654. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  1655. if (!operatorList) {
  1656. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  1657. continue;
  1658. }
  1659. if (this.contentVisible) {
  1660. this.processingType3 = glyph;
  1661. this.save();
  1662. ctx.scale(fontSize, fontSize);
  1663. ctx.transform(...fontMatrix);
  1664. this.executeOperatorList(operatorList);
  1665. this.restore();
  1666. }
  1667. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  1668. width = transformed[0] * fontSize + spacing;
  1669. ctx.translate(width, 0);
  1670. current.x += width * textHScale;
  1671. }
  1672. ctx.restore();
  1673. this.processingType3 = null;
  1674. }
  1675. setCharWidth(xWidth, yWidth) {}
  1676. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  1677. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  1678. this.ctx.clip();
  1679. this.endPath();
  1680. }
  1681. getColorN_Pattern(IR) {
  1682. let pattern;
  1683. if (IR[0] === "TilingPattern") {
  1684. const color = IR[1];
  1685. const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
  1686. const canvasGraphicsFactory = {
  1687. createCanvasGraphics: ctx => {
  1688. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
  1689. }
  1690. };
  1691. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  1692. } else {
  1693. pattern = this._getPattern(IR[1], IR[2]);
  1694. }
  1695. return pattern;
  1696. }
  1697. setStrokeColorN() {
  1698. this.current.strokeColor = this.getColorN_Pattern(arguments);
  1699. }
  1700. setFillColorN() {
  1701. this.current.fillColor = this.getColorN_Pattern(arguments);
  1702. this.current.patternFill = true;
  1703. }
  1704. setStrokeRGBColor(r, g, b) {
  1705. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  1706. this.ctx.strokeStyle = color;
  1707. this.current.strokeColor = color;
  1708. }
  1709. setFillRGBColor(r, g, b) {
  1710. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  1711. this.ctx.fillStyle = color;
  1712. this.current.fillColor = color;
  1713. this.current.patternFill = false;
  1714. }
  1715. _getPattern(objId, matrix = null) {
  1716. let pattern;
  1717. if (this.cachedPatterns.has(objId)) {
  1718. pattern = this.cachedPatterns.get(objId);
  1719. } else {
  1720. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  1721. this.cachedPatterns.set(objId, pattern);
  1722. }
  1723. if (matrix) {
  1724. pattern.matrix = matrix;
  1725. }
  1726. return pattern;
  1727. }
  1728. shadingFill(objId) {
  1729. if (!this.contentVisible) {
  1730. return;
  1731. }
  1732. const ctx = this.ctx;
  1733. this.save();
  1734. const pattern = this._getPattern(objId);
  1735. ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
  1736. const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
  1737. if (inv) {
  1738. const canvas = ctx.canvas;
  1739. const width = canvas.width;
  1740. const height = canvas.height;
  1741. const bl = _util.Util.applyTransform([0, 0], inv);
  1742. const br = _util.Util.applyTransform([0, height], inv);
  1743. const ul = _util.Util.applyTransform([width, 0], inv);
  1744. const ur = _util.Util.applyTransform([width, height], inv);
  1745. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  1746. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  1747. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  1748. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  1749. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  1750. } else {
  1751. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  1752. }
  1753. this.compose(this.current.getClippedPathBoundingBox());
  1754. this.restore();
  1755. }
  1756. beginInlineImage() {
  1757. (0, _util.unreachable)("Should not call beginInlineImage");
  1758. }
  1759. beginImageData() {
  1760. (0, _util.unreachable)("Should not call beginImageData");
  1761. }
  1762. paintFormXObjectBegin(matrix, bbox) {
  1763. if (!this.contentVisible) {
  1764. return;
  1765. }
  1766. this.save();
  1767. this.baseTransformStack.push(this.baseTransform);
  1768. if (Array.isArray(matrix) && matrix.length === 6) {
  1769. this.transform(...matrix);
  1770. }
  1771. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  1772. if (bbox) {
  1773. const width = bbox[2] - bbox[0];
  1774. const height = bbox[3] - bbox[1];
  1775. this.ctx.rect(bbox[0], bbox[1], width, height);
  1776. this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
  1777. this.clip();
  1778. this.endPath();
  1779. }
  1780. }
  1781. paintFormXObjectEnd() {
  1782. if (!this.contentVisible) {
  1783. return;
  1784. }
  1785. this.restore();
  1786. this.baseTransform = this.baseTransformStack.pop();
  1787. }
  1788. beginGroup(group) {
  1789. if (!this.contentVisible) {
  1790. return;
  1791. }
  1792. this.save();
  1793. if (this.inSMaskMode) {
  1794. this.endSMaskMode();
  1795. this.current.activeSMask = null;
  1796. }
  1797. const currentCtx = this.ctx;
  1798. if (!group.isolated) {
  1799. (0, _util.info)("TODO: Support non-isolated groups.");
  1800. }
  1801. if (group.knockout) {
  1802. (0, _util.warn)("Knockout groups not supported.");
  1803. }
  1804. const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
  1805. if (group.matrix) {
  1806. currentCtx.transform(...group.matrix);
  1807. }
  1808. if (!group.bbox) {
  1809. throw new Error("Bounding box is required.");
  1810. }
  1811. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
  1812. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  1813. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  1814. const offsetX = Math.floor(bounds[0]);
  1815. const offsetY = Math.floor(bounds[1]);
  1816. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  1817. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  1818. let scaleX = 1,
  1819. scaleY = 1;
  1820. if (drawnWidth > MAX_GROUP_SIZE) {
  1821. scaleX = drawnWidth / MAX_GROUP_SIZE;
  1822. drawnWidth = MAX_GROUP_SIZE;
  1823. }
  1824. if (drawnHeight > MAX_GROUP_SIZE) {
  1825. scaleY = drawnHeight / MAX_GROUP_SIZE;
  1826. drawnHeight = MAX_GROUP_SIZE;
  1827. }
  1828. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  1829. let cacheId = "groupAt" + this.groupLevel;
  1830. if (group.smask) {
  1831. cacheId += "_smask_" + this.smaskCounter++ % 2;
  1832. }
  1833. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  1834. const groupCtx = scratchCanvas.context;
  1835. groupCtx.scale(1 / scaleX, 1 / scaleY);
  1836. groupCtx.translate(-offsetX, -offsetY);
  1837. groupCtx.transform(...currentTransform);
  1838. if (group.smask) {
  1839. this.smaskStack.push({
  1840. canvas: scratchCanvas.canvas,
  1841. context: groupCtx,
  1842. offsetX,
  1843. offsetY,
  1844. scaleX,
  1845. scaleY,
  1846. subtype: group.smask.subtype,
  1847. backdrop: group.smask.backdrop,
  1848. transferMap: group.smask.transferMap || null,
  1849. startTransformInverse: null
  1850. });
  1851. } else {
  1852. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  1853. currentCtx.translate(offsetX, offsetY);
  1854. currentCtx.scale(scaleX, scaleY);
  1855. currentCtx.save();
  1856. }
  1857. copyCtxState(currentCtx, groupCtx);
  1858. this.ctx = groupCtx;
  1859. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  1860. this.groupStack.push(currentCtx);
  1861. this.groupLevel++;
  1862. }
  1863. endGroup(group) {
  1864. if (!this.contentVisible) {
  1865. return;
  1866. }
  1867. this.groupLevel--;
  1868. const groupCtx = this.ctx;
  1869. const ctx = this.groupStack.pop();
  1870. this.ctx = ctx;
  1871. this.ctx.imageSmoothingEnabled = false;
  1872. if (group.smask) {
  1873. this.tempSMask = this.smaskStack.pop();
  1874. this.restore();
  1875. } else {
  1876. this.ctx.restore();
  1877. const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
  1878. this.restore();
  1879. this.ctx.save();
  1880. this.ctx.setTransform(...currentMtx);
  1881. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  1882. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  1883. this.ctx.restore();
  1884. this.compose(dirtyBox);
  1885. }
  1886. }
  1887. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  1888. this.#restoreInitialState();
  1889. resetCtxToDefault(this.ctx, this.foregroundColor);
  1890. this.ctx.save();
  1891. this.save();
  1892. if (this.baseTransform) {
  1893. this.ctx.setTransform(...this.baseTransform);
  1894. }
  1895. if (Array.isArray(rect) && rect.length === 4) {
  1896. const width = rect[2] - rect[0];
  1897. const height = rect[3] - rect[1];
  1898. if (hasOwnCanvas && this.annotationCanvasMap) {
  1899. transform = transform.slice();
  1900. transform[4] -= rect[0];
  1901. transform[5] -= rect[1];
  1902. rect = rect.slice();
  1903. rect[0] = rect[1] = 0;
  1904. rect[2] = width;
  1905. rect[3] = height;
  1906. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
  1907. const {
  1908. viewportScale
  1909. } = this;
  1910. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  1911. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  1912. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  1913. const {
  1914. canvas,
  1915. context
  1916. } = this.annotationCanvas;
  1917. this.annotationCanvasMap.set(id, canvas);
  1918. this.annotationCanvas.savedCtx = this.ctx;
  1919. this.ctx = context;
  1920. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  1921. resetCtxToDefault(this.ctx, this.foregroundColor);
  1922. } else {
  1923. resetCtxToDefault(this.ctx, this.foregroundColor);
  1924. this.ctx.rect(rect[0], rect[1], width, height);
  1925. this.ctx.clip();
  1926. this.endPath();
  1927. }
  1928. }
  1929. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  1930. this.transform(...transform);
  1931. this.transform(...matrix);
  1932. }
  1933. endAnnotation() {
  1934. if (this.annotationCanvas) {
  1935. this.ctx = this.annotationCanvas.savedCtx;
  1936. delete this.annotationCanvas.savedCtx;
  1937. delete this.annotationCanvas;
  1938. }
  1939. }
  1940. paintImageMaskXObject(img) {
  1941. if (!this.contentVisible) {
  1942. return;
  1943. }
  1944. const count = img.count;
  1945. img = this.getObject(img.data, img);
  1946. img.count = count;
  1947. const ctx = this.ctx;
  1948. const glyph = this.processingType3;
  1949. if (glyph) {
  1950. if (glyph.compiled === undefined) {
  1951. glyph.compiled = compileType3Glyph(img);
  1952. }
  1953. if (glyph.compiled) {
  1954. glyph.compiled(ctx);
  1955. return;
  1956. }
  1957. }
  1958. const mask = this._createMaskCanvas(img);
  1959. const maskCanvas = mask.canvas;
  1960. ctx.save();
  1961. ctx.setTransform(1, 0, 0, 1, 0, 0);
  1962. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  1963. ctx.restore();
  1964. this.compose();
  1965. }
  1966. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  1967. if (!this.contentVisible) {
  1968. return;
  1969. }
  1970. img = this.getObject(img.data, img);
  1971. const ctx = this.ctx;
  1972. ctx.save();
  1973. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  1974. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  1975. const mask = this._createMaskCanvas(img);
  1976. ctx.setTransform(1, 0, 0, 1, 0, 0);
  1977. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  1978. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  1979. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  1980. ctx.drawImage(mask.canvas, x, y);
  1981. }
  1982. ctx.restore();
  1983. this.compose();
  1984. }
  1985. paintImageMaskXObjectGroup(images) {
  1986. if (!this.contentVisible) {
  1987. return;
  1988. }
  1989. const ctx = this.ctx;
  1990. const fillColor = this.current.fillColor;
  1991. const isPatternFill = this.current.patternFill;
  1992. for (const image of images) {
  1993. const {
  1994. data,
  1995. width,
  1996. height,
  1997. transform
  1998. } = image;
  1999. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  2000. const maskCtx = maskCanvas.context;
  2001. maskCtx.save();
  2002. const img = this.getObject(data, image);
  2003. putBinaryImageMask(maskCtx, img);
  2004. maskCtx.globalCompositeOperation = "source-in";
  2005. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
  2006. maskCtx.fillRect(0, 0, width, height);
  2007. maskCtx.restore();
  2008. ctx.save();
  2009. ctx.transform(...transform);
  2010. ctx.scale(1, -1);
  2011. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  2012. ctx.restore();
  2013. }
  2014. this.compose();
  2015. }
  2016. paintImageXObject(objId) {
  2017. if (!this.contentVisible) {
  2018. return;
  2019. }
  2020. const imgData = this.getObject(objId);
  2021. if (!imgData) {
  2022. (0, _util.warn)("Dependent image isn't ready yet");
  2023. return;
  2024. }
  2025. this.paintInlineImageXObject(imgData);
  2026. }
  2027. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  2028. if (!this.contentVisible) {
  2029. return;
  2030. }
  2031. const imgData = this.getObject(objId);
  2032. if (!imgData) {
  2033. (0, _util.warn)("Dependent image isn't ready yet");
  2034. return;
  2035. }
  2036. const width = imgData.width;
  2037. const height = imgData.height;
  2038. const map = [];
  2039. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  2040. map.push({
  2041. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  2042. x: 0,
  2043. y: 0,
  2044. w: width,
  2045. h: height
  2046. });
  2047. }
  2048. this.paintInlineImageXObjectGroup(imgData, map);
  2049. }
  2050. paintInlineImageXObject(imgData) {
  2051. if (!this.contentVisible) {
  2052. return;
  2053. }
  2054. const width = imgData.width;
  2055. const height = imgData.height;
  2056. const ctx = this.ctx;
  2057. this.save();
  2058. ctx.scale(1 / width, -1 / height);
  2059. let imgToPaint;
  2060. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  2061. imgToPaint = imgData;
  2062. } else {
  2063. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  2064. const tmpCtx = tmpCanvas.context;
  2065. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  2066. imgToPaint = tmpCanvas.canvas;
  2067. }
  2068. const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
  2069. ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
  2070. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  2071. this.compose();
  2072. this.restore();
  2073. }
  2074. paintInlineImageXObjectGroup(imgData, map) {
  2075. if (!this.contentVisible) {
  2076. return;
  2077. }
  2078. const ctx = this.ctx;
  2079. const w = imgData.width;
  2080. const h = imgData.height;
  2081. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  2082. const tmpCtx = tmpCanvas.context;
  2083. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  2084. for (const entry of map) {
  2085. ctx.save();
  2086. ctx.transform(...entry.transform);
  2087. ctx.scale(1, -1);
  2088. drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  2089. ctx.restore();
  2090. }
  2091. this.compose();
  2092. }
  2093. paintSolidColorImageMask() {
  2094. if (!this.contentVisible) {
  2095. return;
  2096. }
  2097. this.ctx.fillRect(0, 0, 1, 1);
  2098. this.compose();
  2099. }
  2100. markPoint(tag) {}
  2101. markPointProps(tag, properties) {}
  2102. beginMarkedContent(tag) {
  2103. this.markedContentStack.push({
  2104. visible: true
  2105. });
  2106. }
  2107. beginMarkedContentProps(tag, properties) {
  2108. if (tag === "OC") {
  2109. this.markedContentStack.push({
  2110. visible: this.optionalContentConfig.isVisible(properties)
  2111. });
  2112. } else {
  2113. this.markedContentStack.push({
  2114. visible: true
  2115. });
  2116. }
  2117. this.contentVisible = this.isContentVisible();
  2118. }
  2119. endMarkedContent() {
  2120. this.markedContentStack.pop();
  2121. this.contentVisible = this.isContentVisible();
  2122. }
  2123. beginCompat() {}
  2124. endCompat() {}
  2125. consumePath(clipBox) {
  2126. const isEmpty = this.current.isEmptyClip();
  2127. if (this.pendingClip) {
  2128. this.current.updateClipFromPath();
  2129. }
  2130. if (!this.pendingClip) {
  2131. this.compose(clipBox);
  2132. }
  2133. const ctx = this.ctx;
  2134. if (this.pendingClip) {
  2135. if (!isEmpty) {
  2136. if (this.pendingClip === EO_CLIP) {
  2137. ctx.clip("evenodd");
  2138. } else {
  2139. ctx.clip();
  2140. }
  2141. }
  2142. this.pendingClip = null;
  2143. }
  2144. this.current.startNewPathAndClipBox(this.current.clipBox);
  2145. ctx.beginPath();
  2146. }
  2147. getSinglePixelWidth() {
  2148. if (!this._cachedGetSinglePixelWidth) {
  2149. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  2150. if (m[1] === 0 && m[2] === 0) {
  2151. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  2152. } else {
  2153. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  2154. const normX = Math.hypot(m[0], m[2]);
  2155. const normY = Math.hypot(m[1], m[3]);
  2156. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  2157. }
  2158. }
  2159. return this._cachedGetSinglePixelWidth;
  2160. }
  2161. getScaleForStroking() {
  2162. if (!this._cachedScaleForStroking) {
  2163. const {
  2164. lineWidth
  2165. } = this.current;
  2166. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  2167. let scaleX, scaleY;
  2168. if (m[1] === 0 && m[2] === 0) {
  2169. const normX = Math.abs(m[0]);
  2170. const normY = Math.abs(m[3]);
  2171. if (lineWidth === 0) {
  2172. scaleX = 1 / normX;
  2173. scaleY = 1 / normY;
  2174. } else {
  2175. const scaledXLineWidth = normX * lineWidth;
  2176. const scaledYLineWidth = normY * lineWidth;
  2177. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  2178. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  2179. }
  2180. } else {
  2181. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  2182. const normX = Math.hypot(m[0], m[1]);
  2183. const normY = Math.hypot(m[2], m[3]);
  2184. if (lineWidth === 0) {
  2185. scaleX = normY / absDet;
  2186. scaleY = normX / absDet;
  2187. } else {
  2188. const baseArea = lineWidth * absDet;
  2189. scaleX = normY > baseArea ? normY / baseArea : 1;
  2190. scaleY = normX > baseArea ? normX / baseArea : 1;
  2191. }
  2192. }
  2193. this._cachedScaleForStroking = [scaleX, scaleY];
  2194. }
  2195. return this._cachedScaleForStroking;
  2196. }
  2197. rescaleAndStroke(saveRestore) {
  2198. const {
  2199. ctx
  2200. } = this;
  2201. const {
  2202. lineWidth
  2203. } = this.current;
  2204. const [scaleX, scaleY] = this.getScaleForStroking();
  2205. ctx.lineWidth = lineWidth || 1;
  2206. if (scaleX === 1 && scaleY === 1) {
  2207. ctx.stroke();
  2208. return;
  2209. }
  2210. let savedMatrix, savedDashes, savedDashOffset;
  2211. if (saveRestore) {
  2212. savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
  2213. savedDashes = ctx.getLineDash().slice();
  2214. savedDashOffset = ctx.lineDashOffset;
  2215. }
  2216. ctx.scale(scaleX, scaleY);
  2217. const scale = Math.max(scaleX, scaleY);
  2218. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  2219. ctx.lineDashOffset /= scale;
  2220. ctx.stroke();
  2221. if (saveRestore) {
  2222. ctx.setTransform(...savedMatrix);
  2223. ctx.setLineDash(savedDashes);
  2224. ctx.lineDashOffset = savedDashOffset;
  2225. }
  2226. }
  2227. isContentVisible() {
  2228. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  2229. if (!this.markedContentStack[i].visible) {
  2230. return false;
  2231. }
  2232. }
  2233. return true;
  2234. }
  2235. }
  2236. exports.CanvasGraphics = CanvasGraphics;
  2237. for (const op in _util.OPS) {
  2238. if (CanvasGraphics.prototype[op] !== undefined) {
  2239. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  2240. }
  2241. }