canvas.js 76 KB

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