2
0

canvas.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  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, {
  733. optionalContentConfig,
  734. markedContentStack = null
  735. }, annotationCanvasMap, pageColors) {
  736. this.ctx = canvasCtx;
  737. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  738. this.stateStack = [];
  739. this.pendingClip = null;
  740. this.pendingEOFill = false;
  741. this.res = null;
  742. this.xobjs = null;
  743. this.commonObjs = commonObjs;
  744. this.objs = objs;
  745. this.canvasFactory = canvasFactory;
  746. this.groupStack = [];
  747. this.processingType3 = null;
  748. this.baseTransform = null;
  749. this.baseTransformStack = [];
  750. this.groupLevel = 0;
  751. this.smaskStack = [];
  752. this.smaskCounter = 0;
  753. this.tempSMask = null;
  754. this.suspendedCtx = null;
  755. this.contentVisible = true;
  756. this.markedContentStack = markedContentStack || [];
  757. this.optionalContentConfig = optionalContentConfig;
  758. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  759. this.cachedPatterns = new Map();
  760. this.annotationCanvasMap = annotationCanvasMap;
  761. this.viewportScale = 1;
  762. this.outputScaleX = 1;
  763. this.outputScaleY = 1;
  764. this.backgroundColor = pageColors?.background || null;
  765. this.foregroundColor = pageColors?.foreground || null;
  766. this._cachedScaleForStroking = null;
  767. this._cachedGetSinglePixelWidth = null;
  768. this._cachedBitmapsMap = new Map();
  769. }
  770. getObject(data, fallback = null) {
  771. if (typeof data === "string") {
  772. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  773. }
  774. return fallback;
  775. }
  776. beginDrawing({
  777. transform,
  778. viewport,
  779. transparency = false,
  780. background = null
  781. }) {
  782. const width = this.ctx.canvas.width;
  783. const height = this.ctx.canvas.height;
  784. const defaultBackgroundColor = background || "#ffffff";
  785. this.ctx.save();
  786. if (this.foregroundColor && this.backgroundColor) {
  787. this.ctx.fillStyle = this.foregroundColor;
  788. const fg = this.foregroundColor = this.ctx.fillStyle;
  789. this.ctx.fillStyle = this.backgroundColor;
  790. const bg = this.backgroundColor = this.ctx.fillStyle;
  791. let isValidDefaultBg = true;
  792. let defaultBg = defaultBackgroundColor;
  793. this.ctx.fillStyle = defaultBackgroundColor;
  794. defaultBg = this.ctx.fillStyle;
  795. isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
  796. if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
  797. this.foregroundColor = this.backgroundColor = null;
  798. } else {
  799. const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
  800. const newComp = x => {
  801. x /= 255;
  802. return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  803. };
  804. const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
  805. this.selectColor = (r, g, b) => {
  806. const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
  807. return Math.round(lumC) === lumB ? bg : fg;
  808. };
  809. }
  810. }
  811. this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
  812. this.ctx.fillRect(0, 0, width, height);
  813. this.ctx.restore();
  814. if (transparency) {
  815. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  816. this.compositeCtx = this.ctx;
  817. this.transparentCanvas = transparentCanvas.canvas;
  818. this.ctx = transparentCanvas.context;
  819. this.ctx.save();
  820. this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
  821. }
  822. this.ctx.save();
  823. resetCtxToDefault(this.ctx, this.foregroundColor);
  824. if (transform) {
  825. this.ctx.transform(...transform);
  826. this.outputScaleX = transform[0];
  827. this.outputScaleY = transform[0];
  828. }
  829. this.ctx.transform(...viewport.transform);
  830. this.viewportScale = viewport.scale;
  831. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  832. }
  833. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  834. const argsArray = operatorList.argsArray;
  835. const fnArray = operatorList.fnArray;
  836. let i = executionStartIdx || 0;
  837. const argsArrayLen = argsArray.length;
  838. if (argsArrayLen === i) {
  839. return i;
  840. }
  841. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  842. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  843. let steps = 0;
  844. const commonObjs = this.commonObjs;
  845. const objs = this.objs;
  846. let fnId;
  847. while (true) {
  848. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  849. stepper.breakIt(i, continueCallback);
  850. return i;
  851. }
  852. fnId = fnArray[i];
  853. if (fnId !== _util.OPS.dependency) {
  854. this[fnId].apply(this, argsArray[i]);
  855. } else {
  856. for (const depObjId of argsArray[i]) {
  857. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  858. if (!objsPool.has(depObjId)) {
  859. objsPool.get(depObjId, continueCallback);
  860. return i;
  861. }
  862. }
  863. }
  864. i++;
  865. if (i === argsArrayLen) {
  866. return i;
  867. }
  868. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  869. if (Date.now() > endTime) {
  870. continueCallback();
  871. return i;
  872. }
  873. steps = 0;
  874. }
  875. }
  876. }
  877. #restoreInitialState() {
  878. while (this.stateStack.length || this.inSMaskMode) {
  879. this.restore();
  880. }
  881. this.ctx.restore();
  882. if (this.transparentCanvas) {
  883. this.ctx = this.compositeCtx;
  884. this.ctx.save();
  885. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  886. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  887. this.ctx.restore();
  888. this.transparentCanvas = null;
  889. }
  890. }
  891. endDrawing() {
  892. this.#restoreInitialState();
  893. this.cachedCanvases.clear();
  894. this.cachedPatterns.clear();
  895. for (const cache of this._cachedBitmapsMap.values()) {
  896. for (const canvas of cache.values()) {
  897. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  898. canvas.width = canvas.height = 0;
  899. }
  900. }
  901. cache.clear();
  902. }
  903. this._cachedBitmapsMap.clear();
  904. }
  905. _scaleImage(img, inverseTransform) {
  906. const width = img.width;
  907. const height = img.height;
  908. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  909. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  910. let paintWidth = width,
  911. paintHeight = height;
  912. let tmpCanvasId = "prescale1";
  913. let tmpCanvas, tmpCtx;
  914. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  915. let newWidth = paintWidth,
  916. newHeight = paintHeight;
  917. if (widthScale > 2 && paintWidth > 1) {
  918. newWidth = Math.ceil(paintWidth / 2);
  919. widthScale /= paintWidth / newWidth;
  920. }
  921. if (heightScale > 2 && paintHeight > 1) {
  922. newHeight = Math.ceil(paintHeight / 2);
  923. heightScale /= paintHeight / newHeight;
  924. }
  925. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  926. tmpCtx = tmpCanvas.context;
  927. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  928. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  929. img = tmpCanvas.canvas;
  930. paintWidth = newWidth;
  931. paintHeight = newHeight;
  932. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  933. }
  934. return {
  935. img,
  936. paintWidth,
  937. paintHeight
  938. };
  939. }
  940. _createMaskCanvas(img) {
  941. const ctx = this.ctx;
  942. const {
  943. width,
  944. height
  945. } = img;
  946. const fillColor = this.current.fillColor;
  947. const isPatternFill = this.current.patternFill;
  948. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  949. let cache, cacheKey, scaled, maskCanvas;
  950. if ((img.bitmap || img.data) && img.count > 1) {
  951. const mainKey = img.bitmap || img.data.buffer;
  952. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  953. cache = this._cachedBitmapsMap.get(mainKey);
  954. if (!cache) {
  955. cache = new Map();
  956. this._cachedBitmapsMap.set(mainKey, cache);
  957. }
  958. const cachedImage = cache.get(cacheKey);
  959. if (cachedImage && !isPatternFill) {
  960. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  961. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  962. return {
  963. canvas: cachedImage,
  964. offsetX,
  965. offsetY
  966. };
  967. }
  968. scaled = cachedImage;
  969. }
  970. if (!scaled) {
  971. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  972. putBinaryImageMask(maskCanvas.context, img);
  973. }
  974. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  975. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  976. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  977. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  978. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  979. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  980. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  981. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  982. const fillCtx = fillCanvas.context;
  983. const offsetX = Math.min(cord1[0], cord2[0]);
  984. const offsetY = Math.min(cord1[1], cord2[1]);
  985. fillCtx.translate(-offsetX, -offsetY);
  986. fillCtx.transform(...maskToCanvas);
  987. if (!scaled) {
  988. scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
  989. scaled = scaled.img;
  990. if (cache && isPatternFill) {
  991. cache.set(cacheKey, scaled);
  992. }
  993. }
  994. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
  995. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  996. fillCtx.globalCompositeOperation = "source-in";
  997. const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  998. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  999. fillCtx.fillRect(0, 0, width, height);
  1000. if (cache && !isPatternFill) {
  1001. this.cachedCanvases.delete("fillCanvas");
  1002. cache.set(cacheKey, fillCanvas.canvas);
  1003. }
  1004. return {
  1005. canvas: fillCanvas.canvas,
  1006. offsetX: Math.round(offsetX),
  1007. offsetY: Math.round(offsetY)
  1008. };
  1009. }
  1010. setLineWidth(width) {
  1011. if (width !== this.current.lineWidth) {
  1012. this._cachedScaleForStroking = null;
  1013. }
  1014. this.current.lineWidth = width;
  1015. this.ctx.lineWidth = width;
  1016. }
  1017. setLineCap(style) {
  1018. this.ctx.lineCap = LINE_CAP_STYLES[style];
  1019. }
  1020. setLineJoin(style) {
  1021. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  1022. }
  1023. setMiterLimit(limit) {
  1024. this.ctx.miterLimit = limit;
  1025. }
  1026. setDash(dashArray, dashPhase) {
  1027. const ctx = this.ctx;
  1028. if (ctx.setLineDash !== undefined) {
  1029. ctx.setLineDash(dashArray);
  1030. ctx.lineDashOffset = dashPhase;
  1031. }
  1032. }
  1033. setRenderingIntent(intent) {}
  1034. setFlatness(flatness) {}
  1035. setGState(states) {
  1036. for (const [key, value] of states) {
  1037. switch (key) {
  1038. case "LW":
  1039. this.setLineWidth(value);
  1040. break;
  1041. case "LC":
  1042. this.setLineCap(value);
  1043. break;
  1044. case "LJ":
  1045. this.setLineJoin(value);
  1046. break;
  1047. case "ML":
  1048. this.setMiterLimit(value);
  1049. break;
  1050. case "D":
  1051. this.setDash(value[0], value[1]);
  1052. break;
  1053. case "RI":
  1054. this.setRenderingIntent(value);
  1055. break;
  1056. case "FL":
  1057. this.setFlatness(value);
  1058. break;
  1059. case "Font":
  1060. this.setFont(value[0], value[1]);
  1061. break;
  1062. case "CA":
  1063. this.current.strokeAlpha = value;
  1064. break;
  1065. case "ca":
  1066. this.current.fillAlpha = value;
  1067. this.ctx.globalAlpha = value;
  1068. break;
  1069. case "BM":
  1070. this.ctx.globalCompositeOperation = value;
  1071. break;
  1072. case "SMask":
  1073. this.current.activeSMask = value ? this.tempSMask : null;
  1074. this.tempSMask = null;
  1075. this.checkSMaskState();
  1076. break;
  1077. case "TR":
  1078. this.current.transferMaps = value;
  1079. }
  1080. }
  1081. }
  1082. get inSMaskMode() {
  1083. return !!this.suspendedCtx;
  1084. }
  1085. checkSMaskState() {
  1086. const inSMaskMode = this.inSMaskMode;
  1087. if (this.current.activeSMask && !inSMaskMode) {
  1088. this.beginSMaskMode();
  1089. } else if (!this.current.activeSMask && inSMaskMode) {
  1090. this.endSMaskMode();
  1091. }
  1092. }
  1093. beginSMaskMode() {
  1094. if (this.inSMaskMode) {
  1095. throw new Error("beginSMaskMode called while already in smask mode");
  1096. }
  1097. const drawnWidth = this.ctx.canvas.width;
  1098. const drawnHeight = this.ctx.canvas.height;
  1099. const cacheId = "smaskGroupAt" + this.groupLevel;
  1100. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  1101. this.suspendedCtx = this.ctx;
  1102. this.ctx = scratchCanvas.context;
  1103. const ctx = this.ctx;
  1104. ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
  1105. copyCtxState(this.suspendedCtx, ctx);
  1106. mirrorContextOperations(ctx, this.suspendedCtx);
  1107. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  1108. }
  1109. endSMaskMode() {
  1110. if (!this.inSMaskMode) {
  1111. throw new Error("endSMaskMode called while not in smask mode");
  1112. }
  1113. this.ctx._removeMirroring();
  1114. copyCtxState(this.ctx, this.suspendedCtx);
  1115. this.ctx = this.suspendedCtx;
  1116. this.suspendedCtx = null;
  1117. }
  1118. compose(dirtyBox) {
  1119. if (!this.current.activeSMask) {
  1120. return;
  1121. }
  1122. if (!dirtyBox) {
  1123. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  1124. } else {
  1125. dirtyBox[0] = Math.floor(dirtyBox[0]);
  1126. dirtyBox[1] = Math.floor(dirtyBox[1]);
  1127. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  1128. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  1129. }
  1130. const smask = this.current.activeSMask;
  1131. const suspendedCtx = this.suspendedCtx;
  1132. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  1133. this.ctx.save();
  1134. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  1135. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  1136. this.ctx.restore();
  1137. }
  1138. save() {
  1139. if (this.inSMaskMode) {
  1140. copyCtxState(this.ctx, this.suspendedCtx);
  1141. this.suspendedCtx.save();
  1142. } else {
  1143. this.ctx.save();
  1144. }
  1145. const old = this.current;
  1146. this.stateStack.push(old);
  1147. this.current = old.clone();
  1148. }
  1149. restore() {
  1150. if (this.stateStack.length === 0 && this.inSMaskMode) {
  1151. this.endSMaskMode();
  1152. }
  1153. if (this.stateStack.length !== 0) {
  1154. this.current = this.stateStack.pop();
  1155. if (this.inSMaskMode) {
  1156. this.suspendedCtx.restore();
  1157. copyCtxState(this.suspendedCtx, this.ctx);
  1158. } else {
  1159. this.ctx.restore();
  1160. }
  1161. this.checkSMaskState();
  1162. this.pendingClip = null;
  1163. this._cachedScaleForStroking = null;
  1164. this._cachedGetSinglePixelWidth = null;
  1165. }
  1166. }
  1167. transform(a, b, c, d, e, f) {
  1168. this.ctx.transform(a, b, c, d, e, f);
  1169. this._cachedScaleForStroking = null;
  1170. this._cachedGetSinglePixelWidth = null;
  1171. }
  1172. constructPath(ops, args, minMax) {
  1173. const ctx = this.ctx;
  1174. const current = this.current;
  1175. let x = current.x,
  1176. y = current.y;
  1177. let startX, startY;
  1178. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  1179. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  1180. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  1181. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  1182. switch (ops[i] | 0) {
  1183. case _util.OPS.rectangle:
  1184. x = args[j++];
  1185. y = args[j++];
  1186. const width = args[j++];
  1187. const height = args[j++];
  1188. const xw = x + width;
  1189. const yh = y + height;
  1190. ctx.moveTo(x, y);
  1191. if (width === 0 || height === 0) {
  1192. ctx.lineTo(xw, yh);
  1193. } else {
  1194. ctx.lineTo(xw, y);
  1195. ctx.lineTo(xw, yh);
  1196. ctx.lineTo(x, yh);
  1197. }
  1198. if (!isScalingMatrix) {
  1199. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  1200. }
  1201. ctx.closePath();
  1202. break;
  1203. case _util.OPS.moveTo:
  1204. x = args[j++];
  1205. y = args[j++];
  1206. ctx.moveTo(x, y);
  1207. if (!isScalingMatrix) {
  1208. current.updatePathMinMax(currentTransform, x, y);
  1209. }
  1210. break;
  1211. case _util.OPS.lineTo:
  1212. x = args[j++];
  1213. y = args[j++];
  1214. ctx.lineTo(x, y);
  1215. if (!isScalingMatrix) {
  1216. current.updatePathMinMax(currentTransform, x, y);
  1217. }
  1218. break;
  1219. case _util.OPS.curveTo:
  1220. startX = x;
  1221. startY = y;
  1222. x = args[j + 4];
  1223. y = args[j + 5];
  1224. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  1225. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  1226. j += 6;
  1227. break;
  1228. case _util.OPS.curveTo2:
  1229. startX = x;
  1230. startY = y;
  1231. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  1232. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  1233. x = args[j + 2];
  1234. y = args[j + 3];
  1235. j += 4;
  1236. break;
  1237. case _util.OPS.curveTo3:
  1238. startX = x;
  1239. startY = y;
  1240. x = args[j + 2];
  1241. y = args[j + 3];
  1242. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  1243. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  1244. j += 4;
  1245. break;
  1246. case _util.OPS.closePath:
  1247. ctx.closePath();
  1248. break;
  1249. }
  1250. }
  1251. if (isScalingMatrix) {
  1252. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  1253. }
  1254. current.setCurrentPoint(x, y);
  1255. }
  1256. closePath() {
  1257. this.ctx.closePath();
  1258. }
  1259. stroke(consumePath) {
  1260. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  1261. const ctx = this.ctx;
  1262. const strokeColor = this.current.strokeColor;
  1263. ctx.globalAlpha = this.current.strokeAlpha;
  1264. if (this.contentVisible) {
  1265. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  1266. ctx.save();
  1267. ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
  1268. this.rescaleAndStroke(false);
  1269. ctx.restore();
  1270. } else {
  1271. this.rescaleAndStroke(true);
  1272. }
  1273. }
  1274. if (consumePath) {
  1275. this.consumePath(this.current.getClippedPathBoundingBox());
  1276. }
  1277. ctx.globalAlpha = this.current.fillAlpha;
  1278. }
  1279. closeStroke() {
  1280. this.closePath();
  1281. this.stroke();
  1282. }
  1283. fill(consumePath) {
  1284. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  1285. const ctx = this.ctx;
  1286. const fillColor = this.current.fillColor;
  1287. const isPatternFill = this.current.patternFill;
  1288. let needRestore = false;
  1289. if (isPatternFill) {
  1290. ctx.save();
  1291. ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  1292. needRestore = true;
  1293. }
  1294. const intersect = this.current.getClippedPathBoundingBox();
  1295. if (this.contentVisible && intersect !== null) {
  1296. if (this.pendingEOFill) {
  1297. ctx.fill("evenodd");
  1298. this.pendingEOFill = false;
  1299. } else {
  1300. ctx.fill();
  1301. }
  1302. }
  1303. if (needRestore) {
  1304. ctx.restore();
  1305. }
  1306. if (consumePath) {
  1307. this.consumePath(intersect);
  1308. }
  1309. }
  1310. eoFill() {
  1311. this.pendingEOFill = true;
  1312. this.fill();
  1313. }
  1314. fillStroke() {
  1315. this.fill(false);
  1316. this.stroke(false);
  1317. this.consumePath();
  1318. }
  1319. eoFillStroke() {
  1320. this.pendingEOFill = true;
  1321. this.fillStroke();
  1322. }
  1323. closeFillStroke() {
  1324. this.closePath();
  1325. this.fillStroke();
  1326. }
  1327. closeEOFillStroke() {
  1328. this.pendingEOFill = true;
  1329. this.closePath();
  1330. this.fillStroke();
  1331. }
  1332. endPath() {
  1333. this.consumePath();
  1334. }
  1335. clip() {
  1336. this.pendingClip = NORMAL_CLIP;
  1337. }
  1338. eoClip() {
  1339. this.pendingClip = EO_CLIP;
  1340. }
  1341. beginText() {
  1342. this.current.textMatrix = _util.IDENTITY_MATRIX;
  1343. this.current.textMatrixScale = 1;
  1344. this.current.x = this.current.lineX = 0;
  1345. this.current.y = this.current.lineY = 0;
  1346. }
  1347. endText() {
  1348. const paths = this.pendingTextPaths;
  1349. const ctx = this.ctx;
  1350. if (paths === undefined) {
  1351. ctx.beginPath();
  1352. return;
  1353. }
  1354. ctx.save();
  1355. ctx.beginPath();
  1356. for (const path of paths) {
  1357. ctx.setTransform(...path.transform);
  1358. ctx.translate(path.x, path.y);
  1359. path.addToPath(ctx, path.fontSize);
  1360. }
  1361. ctx.restore();
  1362. ctx.clip();
  1363. ctx.beginPath();
  1364. delete this.pendingTextPaths;
  1365. }
  1366. setCharSpacing(spacing) {
  1367. this.current.charSpacing = spacing;
  1368. }
  1369. setWordSpacing(spacing) {
  1370. this.current.wordSpacing = spacing;
  1371. }
  1372. setHScale(scale) {
  1373. this.current.textHScale = scale / 100;
  1374. }
  1375. setLeading(leading) {
  1376. this.current.leading = -leading;
  1377. }
  1378. setFont(fontRefName, size) {
  1379. const fontObj = this.commonObjs.get(fontRefName);
  1380. const current = this.current;
  1381. if (!fontObj) {
  1382. throw new Error(`Can't find font for ${fontRefName}`);
  1383. }
  1384. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1385. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  1386. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  1387. }
  1388. if (size < 0) {
  1389. size = -size;
  1390. current.fontDirection = -1;
  1391. } else {
  1392. current.fontDirection = 1;
  1393. }
  1394. this.current.font = fontObj;
  1395. this.current.fontSize = size;
  1396. if (fontObj.isType3Font) {
  1397. return;
  1398. }
  1399. const name = fontObj.loadedName || "sans-serif";
  1400. let bold = "normal";
  1401. if (fontObj.black) {
  1402. bold = "900";
  1403. } else if (fontObj.bold) {
  1404. bold = "bold";
  1405. }
  1406. const italic = fontObj.italic ? "italic" : "normal";
  1407. const typeface = `"${name}", ${fontObj.fallbackName}`;
  1408. let browserFontSize = size;
  1409. if (size < MIN_FONT_SIZE) {
  1410. browserFontSize = MIN_FONT_SIZE;
  1411. } else if (size > MAX_FONT_SIZE) {
  1412. browserFontSize = MAX_FONT_SIZE;
  1413. }
  1414. this.current.fontSizeScale = size / browserFontSize;
  1415. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  1416. }
  1417. setTextRenderingMode(mode) {
  1418. this.current.textRenderingMode = mode;
  1419. }
  1420. setTextRise(rise) {
  1421. this.current.textRise = rise;
  1422. }
  1423. moveText(x, y) {
  1424. this.current.x = this.current.lineX += x;
  1425. this.current.y = this.current.lineY += y;
  1426. }
  1427. setLeadingMoveText(x, y) {
  1428. this.setLeading(-y);
  1429. this.moveText(x, y);
  1430. }
  1431. setTextMatrix(a, b, c, d, e, f) {
  1432. this.current.textMatrix = [a, b, c, d, e, f];
  1433. this.current.textMatrixScale = Math.hypot(a, b);
  1434. this.current.x = this.current.lineX = 0;
  1435. this.current.y = this.current.lineY = 0;
  1436. }
  1437. nextLine() {
  1438. this.moveText(0, this.current.leading);
  1439. }
  1440. paintChar(character, x, y, patternTransform) {
  1441. const ctx = this.ctx;
  1442. const current = this.current;
  1443. const font = current.font;
  1444. const textRenderingMode = current.textRenderingMode;
  1445. const fontSize = current.fontSize / current.fontSizeScale;
  1446. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1447. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  1448. const patternFill = current.patternFill && !font.missingFile;
  1449. let addToPath;
  1450. if (font.disableFontFace || isAddToPathSet || patternFill) {
  1451. addToPath = font.getPathGenerator(this.commonObjs, character);
  1452. }
  1453. if (font.disableFontFace || patternFill) {
  1454. ctx.save();
  1455. ctx.translate(x, y);
  1456. ctx.beginPath();
  1457. addToPath(ctx, fontSize);
  1458. if (patternTransform) {
  1459. ctx.setTransform(...patternTransform);
  1460. }
  1461. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1462. ctx.fill();
  1463. }
  1464. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1465. ctx.stroke();
  1466. }
  1467. ctx.restore();
  1468. } else {
  1469. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1470. ctx.fillText(character, x, y);
  1471. }
  1472. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1473. ctx.strokeText(character, x, y);
  1474. }
  1475. }
  1476. if (isAddToPathSet) {
  1477. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  1478. paths.push({
  1479. transform: (0, _display_utils.getCurrentTransform)(ctx),
  1480. x,
  1481. y,
  1482. fontSize,
  1483. addToPath
  1484. });
  1485. }
  1486. }
  1487. get isFontSubpixelAAEnabled() {
  1488. const {
  1489. context: ctx
  1490. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  1491. ctx.scale(1.5, 1);
  1492. ctx.fillText("I", 0, 10);
  1493. const data = ctx.getImageData(0, 0, 10, 10).data;
  1494. let enabled = false;
  1495. for (let i = 3; i < data.length; i += 4) {
  1496. if (data[i] > 0 && data[i] < 255) {
  1497. enabled = true;
  1498. break;
  1499. }
  1500. }
  1501. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  1502. }
  1503. showText(glyphs) {
  1504. const current = this.current;
  1505. const font = current.font;
  1506. if (font.isType3Font) {
  1507. return this.showType3Text(glyphs);
  1508. }
  1509. const fontSize = current.fontSize;
  1510. if (fontSize === 0) {
  1511. return undefined;
  1512. }
  1513. const ctx = this.ctx;
  1514. const fontSizeScale = current.fontSizeScale;
  1515. const charSpacing = current.charSpacing;
  1516. const wordSpacing = current.wordSpacing;
  1517. const fontDirection = current.fontDirection;
  1518. const textHScale = current.textHScale * fontDirection;
  1519. const glyphsLength = glyphs.length;
  1520. const vertical = font.vertical;
  1521. const spacingDir = vertical ? 1 : -1;
  1522. const defaultVMetrics = font.defaultVMetrics;
  1523. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  1524. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  1525. ctx.save();
  1526. ctx.transform(...current.textMatrix);
  1527. ctx.translate(current.x, current.y + current.textRise);
  1528. if (fontDirection > 0) {
  1529. ctx.scale(textHScale, -1);
  1530. } else {
  1531. ctx.scale(textHScale, 1);
  1532. }
  1533. let patternTransform;
  1534. if (current.patternFill) {
  1535. ctx.save();
  1536. const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  1537. patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
  1538. ctx.restore();
  1539. ctx.fillStyle = pattern;
  1540. }
  1541. let lineWidth = current.lineWidth;
  1542. const scale = current.textMatrixScale;
  1543. if (scale === 0 || lineWidth === 0) {
  1544. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1545. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1546. lineWidth = this.getSinglePixelWidth();
  1547. }
  1548. } else {
  1549. lineWidth /= scale;
  1550. }
  1551. if (fontSizeScale !== 1.0) {
  1552. ctx.scale(fontSizeScale, fontSizeScale);
  1553. lineWidth /= fontSizeScale;
  1554. }
  1555. ctx.lineWidth = lineWidth;
  1556. if (font.isInvalidPDFjsFont) {
  1557. const chars = [];
  1558. let width = 0;
  1559. for (const glyph of glyphs) {
  1560. chars.push(glyph.unicode);
  1561. width += glyph.width;
  1562. }
  1563. ctx.fillText(chars.join(""), 0, 0);
  1564. current.x += width * widthAdvanceScale * textHScale;
  1565. ctx.restore();
  1566. this.compose();
  1567. return undefined;
  1568. }
  1569. let x = 0,
  1570. i;
  1571. for (i = 0; i < glyphsLength; ++i) {
  1572. const glyph = glyphs[i];
  1573. if (typeof glyph === "number") {
  1574. x += spacingDir * glyph * fontSize / 1000;
  1575. continue;
  1576. }
  1577. let restoreNeeded = false;
  1578. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1579. const character = glyph.fontChar;
  1580. const accent = glyph.accent;
  1581. let scaledX, scaledY;
  1582. let width = glyph.width;
  1583. if (vertical) {
  1584. const vmetric = glyph.vmetric || defaultVMetrics;
  1585. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  1586. const vy = vmetric[2] * widthAdvanceScale;
  1587. width = vmetric ? -vmetric[0] : width;
  1588. scaledX = vx / fontSizeScale;
  1589. scaledY = (x + vy) / fontSizeScale;
  1590. } else {
  1591. scaledX = x / fontSizeScale;
  1592. scaledY = 0;
  1593. }
  1594. if (font.remeasure && width > 0) {
  1595. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  1596. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  1597. const characterScaleX = width / measuredWidth;
  1598. restoreNeeded = true;
  1599. ctx.save();
  1600. ctx.scale(characterScaleX, 1);
  1601. scaledX /= characterScaleX;
  1602. } else if (width !== measuredWidth) {
  1603. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  1604. }
  1605. }
  1606. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  1607. if (simpleFillText && !accent) {
  1608. ctx.fillText(character, scaledX, scaledY);
  1609. } else {
  1610. this.paintChar(character, scaledX, scaledY, patternTransform);
  1611. if (accent) {
  1612. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  1613. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  1614. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  1615. }
  1616. }
  1617. }
  1618. let charWidth;
  1619. if (vertical) {
  1620. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  1621. } else {
  1622. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  1623. }
  1624. x += charWidth;
  1625. if (restoreNeeded) {
  1626. ctx.restore();
  1627. }
  1628. }
  1629. if (vertical) {
  1630. current.y -= x;
  1631. } else {
  1632. current.x += x * textHScale;
  1633. }
  1634. ctx.restore();
  1635. this.compose();
  1636. return undefined;
  1637. }
  1638. showType3Text(glyphs) {
  1639. const ctx = this.ctx;
  1640. const current = this.current;
  1641. const font = current.font;
  1642. const fontSize = current.fontSize;
  1643. const fontDirection = current.fontDirection;
  1644. const spacingDir = font.vertical ? 1 : -1;
  1645. const charSpacing = current.charSpacing;
  1646. const wordSpacing = current.wordSpacing;
  1647. const textHScale = current.textHScale * fontDirection;
  1648. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1649. const glyphsLength = glyphs.length;
  1650. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  1651. let i, glyph, width, spacingLength;
  1652. if (isTextInvisible || fontSize === 0) {
  1653. return;
  1654. }
  1655. this._cachedScaleForStroking = null;
  1656. this._cachedGetSinglePixelWidth = null;
  1657. ctx.save();
  1658. ctx.transform(...current.textMatrix);
  1659. ctx.translate(current.x, current.y);
  1660. ctx.scale(textHScale, fontDirection);
  1661. for (i = 0; i < glyphsLength; ++i) {
  1662. glyph = glyphs[i];
  1663. if (typeof glyph === "number") {
  1664. spacingLength = spacingDir * glyph * fontSize / 1000;
  1665. this.ctx.translate(spacingLength, 0);
  1666. current.x += spacingLength * textHScale;
  1667. continue;
  1668. }
  1669. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1670. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  1671. if (!operatorList) {
  1672. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  1673. continue;
  1674. }
  1675. if (this.contentVisible) {
  1676. this.processingType3 = glyph;
  1677. this.save();
  1678. ctx.scale(fontSize, fontSize);
  1679. ctx.transform(...fontMatrix);
  1680. this.executeOperatorList(operatorList);
  1681. this.restore();
  1682. }
  1683. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  1684. width = transformed[0] * fontSize + spacing;
  1685. ctx.translate(width, 0);
  1686. current.x += width * textHScale;
  1687. }
  1688. ctx.restore();
  1689. this.processingType3 = null;
  1690. }
  1691. setCharWidth(xWidth, yWidth) {}
  1692. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  1693. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  1694. this.ctx.clip();
  1695. this.endPath();
  1696. }
  1697. getColorN_Pattern(IR) {
  1698. let pattern;
  1699. if (IR[0] === "TilingPattern") {
  1700. const color = IR[1];
  1701. const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
  1702. const canvasGraphicsFactory = {
  1703. createCanvasGraphics: ctx => {
  1704. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, {
  1705. optionalContentConfig: this.optionalContentConfig,
  1706. markedContentStack: this.markedContentStack
  1707. });
  1708. }
  1709. };
  1710. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  1711. } else {
  1712. pattern = this._getPattern(IR[1], IR[2]);
  1713. }
  1714. return pattern;
  1715. }
  1716. setStrokeColorN() {
  1717. this.current.strokeColor = this.getColorN_Pattern(arguments);
  1718. }
  1719. setFillColorN() {
  1720. this.current.fillColor = this.getColorN_Pattern(arguments);
  1721. this.current.patternFill = true;
  1722. }
  1723. setStrokeRGBColor(r, g, b) {
  1724. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  1725. this.ctx.strokeStyle = color;
  1726. this.current.strokeColor = color;
  1727. }
  1728. setFillRGBColor(r, g, b) {
  1729. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  1730. this.ctx.fillStyle = color;
  1731. this.current.fillColor = color;
  1732. this.current.patternFill = false;
  1733. }
  1734. _getPattern(objId, matrix = null) {
  1735. let pattern;
  1736. if (this.cachedPatterns.has(objId)) {
  1737. pattern = this.cachedPatterns.get(objId);
  1738. } else {
  1739. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  1740. this.cachedPatterns.set(objId, pattern);
  1741. }
  1742. if (matrix) {
  1743. pattern.matrix = matrix;
  1744. }
  1745. return pattern;
  1746. }
  1747. shadingFill(objId) {
  1748. if (!this.contentVisible) {
  1749. return;
  1750. }
  1751. const ctx = this.ctx;
  1752. this.save();
  1753. const pattern = this._getPattern(objId);
  1754. ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
  1755. const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
  1756. if (inv) {
  1757. const canvas = ctx.canvas;
  1758. const width = canvas.width;
  1759. const height = canvas.height;
  1760. const bl = _util.Util.applyTransform([0, 0], inv);
  1761. const br = _util.Util.applyTransform([0, height], inv);
  1762. const ul = _util.Util.applyTransform([width, 0], inv);
  1763. const ur = _util.Util.applyTransform([width, height], inv);
  1764. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  1765. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  1766. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  1767. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  1768. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  1769. } else {
  1770. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  1771. }
  1772. this.compose(this.current.getClippedPathBoundingBox());
  1773. this.restore();
  1774. }
  1775. beginInlineImage() {
  1776. (0, _util.unreachable)("Should not call beginInlineImage");
  1777. }
  1778. beginImageData() {
  1779. (0, _util.unreachable)("Should not call beginImageData");
  1780. }
  1781. paintFormXObjectBegin(matrix, bbox) {
  1782. if (!this.contentVisible) {
  1783. return;
  1784. }
  1785. this.save();
  1786. this.baseTransformStack.push(this.baseTransform);
  1787. if (Array.isArray(matrix) && matrix.length === 6) {
  1788. this.transform(...matrix);
  1789. }
  1790. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  1791. if (bbox) {
  1792. const width = bbox[2] - bbox[0];
  1793. const height = bbox[3] - bbox[1];
  1794. this.ctx.rect(bbox[0], bbox[1], width, height);
  1795. this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
  1796. this.clip();
  1797. this.endPath();
  1798. }
  1799. }
  1800. paintFormXObjectEnd() {
  1801. if (!this.contentVisible) {
  1802. return;
  1803. }
  1804. this.restore();
  1805. this.baseTransform = this.baseTransformStack.pop();
  1806. }
  1807. beginGroup(group) {
  1808. if (!this.contentVisible) {
  1809. return;
  1810. }
  1811. this.save();
  1812. if (this.inSMaskMode) {
  1813. this.endSMaskMode();
  1814. this.current.activeSMask = null;
  1815. }
  1816. const currentCtx = this.ctx;
  1817. if (!group.isolated) {
  1818. (0, _util.info)("TODO: Support non-isolated groups.");
  1819. }
  1820. if (group.knockout) {
  1821. (0, _util.warn)("Knockout groups not supported.");
  1822. }
  1823. const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
  1824. if (group.matrix) {
  1825. currentCtx.transform(...group.matrix);
  1826. }
  1827. if (!group.bbox) {
  1828. throw new Error("Bounding box is required.");
  1829. }
  1830. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
  1831. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  1832. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  1833. const offsetX = Math.floor(bounds[0]);
  1834. const offsetY = Math.floor(bounds[1]);
  1835. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  1836. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  1837. let scaleX = 1,
  1838. scaleY = 1;
  1839. if (drawnWidth > MAX_GROUP_SIZE) {
  1840. scaleX = drawnWidth / MAX_GROUP_SIZE;
  1841. drawnWidth = MAX_GROUP_SIZE;
  1842. }
  1843. if (drawnHeight > MAX_GROUP_SIZE) {
  1844. scaleY = drawnHeight / MAX_GROUP_SIZE;
  1845. drawnHeight = MAX_GROUP_SIZE;
  1846. }
  1847. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  1848. let cacheId = "groupAt" + this.groupLevel;
  1849. if (group.smask) {
  1850. cacheId += "_smask_" + this.smaskCounter++ % 2;
  1851. }
  1852. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  1853. const groupCtx = scratchCanvas.context;
  1854. groupCtx.scale(1 / scaleX, 1 / scaleY);
  1855. groupCtx.translate(-offsetX, -offsetY);
  1856. groupCtx.transform(...currentTransform);
  1857. if (group.smask) {
  1858. this.smaskStack.push({
  1859. canvas: scratchCanvas.canvas,
  1860. context: groupCtx,
  1861. offsetX,
  1862. offsetY,
  1863. scaleX,
  1864. scaleY,
  1865. subtype: group.smask.subtype,
  1866. backdrop: group.smask.backdrop,
  1867. transferMap: group.smask.transferMap || null,
  1868. startTransformInverse: null
  1869. });
  1870. } else {
  1871. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  1872. currentCtx.translate(offsetX, offsetY);
  1873. currentCtx.scale(scaleX, scaleY);
  1874. currentCtx.save();
  1875. }
  1876. copyCtxState(currentCtx, groupCtx);
  1877. this.ctx = groupCtx;
  1878. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  1879. this.groupStack.push(currentCtx);
  1880. this.groupLevel++;
  1881. }
  1882. endGroup(group) {
  1883. if (!this.contentVisible) {
  1884. return;
  1885. }
  1886. this.groupLevel--;
  1887. const groupCtx = this.ctx;
  1888. const ctx = this.groupStack.pop();
  1889. this.ctx = ctx;
  1890. this.ctx.imageSmoothingEnabled = false;
  1891. if (group.smask) {
  1892. this.tempSMask = this.smaskStack.pop();
  1893. this.restore();
  1894. } else {
  1895. this.ctx.restore();
  1896. const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
  1897. this.restore();
  1898. this.ctx.save();
  1899. this.ctx.setTransform(...currentMtx);
  1900. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  1901. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  1902. this.ctx.restore();
  1903. this.compose(dirtyBox);
  1904. }
  1905. }
  1906. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  1907. this.#restoreInitialState();
  1908. resetCtxToDefault(this.ctx, this.foregroundColor);
  1909. this.ctx.save();
  1910. this.save();
  1911. if (this.baseTransform) {
  1912. this.ctx.setTransform(...this.baseTransform);
  1913. }
  1914. if (Array.isArray(rect) && rect.length === 4) {
  1915. const width = rect[2] - rect[0];
  1916. const height = rect[3] - rect[1];
  1917. if (hasOwnCanvas && this.annotationCanvasMap) {
  1918. transform = transform.slice();
  1919. transform[4] -= rect[0];
  1920. transform[5] -= rect[1];
  1921. rect = rect.slice();
  1922. rect[0] = rect[1] = 0;
  1923. rect[2] = width;
  1924. rect[3] = height;
  1925. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
  1926. const {
  1927. viewportScale
  1928. } = this;
  1929. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  1930. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  1931. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  1932. const {
  1933. canvas,
  1934. context
  1935. } = this.annotationCanvas;
  1936. this.annotationCanvasMap.set(id, canvas);
  1937. this.annotationCanvas.savedCtx = this.ctx;
  1938. this.ctx = context;
  1939. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  1940. resetCtxToDefault(this.ctx, this.foregroundColor);
  1941. } else {
  1942. resetCtxToDefault(this.ctx, this.foregroundColor);
  1943. this.ctx.rect(rect[0], rect[1], width, height);
  1944. this.ctx.clip();
  1945. this.endPath();
  1946. }
  1947. }
  1948. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  1949. this.transform(...transform);
  1950. this.transform(...matrix);
  1951. }
  1952. endAnnotation() {
  1953. if (this.annotationCanvas) {
  1954. this.ctx = this.annotationCanvas.savedCtx;
  1955. delete this.annotationCanvas.savedCtx;
  1956. delete this.annotationCanvas;
  1957. }
  1958. }
  1959. paintImageMaskXObject(img) {
  1960. if (!this.contentVisible) {
  1961. return;
  1962. }
  1963. const count = img.count;
  1964. img = this.getObject(img.data, img);
  1965. img.count = count;
  1966. const ctx = this.ctx;
  1967. const glyph = this.processingType3;
  1968. if (glyph) {
  1969. if (glyph.compiled === undefined) {
  1970. glyph.compiled = compileType3Glyph(img);
  1971. }
  1972. if (glyph.compiled) {
  1973. glyph.compiled(ctx);
  1974. return;
  1975. }
  1976. }
  1977. const mask = this._createMaskCanvas(img);
  1978. const maskCanvas = mask.canvas;
  1979. ctx.save();
  1980. ctx.setTransform(1, 0, 0, 1, 0, 0);
  1981. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  1982. ctx.restore();
  1983. this.compose();
  1984. }
  1985. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  1986. if (!this.contentVisible) {
  1987. return;
  1988. }
  1989. img = this.getObject(img.data, img);
  1990. const ctx = this.ctx;
  1991. ctx.save();
  1992. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  1993. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  1994. const mask = this._createMaskCanvas(img);
  1995. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  1996. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  1997. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  1998. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  1999. ctx.drawImage(mask.canvas, x, y);
  2000. }
  2001. ctx.restore();
  2002. this.compose();
  2003. }
  2004. paintImageMaskXObjectGroup(images) {
  2005. if (!this.contentVisible) {
  2006. return;
  2007. }
  2008. const ctx = this.ctx;
  2009. const fillColor = this.current.fillColor;
  2010. const isPatternFill = this.current.patternFill;
  2011. for (const image of images) {
  2012. const {
  2013. data,
  2014. width,
  2015. height,
  2016. transform
  2017. } = image;
  2018. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  2019. const maskCtx = maskCanvas.context;
  2020. maskCtx.save();
  2021. const img = this.getObject(data, image);
  2022. putBinaryImageMask(maskCtx, img);
  2023. maskCtx.globalCompositeOperation = "source-in";
  2024. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
  2025. maskCtx.fillRect(0, 0, width, height);
  2026. maskCtx.restore();
  2027. ctx.save();
  2028. ctx.transform(...transform);
  2029. ctx.scale(1, -1);
  2030. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  2031. ctx.restore();
  2032. }
  2033. this.compose();
  2034. }
  2035. paintImageXObject(objId) {
  2036. if (!this.contentVisible) {
  2037. return;
  2038. }
  2039. const imgData = this.getObject(objId);
  2040. if (!imgData) {
  2041. (0, _util.warn)("Dependent image isn't ready yet");
  2042. return;
  2043. }
  2044. this.paintInlineImageXObject(imgData);
  2045. }
  2046. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  2047. if (!this.contentVisible) {
  2048. return;
  2049. }
  2050. const imgData = this.getObject(objId);
  2051. if (!imgData) {
  2052. (0, _util.warn)("Dependent image isn't ready yet");
  2053. return;
  2054. }
  2055. const width = imgData.width;
  2056. const height = imgData.height;
  2057. const map = [];
  2058. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  2059. map.push({
  2060. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  2061. x: 0,
  2062. y: 0,
  2063. w: width,
  2064. h: height
  2065. });
  2066. }
  2067. this.paintInlineImageXObjectGroup(imgData, map);
  2068. }
  2069. paintInlineImageXObject(imgData) {
  2070. if (!this.contentVisible) {
  2071. return;
  2072. }
  2073. const width = imgData.width;
  2074. const height = imgData.height;
  2075. const ctx = this.ctx;
  2076. this.save();
  2077. ctx.scale(1 / width, -1 / height);
  2078. let imgToPaint;
  2079. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  2080. imgToPaint = imgData;
  2081. } else {
  2082. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  2083. const tmpCtx = tmpCanvas.context;
  2084. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  2085. imgToPaint = tmpCanvas.canvas;
  2086. }
  2087. const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
  2088. ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
  2089. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  2090. this.compose();
  2091. this.restore();
  2092. }
  2093. paintInlineImageXObjectGroup(imgData, map) {
  2094. if (!this.contentVisible) {
  2095. return;
  2096. }
  2097. const ctx = this.ctx;
  2098. const w = imgData.width;
  2099. const h = imgData.height;
  2100. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  2101. const tmpCtx = tmpCanvas.context;
  2102. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  2103. for (const entry of map) {
  2104. ctx.save();
  2105. ctx.transform(...entry.transform);
  2106. ctx.scale(1, -1);
  2107. drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  2108. ctx.restore();
  2109. }
  2110. this.compose();
  2111. }
  2112. paintSolidColorImageMask() {
  2113. if (!this.contentVisible) {
  2114. return;
  2115. }
  2116. this.ctx.fillRect(0, 0, 1, 1);
  2117. this.compose();
  2118. }
  2119. markPoint(tag) {}
  2120. markPointProps(tag, properties) {}
  2121. beginMarkedContent(tag) {
  2122. this.markedContentStack.push({
  2123. visible: true
  2124. });
  2125. }
  2126. beginMarkedContentProps(tag, properties) {
  2127. if (tag === "OC") {
  2128. this.markedContentStack.push({
  2129. visible: this.optionalContentConfig.isVisible(properties)
  2130. });
  2131. } else {
  2132. this.markedContentStack.push({
  2133. visible: true
  2134. });
  2135. }
  2136. this.contentVisible = this.isContentVisible();
  2137. }
  2138. endMarkedContent() {
  2139. this.markedContentStack.pop();
  2140. this.contentVisible = this.isContentVisible();
  2141. }
  2142. beginCompat() {}
  2143. endCompat() {}
  2144. consumePath(clipBox) {
  2145. const isEmpty = this.current.isEmptyClip();
  2146. if (this.pendingClip) {
  2147. this.current.updateClipFromPath();
  2148. }
  2149. if (!this.pendingClip) {
  2150. this.compose(clipBox);
  2151. }
  2152. const ctx = this.ctx;
  2153. if (this.pendingClip) {
  2154. if (!isEmpty) {
  2155. if (this.pendingClip === EO_CLIP) {
  2156. ctx.clip("evenodd");
  2157. } else {
  2158. ctx.clip();
  2159. }
  2160. }
  2161. this.pendingClip = null;
  2162. }
  2163. this.current.startNewPathAndClipBox(this.current.clipBox);
  2164. ctx.beginPath();
  2165. }
  2166. getSinglePixelWidth() {
  2167. if (!this._cachedGetSinglePixelWidth) {
  2168. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  2169. if (m[1] === 0 && m[2] === 0) {
  2170. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  2171. } else {
  2172. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  2173. const normX = Math.hypot(m[0], m[2]);
  2174. const normY = Math.hypot(m[1], m[3]);
  2175. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  2176. }
  2177. }
  2178. return this._cachedGetSinglePixelWidth;
  2179. }
  2180. getScaleForStroking() {
  2181. if (!this._cachedScaleForStroking) {
  2182. const {
  2183. lineWidth
  2184. } = this.current;
  2185. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  2186. let scaleX, scaleY;
  2187. if (m[1] === 0 && m[2] === 0) {
  2188. const normX = Math.abs(m[0]);
  2189. const normY = Math.abs(m[3]);
  2190. if (lineWidth === 0) {
  2191. scaleX = 1 / normX;
  2192. scaleY = 1 / normY;
  2193. } else {
  2194. const scaledXLineWidth = normX * lineWidth;
  2195. const scaledYLineWidth = normY * lineWidth;
  2196. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  2197. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  2198. }
  2199. } else {
  2200. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  2201. const normX = Math.hypot(m[0], m[1]);
  2202. const normY = Math.hypot(m[2], m[3]);
  2203. if (lineWidth === 0) {
  2204. scaleX = normY / absDet;
  2205. scaleY = normX / absDet;
  2206. } else {
  2207. const baseArea = lineWidth * absDet;
  2208. scaleX = normY > baseArea ? normY / baseArea : 1;
  2209. scaleY = normX > baseArea ? normX / baseArea : 1;
  2210. }
  2211. }
  2212. this._cachedScaleForStroking = [scaleX, scaleY];
  2213. }
  2214. return this._cachedScaleForStroking;
  2215. }
  2216. rescaleAndStroke(saveRestore) {
  2217. const {
  2218. ctx
  2219. } = this;
  2220. const {
  2221. lineWidth
  2222. } = this.current;
  2223. const [scaleX, scaleY] = this.getScaleForStroking();
  2224. ctx.lineWidth = lineWidth || 1;
  2225. if (scaleX === 1 && scaleY === 1) {
  2226. ctx.stroke();
  2227. return;
  2228. }
  2229. let savedMatrix, savedDashes, savedDashOffset;
  2230. if (saveRestore) {
  2231. savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
  2232. savedDashes = ctx.getLineDash().slice();
  2233. savedDashOffset = ctx.lineDashOffset;
  2234. }
  2235. ctx.scale(scaleX, scaleY);
  2236. const scale = Math.max(scaleX, scaleY);
  2237. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  2238. ctx.lineDashOffset /= scale;
  2239. ctx.stroke();
  2240. if (saveRestore) {
  2241. ctx.setTransform(...savedMatrix);
  2242. ctx.setLineDash(savedDashes);
  2243. ctx.lineDashOffset = savedDashOffset;
  2244. }
  2245. }
  2246. isContentVisible() {
  2247. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  2248. if (!this.markedContentStack[i].visible) {
  2249. return false;
  2250. }
  2251. }
  2252. return true;
  2253. }
  2254. }
  2255. exports.CanvasGraphics = CanvasGraphics;
  2256. for (const op in _util.OPS) {
  2257. if (CanvasGraphics.prototype[op] !== undefined) {
  2258. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  2259. }
  2260. }