2
0

canvas.js 75 KB

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