2
0

canvas.js 80 KB

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