canvas.js 69 KB

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