canvas.js 64 KB

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