2
0

canvas.js 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  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 _pattern_helper = require("./pattern_helper.js");
  29. var _image_utils = require("../shared/image_utils.js");
  30. var _is_node = require("../shared/is_node.js");
  31. var _display_utils = require("./display_utils.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 cB = parseInt(defaultBg.slice(1), 16);
  929. const rB = (cB && 0xff0000) >> 16;
  930. const gB = (cB && 0x00ff00) >> 8;
  931. const bB = cB && 0x0000ff;
  932. const newComp = x => {
  933. x /= 255;
  934. return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  935. };
  936. const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
  937. this.selectColor = (r, g, b) => {
  938. const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
  939. return Math.round(lumC) === lumB ? bg : fg;
  940. };
  941. }
  942. }
  943. this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
  944. this.ctx.fillRect(0, 0, width, height);
  945. this.ctx.restore();
  946. if (transparency) {
  947. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
  948. this.compositeCtx = this.ctx;
  949. this.transparentCanvas = transparentCanvas.canvas;
  950. this.ctx = transparentCanvas.context;
  951. this.ctx.save();
  952. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  953. }
  954. this.ctx.save();
  955. resetCtxToDefault(this.ctx, this.foregroundColor);
  956. if (transform) {
  957. this.ctx.transform.apply(this.ctx, transform);
  958. this.outputScaleX = transform[0];
  959. this.outputScaleY = transform[0];
  960. }
  961. this.ctx.transform.apply(this.ctx, viewport.transform);
  962. this.viewportScale = viewport.scale;
  963. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  964. if (this.imageLayer) {
  965. this.imageLayer.beginLayout();
  966. }
  967. }
  968. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  969. const argsArray = operatorList.argsArray;
  970. const fnArray = operatorList.fnArray;
  971. let i = executionStartIdx || 0;
  972. const argsArrayLen = argsArray.length;
  973. if (argsArrayLen === i) {
  974. return i;
  975. }
  976. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  977. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  978. let steps = 0;
  979. const commonObjs = this.commonObjs;
  980. const objs = this.objs;
  981. let fnId;
  982. while (true) {
  983. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  984. stepper.breakIt(i, continueCallback);
  985. return i;
  986. }
  987. fnId = fnArray[i];
  988. if (fnId !== _util.OPS.dependency) {
  989. this[fnId].apply(this, argsArray[i]);
  990. } else {
  991. for (const depObjId of argsArray[i]) {
  992. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  993. if (!objsPool.has(depObjId)) {
  994. objsPool.get(depObjId, continueCallback);
  995. return i;
  996. }
  997. }
  998. }
  999. i++;
  1000. if (i === argsArrayLen) {
  1001. return i;
  1002. }
  1003. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  1004. if (Date.now() > endTime) {
  1005. continueCallback();
  1006. return i;
  1007. }
  1008. steps = 0;
  1009. }
  1010. }
  1011. }
  1012. endDrawing() {
  1013. while (this.stateStack.length || this.inSMaskMode) {
  1014. this.restore();
  1015. }
  1016. this.ctx.restore();
  1017. if (this.transparentCanvas) {
  1018. this.ctx = this.compositeCtx;
  1019. this.ctx.save();
  1020. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  1021. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  1022. this.ctx.restore();
  1023. this.transparentCanvas = null;
  1024. }
  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 (let i = 0; i < paths.length; i++) {
  1496. const path = paths[i];
  1497. ctx.setTransform.apply(ctx, path.transform);
  1498. ctx.translate(path.x, path.y);
  1499. path.addToPath(ctx, path.fontSize);
  1500. }
  1501. ctx.restore();
  1502. ctx.clip();
  1503. ctx.beginPath();
  1504. delete this.pendingTextPaths;
  1505. }
  1506. setCharSpacing(spacing) {
  1507. this.current.charSpacing = spacing;
  1508. }
  1509. setWordSpacing(spacing) {
  1510. this.current.wordSpacing = spacing;
  1511. }
  1512. setHScale(scale) {
  1513. this.current.textHScale = scale / 100;
  1514. }
  1515. setLeading(leading) {
  1516. this.current.leading = -leading;
  1517. }
  1518. setFont(fontRefName, size) {
  1519. const fontObj = this.commonObjs.get(fontRefName);
  1520. const current = this.current;
  1521. if (!fontObj) {
  1522. throw new Error(`Can't find font for ${fontRefName}`);
  1523. }
  1524. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1525. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  1526. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  1527. }
  1528. if (size < 0) {
  1529. size = -size;
  1530. current.fontDirection = -1;
  1531. } else {
  1532. current.fontDirection = 1;
  1533. }
  1534. this.current.font = fontObj;
  1535. this.current.fontSize = size;
  1536. if (fontObj.isType3Font) {
  1537. return;
  1538. }
  1539. const name = fontObj.loadedName || "sans-serif";
  1540. let bold = "normal";
  1541. if (fontObj.black) {
  1542. bold = "900";
  1543. } else if (fontObj.bold) {
  1544. bold = "bold";
  1545. }
  1546. const italic = fontObj.italic ? "italic" : "normal";
  1547. const typeface = `"${name}", ${fontObj.fallbackName}`;
  1548. let browserFontSize = size;
  1549. if (size < MIN_FONT_SIZE) {
  1550. browserFontSize = MIN_FONT_SIZE;
  1551. } else if (size > MAX_FONT_SIZE) {
  1552. browserFontSize = MAX_FONT_SIZE;
  1553. }
  1554. this.current.fontSizeScale = size / browserFontSize;
  1555. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  1556. }
  1557. setTextRenderingMode(mode) {
  1558. this.current.textRenderingMode = mode;
  1559. }
  1560. setTextRise(rise) {
  1561. this.current.textRise = rise;
  1562. }
  1563. moveText(x, y) {
  1564. this.current.x = this.current.lineX += x;
  1565. this.current.y = this.current.lineY += y;
  1566. }
  1567. setLeadingMoveText(x, y) {
  1568. this.setLeading(-y);
  1569. this.moveText(x, y);
  1570. }
  1571. setTextMatrix(a, b, c, d, e, f) {
  1572. this.current.textMatrix = [a, b, c, d, e, f];
  1573. this.current.textMatrixScale = Math.hypot(a, b);
  1574. this.current.x = this.current.lineX = 0;
  1575. this.current.y = this.current.lineY = 0;
  1576. }
  1577. nextLine() {
  1578. this.moveText(0, this.current.leading);
  1579. }
  1580. paintChar(character, x, y, patternTransform) {
  1581. const ctx = this.ctx;
  1582. const current = this.current;
  1583. const font = current.font;
  1584. const textRenderingMode = current.textRenderingMode;
  1585. const fontSize = current.fontSize / current.fontSizeScale;
  1586. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1587. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  1588. const patternFill = current.patternFill && !font.missingFile;
  1589. let addToPath;
  1590. if (font.disableFontFace || isAddToPathSet || patternFill) {
  1591. addToPath = font.getPathGenerator(this.commonObjs, character);
  1592. }
  1593. if (font.disableFontFace || patternFill) {
  1594. ctx.save();
  1595. ctx.translate(x, y);
  1596. ctx.beginPath();
  1597. addToPath(ctx, fontSize);
  1598. if (patternTransform) {
  1599. ctx.setTransform.apply(ctx, patternTransform);
  1600. }
  1601. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1602. ctx.fill();
  1603. }
  1604. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1605. ctx.stroke();
  1606. }
  1607. ctx.restore();
  1608. } else {
  1609. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1610. ctx.fillText(character, x, y);
  1611. }
  1612. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1613. ctx.strokeText(character, x, y);
  1614. }
  1615. }
  1616. if (isAddToPathSet) {
  1617. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  1618. paths.push({
  1619. transform: ctx.mozCurrentTransform,
  1620. x,
  1621. y,
  1622. fontSize,
  1623. addToPath
  1624. });
  1625. }
  1626. }
  1627. get isFontSubpixelAAEnabled() {
  1628. const {
  1629. context: ctx
  1630. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10, false);
  1631. ctx.scale(1.5, 1);
  1632. ctx.fillText("I", 0, 10);
  1633. const data = ctx.getImageData(0, 0, 10, 10).data;
  1634. let enabled = false;
  1635. for (let i = 3; i < data.length; i += 4) {
  1636. if (data[i] > 0 && data[i] < 255) {
  1637. enabled = true;
  1638. break;
  1639. }
  1640. }
  1641. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  1642. }
  1643. showText(glyphs) {
  1644. const current = this.current;
  1645. const font = current.font;
  1646. if (font.isType3Font) {
  1647. return this.showType3Text(glyphs);
  1648. }
  1649. const fontSize = current.fontSize;
  1650. if (fontSize === 0) {
  1651. return undefined;
  1652. }
  1653. const ctx = this.ctx;
  1654. const fontSizeScale = current.fontSizeScale;
  1655. const charSpacing = current.charSpacing;
  1656. const wordSpacing = current.wordSpacing;
  1657. const fontDirection = current.fontDirection;
  1658. const textHScale = current.textHScale * fontDirection;
  1659. const glyphsLength = glyphs.length;
  1660. const vertical = font.vertical;
  1661. const spacingDir = vertical ? 1 : -1;
  1662. const defaultVMetrics = font.defaultVMetrics;
  1663. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  1664. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  1665. ctx.save();
  1666. ctx.transform.apply(ctx, current.textMatrix);
  1667. ctx.translate(current.x, current.y + current.textRise);
  1668. if (fontDirection > 0) {
  1669. ctx.scale(textHScale, -1);
  1670. } else {
  1671. ctx.scale(textHScale, 1);
  1672. }
  1673. let patternTransform;
  1674. if (current.patternFill) {
  1675. ctx.save();
  1676. const pattern = current.fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL);
  1677. patternTransform = ctx.mozCurrentTransform;
  1678. ctx.restore();
  1679. ctx.fillStyle = pattern;
  1680. }
  1681. let lineWidth = current.lineWidth;
  1682. const scale = current.textMatrixScale;
  1683. if (scale === 0 || lineWidth === 0) {
  1684. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  1685. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  1686. lineWidth = this.getSinglePixelWidth();
  1687. }
  1688. } else {
  1689. lineWidth /= scale;
  1690. }
  1691. if (fontSizeScale !== 1.0) {
  1692. ctx.scale(fontSizeScale, fontSizeScale);
  1693. lineWidth /= fontSizeScale;
  1694. }
  1695. ctx.lineWidth = lineWidth;
  1696. let x = 0,
  1697. i;
  1698. for (i = 0; i < glyphsLength; ++i) {
  1699. const glyph = glyphs[i];
  1700. if (typeof glyph === "number") {
  1701. x += spacingDir * glyph * fontSize / 1000;
  1702. continue;
  1703. }
  1704. let restoreNeeded = false;
  1705. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1706. const character = glyph.fontChar;
  1707. const accent = glyph.accent;
  1708. let scaledX, scaledY;
  1709. let width = glyph.width;
  1710. if (vertical) {
  1711. const vmetric = glyph.vmetric || defaultVMetrics;
  1712. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  1713. const vy = vmetric[2] * widthAdvanceScale;
  1714. width = vmetric ? -vmetric[0] : width;
  1715. scaledX = vx / fontSizeScale;
  1716. scaledY = (x + vy) / fontSizeScale;
  1717. } else {
  1718. scaledX = x / fontSizeScale;
  1719. scaledY = 0;
  1720. }
  1721. if (font.remeasure && width > 0) {
  1722. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  1723. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  1724. const characterScaleX = width / measuredWidth;
  1725. restoreNeeded = true;
  1726. ctx.save();
  1727. ctx.scale(characterScaleX, 1);
  1728. scaledX /= characterScaleX;
  1729. } else if (width !== measuredWidth) {
  1730. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  1731. }
  1732. }
  1733. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  1734. if (simpleFillText && !accent) {
  1735. ctx.fillText(character, scaledX, scaledY);
  1736. } else {
  1737. this.paintChar(character, scaledX, scaledY, patternTransform);
  1738. if (accent) {
  1739. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  1740. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  1741. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  1742. }
  1743. }
  1744. }
  1745. let charWidth;
  1746. if (vertical) {
  1747. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  1748. } else {
  1749. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  1750. }
  1751. x += charWidth;
  1752. if (restoreNeeded) {
  1753. ctx.restore();
  1754. }
  1755. }
  1756. if (vertical) {
  1757. current.y -= x;
  1758. } else {
  1759. current.x += x * textHScale;
  1760. }
  1761. ctx.restore();
  1762. this.compose();
  1763. return undefined;
  1764. }
  1765. showType3Text(glyphs) {
  1766. const ctx = this.ctx;
  1767. const current = this.current;
  1768. const font = current.font;
  1769. const fontSize = current.fontSize;
  1770. const fontDirection = current.fontDirection;
  1771. const spacingDir = font.vertical ? 1 : -1;
  1772. const charSpacing = current.charSpacing;
  1773. const wordSpacing = current.wordSpacing;
  1774. const textHScale = current.textHScale * fontDirection;
  1775. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1776. const glyphsLength = glyphs.length;
  1777. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  1778. let i, glyph, width, spacingLength;
  1779. if (isTextInvisible || fontSize === 0) {
  1780. return;
  1781. }
  1782. this._cachedScaleForStroking = null;
  1783. this._cachedGetSinglePixelWidth = null;
  1784. ctx.save();
  1785. ctx.transform.apply(ctx, current.textMatrix);
  1786. ctx.translate(current.x, current.y);
  1787. ctx.scale(textHScale, fontDirection);
  1788. for (i = 0; i < glyphsLength; ++i) {
  1789. glyph = glyphs[i];
  1790. if (typeof glyph === "number") {
  1791. spacingLength = spacingDir * glyph * fontSize / 1000;
  1792. this.ctx.translate(spacingLength, 0);
  1793. current.x += spacingLength * textHScale;
  1794. continue;
  1795. }
  1796. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  1797. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  1798. if (!operatorList) {
  1799. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  1800. continue;
  1801. }
  1802. if (this.contentVisible) {
  1803. this.processingType3 = glyph;
  1804. this.save();
  1805. ctx.scale(fontSize, fontSize);
  1806. ctx.transform.apply(ctx, fontMatrix);
  1807. this.executeOperatorList(operatorList);
  1808. this.restore();
  1809. }
  1810. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  1811. width = transformed[0] * fontSize + spacing;
  1812. ctx.translate(width, 0);
  1813. current.x += width * textHScale;
  1814. }
  1815. ctx.restore();
  1816. this.processingType3 = null;
  1817. }
  1818. setCharWidth(xWidth, yWidth) {}
  1819. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  1820. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  1821. this.ctx.clip();
  1822. this.endPath();
  1823. }
  1824. getColorN_Pattern(IR) {
  1825. let pattern;
  1826. if (IR[0] === "TilingPattern") {
  1827. const color = IR[1];
  1828. const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  1829. const canvasGraphicsFactory = {
  1830. createCanvasGraphics: ctx => {
  1831. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
  1832. }
  1833. };
  1834. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  1835. } else {
  1836. pattern = this._getPattern(IR[1], IR[2]);
  1837. }
  1838. return pattern;
  1839. }
  1840. setStrokeColorN() {
  1841. this.current.strokeColor = this.getColorN_Pattern(arguments);
  1842. }
  1843. setFillColorN() {
  1844. this.current.fillColor = this.getColorN_Pattern(arguments);
  1845. this.current.patternFill = true;
  1846. }
  1847. setStrokeRGBColor(r, g, b) {
  1848. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  1849. this.ctx.strokeStyle = color;
  1850. this.current.strokeColor = color;
  1851. }
  1852. setFillRGBColor(r, g, b) {
  1853. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  1854. this.ctx.fillStyle = color;
  1855. this.current.fillColor = color;
  1856. this.current.patternFill = false;
  1857. }
  1858. _getPattern(objId, matrix = null) {
  1859. let pattern;
  1860. if (this.cachedPatterns.has(objId)) {
  1861. pattern = this.cachedPatterns.get(objId);
  1862. } else {
  1863. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  1864. this.cachedPatterns.set(objId, pattern);
  1865. }
  1866. if (matrix) {
  1867. pattern.matrix = matrix;
  1868. }
  1869. return pattern;
  1870. }
  1871. shadingFill(objId) {
  1872. if (!this.contentVisible) {
  1873. return;
  1874. }
  1875. const ctx = this.ctx;
  1876. this.save();
  1877. const pattern = this._getPattern(objId);
  1878. ctx.fillStyle = pattern.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.SHADING);
  1879. const inv = ctx.mozCurrentTransformInverse;
  1880. if (inv) {
  1881. const canvas = ctx.canvas;
  1882. const width = canvas.width;
  1883. const height = canvas.height;
  1884. const bl = _util.Util.applyTransform([0, 0], inv);
  1885. const br = _util.Util.applyTransform([0, height], inv);
  1886. const ul = _util.Util.applyTransform([width, 0], inv);
  1887. const ur = _util.Util.applyTransform([width, height], inv);
  1888. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  1889. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  1890. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  1891. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  1892. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  1893. } else {
  1894. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  1895. }
  1896. this.compose(this.current.getClippedPathBoundingBox());
  1897. this.restore();
  1898. }
  1899. beginInlineImage() {
  1900. (0, _util.unreachable)("Should not call beginInlineImage");
  1901. }
  1902. beginImageData() {
  1903. (0, _util.unreachable)("Should not call beginImageData");
  1904. }
  1905. paintFormXObjectBegin(matrix, bbox) {
  1906. if (!this.contentVisible) {
  1907. return;
  1908. }
  1909. this.save();
  1910. this.baseTransformStack.push(this.baseTransform);
  1911. if (Array.isArray(matrix) && matrix.length === 6) {
  1912. this.transform.apply(this, matrix);
  1913. }
  1914. this.baseTransform = this.ctx.mozCurrentTransform;
  1915. if (bbox) {
  1916. const width = bbox[2] - bbox[0];
  1917. const height = bbox[3] - bbox[1];
  1918. this.ctx.rect(bbox[0], bbox[1], width, height);
  1919. this.current.updateRectMinMax(this.ctx.mozCurrentTransform, bbox);
  1920. this.clip();
  1921. this.endPath();
  1922. }
  1923. }
  1924. paintFormXObjectEnd() {
  1925. if (!this.contentVisible) {
  1926. return;
  1927. }
  1928. this.restore();
  1929. this.baseTransform = this.baseTransformStack.pop();
  1930. }
  1931. beginGroup(group) {
  1932. if (!this.contentVisible) {
  1933. return;
  1934. }
  1935. this.save();
  1936. if (this.inSMaskMode) {
  1937. this.endSMaskMode();
  1938. this.current.activeSMask = null;
  1939. }
  1940. const currentCtx = this.ctx;
  1941. if (!group.isolated) {
  1942. (0, _util.info)("TODO: Support non-isolated groups.");
  1943. }
  1944. if (group.knockout) {
  1945. (0, _util.warn)("Knockout groups not supported.");
  1946. }
  1947. const currentTransform = currentCtx.mozCurrentTransform;
  1948. if (group.matrix) {
  1949. currentCtx.transform.apply(currentCtx, group.matrix);
  1950. }
  1951. if (!group.bbox) {
  1952. throw new Error("Bounding box is required.");
  1953. }
  1954. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  1955. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  1956. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  1957. const offsetX = Math.floor(bounds[0]);
  1958. const offsetY = Math.floor(bounds[1]);
  1959. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  1960. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  1961. let scaleX = 1,
  1962. scaleY = 1;
  1963. if (drawnWidth > MAX_GROUP_SIZE) {
  1964. scaleX = drawnWidth / MAX_GROUP_SIZE;
  1965. drawnWidth = MAX_GROUP_SIZE;
  1966. }
  1967. if (drawnHeight > MAX_GROUP_SIZE) {
  1968. scaleY = drawnHeight / MAX_GROUP_SIZE;
  1969. drawnHeight = MAX_GROUP_SIZE;
  1970. }
  1971. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  1972. let cacheId = "groupAt" + this.groupLevel;
  1973. if (group.smask) {
  1974. cacheId += "_smask_" + this.smaskCounter++ % 2;
  1975. }
  1976. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  1977. const groupCtx = scratchCanvas.context;
  1978. groupCtx.scale(1 / scaleX, 1 / scaleY);
  1979. groupCtx.translate(-offsetX, -offsetY);
  1980. groupCtx.transform.apply(groupCtx, currentTransform);
  1981. if (group.smask) {
  1982. this.smaskStack.push({
  1983. canvas: scratchCanvas.canvas,
  1984. context: groupCtx,
  1985. offsetX,
  1986. offsetY,
  1987. scaleX,
  1988. scaleY,
  1989. subtype: group.smask.subtype,
  1990. backdrop: group.smask.backdrop,
  1991. transferMap: group.smask.transferMap || null,
  1992. startTransformInverse: null
  1993. });
  1994. } else {
  1995. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  1996. currentCtx.translate(offsetX, offsetY);
  1997. currentCtx.scale(scaleX, scaleY);
  1998. currentCtx.save();
  1999. }
  2000. copyCtxState(currentCtx, groupCtx);
  2001. this.ctx = groupCtx;
  2002. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  2003. this.groupStack.push(currentCtx);
  2004. this.groupLevel++;
  2005. }
  2006. endGroup(group) {
  2007. if (!this.contentVisible) {
  2008. return;
  2009. }
  2010. this.groupLevel--;
  2011. const groupCtx = this.ctx;
  2012. const ctx = this.groupStack.pop();
  2013. this.ctx = ctx;
  2014. this.ctx.imageSmoothingEnabled = false;
  2015. if (group.smask) {
  2016. this.tempSMask = this.smaskStack.pop();
  2017. this.restore();
  2018. } else {
  2019. this.ctx.restore();
  2020. const currentMtx = this.ctx.mozCurrentTransform;
  2021. this.restore();
  2022. this.ctx.save();
  2023. this.ctx.setTransform.apply(this.ctx, currentMtx);
  2024. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  2025. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  2026. this.ctx.restore();
  2027. this.compose(dirtyBox);
  2028. }
  2029. }
  2030. beginAnnotations() {
  2031. this.save();
  2032. if (this.baseTransform) {
  2033. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  2034. }
  2035. }
  2036. endAnnotations() {
  2037. this.restore();
  2038. }
  2039. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  2040. this.save();
  2041. if (Array.isArray(rect) && rect.length === 4) {
  2042. const width = rect[2] - rect[0];
  2043. const height = rect[3] - rect[1];
  2044. if (hasOwnCanvas && this.annotationCanvasMap) {
  2045. transform = transform.slice();
  2046. transform[4] -= rect[0];
  2047. transform[5] -= rect[1];
  2048. rect = rect.slice();
  2049. rect[0] = rect[1] = 0;
  2050. rect[2] = width;
  2051. rect[3] = height;
  2052. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale(this.ctx.mozCurrentTransform);
  2053. const {
  2054. viewportScale
  2055. } = this;
  2056. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  2057. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  2058. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  2059. const {
  2060. canvas,
  2061. context
  2062. } = this.annotationCanvas;
  2063. const viewportScaleFactorStr = `var(--zoom-factor) * ${_display_utils.PixelsPerInch.PDF_TO_CSS_UNITS}`;
  2064. canvas.style.width = `calc(${width}px * ${viewportScaleFactorStr})`;
  2065. canvas.style.height = `calc(${height}px * ${viewportScaleFactorStr})`;
  2066. this.annotationCanvasMap.set(id, canvas);
  2067. this.annotationCanvas.savedCtx = this.ctx;
  2068. this.ctx = context;
  2069. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  2070. addContextCurrentTransform(this.ctx);
  2071. resetCtxToDefault(this.ctx, this.foregroundColor);
  2072. } else {
  2073. resetCtxToDefault(this.ctx, this.foregroundColor);
  2074. this.ctx.rect(rect[0], rect[1], width, height);
  2075. this.ctx.clip();
  2076. this.endPath();
  2077. }
  2078. }
  2079. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  2080. this.transform.apply(this, transform);
  2081. this.transform.apply(this, matrix);
  2082. }
  2083. endAnnotation() {
  2084. if (this.annotationCanvas) {
  2085. this.ctx = this.annotationCanvas.savedCtx;
  2086. delete this.annotationCanvas.savedCtx;
  2087. delete this.annotationCanvas;
  2088. }
  2089. this.restore();
  2090. }
  2091. paintImageMaskXObject(img) {
  2092. if (!this.contentVisible) {
  2093. return;
  2094. }
  2095. const count = img.count;
  2096. img = this.getObject(img.data, img);
  2097. img.count = count;
  2098. const ctx = this.ctx;
  2099. const glyph = this.processingType3;
  2100. if (glyph) {
  2101. if (glyph.compiled === undefined) {
  2102. glyph.compiled = compileType3Glyph(img);
  2103. }
  2104. if (glyph.compiled) {
  2105. glyph.compiled(ctx);
  2106. return;
  2107. }
  2108. }
  2109. const mask = this._createMaskCanvas(img);
  2110. const maskCanvas = mask.canvas;
  2111. ctx.save();
  2112. ctx.setTransform(1, 0, 0, 1, 0, 0);
  2113. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  2114. ctx.restore();
  2115. this.compose();
  2116. }
  2117. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  2118. if (!this.contentVisible) {
  2119. return;
  2120. }
  2121. img = this.getObject(img.data, img);
  2122. const ctx = this.ctx;
  2123. ctx.save();
  2124. const currentTransform = ctx.mozCurrentTransform;
  2125. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  2126. const mask = this._createMaskCanvas(img);
  2127. ctx.setTransform(1, 0, 0, 1, 0, 0);
  2128. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  2129. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  2130. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  2131. ctx.drawImage(mask.canvas, x, y);
  2132. }
  2133. ctx.restore();
  2134. this.compose();
  2135. }
  2136. paintImageMaskXObjectGroup(images) {
  2137. if (!this.contentVisible) {
  2138. return;
  2139. }
  2140. const ctx = this.ctx;
  2141. const fillColor = this.current.fillColor;
  2142. const isPatternFill = this.current.patternFill;
  2143. for (let i = 0, ii = images.length; i < ii; i++) {
  2144. const image = images[i];
  2145. const width = image.width,
  2146. height = image.height;
  2147. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height, false);
  2148. const maskCtx = maskCanvas.context;
  2149. maskCtx.save();
  2150. putBinaryImageMask(maskCtx, image);
  2151. maskCtx.globalCompositeOperation = "source-in";
  2152. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL) : fillColor;
  2153. maskCtx.fillRect(0, 0, width, height);
  2154. maskCtx.restore();
  2155. ctx.save();
  2156. ctx.transform.apply(ctx, image.transform);
  2157. ctx.scale(1, -1);
  2158. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  2159. ctx.restore();
  2160. }
  2161. this.compose();
  2162. }
  2163. paintImageXObject(objId) {
  2164. if (!this.contentVisible) {
  2165. return;
  2166. }
  2167. const imgData = this.getObject(objId);
  2168. if (!imgData) {
  2169. (0, _util.warn)("Dependent image isn't ready yet");
  2170. return;
  2171. }
  2172. this.paintInlineImageXObject(imgData);
  2173. }
  2174. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  2175. if (!this.contentVisible) {
  2176. return;
  2177. }
  2178. const imgData = this.getObject(objId);
  2179. if (!imgData) {
  2180. (0, _util.warn)("Dependent image isn't ready yet");
  2181. return;
  2182. }
  2183. const width = imgData.width;
  2184. const height = imgData.height;
  2185. const map = [];
  2186. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  2187. map.push({
  2188. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  2189. x: 0,
  2190. y: 0,
  2191. w: width,
  2192. h: height
  2193. });
  2194. }
  2195. this.paintInlineImageXObjectGroup(imgData, map);
  2196. }
  2197. paintInlineImageXObject(imgData) {
  2198. if (!this.contentVisible) {
  2199. return;
  2200. }
  2201. const width = imgData.width;
  2202. const height = imgData.height;
  2203. const ctx = this.ctx;
  2204. this.save();
  2205. ctx.scale(1 / width, -1 / height);
  2206. let imgToPaint;
  2207. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  2208. imgToPaint = imgData;
  2209. } else {
  2210. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height, false);
  2211. const tmpCtx = tmpCanvas.context;
  2212. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  2213. imgToPaint = tmpCanvas.canvas;
  2214. }
  2215. const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse);
  2216. ctx.imageSmoothingEnabled = getImageSmoothingEnabled(ctx.mozCurrentTransform, imgData.interpolate);
  2217. const [rWidth, rHeight] = drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  2218. if (this.imageLayer) {
  2219. const position = this.getCanvasPosition(0, -height);
  2220. this.imageLayer.appendImage({
  2221. imgData,
  2222. left: position[0],
  2223. top: position[1],
  2224. width: rWidth,
  2225. height: rHeight
  2226. });
  2227. }
  2228. this.compose();
  2229. this.restore();
  2230. }
  2231. paintInlineImageXObjectGroup(imgData, map) {
  2232. if (!this.contentVisible) {
  2233. return;
  2234. }
  2235. const ctx = this.ctx;
  2236. const w = imgData.width;
  2237. const h = imgData.height;
  2238. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h, false);
  2239. const tmpCtx = tmpCanvas.context;
  2240. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  2241. for (let i = 0, ii = map.length; i < ii; i++) {
  2242. const entry = map[i];
  2243. ctx.save();
  2244. ctx.transform.apply(ctx, entry.transform);
  2245. ctx.scale(1, -1);
  2246. drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  2247. if (this.imageLayer) {
  2248. const position = this.getCanvasPosition(entry.x, entry.y);
  2249. this.imageLayer.appendImage({
  2250. imgData,
  2251. left: position[0],
  2252. top: position[1],
  2253. width: w,
  2254. height: h
  2255. });
  2256. }
  2257. ctx.restore();
  2258. }
  2259. this.compose();
  2260. }
  2261. paintSolidColorImageMask() {
  2262. if (!this.contentVisible) {
  2263. return;
  2264. }
  2265. this.ctx.fillRect(0, 0, 1, 1);
  2266. this.compose();
  2267. }
  2268. markPoint(tag) {}
  2269. markPointProps(tag, properties) {}
  2270. beginMarkedContent(tag) {
  2271. this.markedContentStack.push({
  2272. visible: true
  2273. });
  2274. }
  2275. beginMarkedContentProps(tag, properties) {
  2276. if (tag === "OC") {
  2277. this.markedContentStack.push({
  2278. visible: this.optionalContentConfig.isVisible(properties)
  2279. });
  2280. } else {
  2281. this.markedContentStack.push({
  2282. visible: true
  2283. });
  2284. }
  2285. this.contentVisible = this.isContentVisible();
  2286. }
  2287. endMarkedContent() {
  2288. this.markedContentStack.pop();
  2289. this.contentVisible = this.isContentVisible();
  2290. }
  2291. beginCompat() {}
  2292. endCompat() {}
  2293. consumePath(clipBox) {
  2294. const isEmpty = this.current.isEmptyClip();
  2295. if (this.pendingClip) {
  2296. this.current.updateClipFromPath();
  2297. }
  2298. if (!this.pendingClip) {
  2299. this.compose(clipBox);
  2300. }
  2301. const ctx = this.ctx;
  2302. if (this.pendingClip) {
  2303. if (!isEmpty) {
  2304. if (this.pendingClip === EO_CLIP) {
  2305. ctx.clip("evenodd");
  2306. } else {
  2307. ctx.clip();
  2308. }
  2309. }
  2310. this.pendingClip = null;
  2311. }
  2312. this.current.startNewPathAndClipBox(this.current.clipBox);
  2313. ctx.beginPath();
  2314. }
  2315. getSinglePixelWidth() {
  2316. if (!this._cachedGetSinglePixelWidth) {
  2317. const m = this.ctx.mozCurrentTransform;
  2318. if (m[1] === 0 && m[2] === 0) {
  2319. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  2320. } else {
  2321. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  2322. const normX = Math.hypot(m[0], m[2]);
  2323. const normY = Math.hypot(m[1], m[3]);
  2324. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  2325. }
  2326. }
  2327. return this._cachedGetSinglePixelWidth;
  2328. }
  2329. getScaleForStroking() {
  2330. if (!this._cachedScaleForStroking) {
  2331. const {
  2332. lineWidth
  2333. } = this.current;
  2334. const m = this.ctx.mozCurrentTransform;
  2335. let scaleX, scaleY;
  2336. if (m[1] === 0 && m[2] === 0) {
  2337. const normX = Math.abs(m[0]);
  2338. const normY = Math.abs(m[3]);
  2339. if (lineWidth === 0) {
  2340. scaleX = 1 / normX;
  2341. scaleY = 1 / normY;
  2342. } else {
  2343. const scaledXLineWidth = normX * lineWidth;
  2344. const scaledYLineWidth = normY * lineWidth;
  2345. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  2346. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  2347. }
  2348. } else {
  2349. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  2350. const normX = Math.hypot(m[0], m[1]);
  2351. const normY = Math.hypot(m[2], m[3]);
  2352. if (lineWidth === 0) {
  2353. scaleX = normY / absDet;
  2354. scaleY = normX / absDet;
  2355. } else {
  2356. const baseArea = lineWidth * absDet;
  2357. scaleX = normY > baseArea ? normY / baseArea : 1;
  2358. scaleY = normX > baseArea ? normX / baseArea : 1;
  2359. }
  2360. }
  2361. this._cachedScaleForStroking = [scaleX, scaleY];
  2362. }
  2363. return this._cachedScaleForStroking;
  2364. }
  2365. rescaleAndStroke(saveRestore) {
  2366. const {
  2367. ctx
  2368. } = this;
  2369. const {
  2370. lineWidth
  2371. } = this.current;
  2372. const [scaleX, scaleY] = this.getScaleForStroking();
  2373. ctx.lineWidth = lineWidth || 1;
  2374. if (scaleX === 1 && scaleY === 1) {
  2375. ctx.stroke();
  2376. return;
  2377. }
  2378. let savedMatrix, savedDashes, savedDashOffset;
  2379. if (saveRestore) {
  2380. savedMatrix = ctx.mozCurrentTransform.slice();
  2381. savedDashes = ctx.getLineDash().slice();
  2382. savedDashOffset = ctx.lineDashOffset;
  2383. }
  2384. ctx.scale(scaleX, scaleY);
  2385. const scale = Math.max(scaleX, scaleY);
  2386. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  2387. ctx.lineDashOffset /= scale;
  2388. ctx.stroke();
  2389. if (saveRestore) {
  2390. ctx.setTransform(...savedMatrix);
  2391. ctx.setLineDash(savedDashes);
  2392. ctx.lineDashOffset = savedDashOffset;
  2393. }
  2394. }
  2395. getCanvasPosition(x, y) {
  2396. const transform = this.ctx.mozCurrentTransform;
  2397. return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
  2398. }
  2399. isContentVisible() {
  2400. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  2401. if (!this.markedContentStack[i].visible) {
  2402. return false;
  2403. }
  2404. }
  2405. return true;
  2406. }
  2407. }
  2408. exports.CanvasGraphics = CanvasGraphics;
  2409. for (const op in _util.OPS) {
  2410. if (CanvasGraphics.prototype[op] !== undefined) {
  2411. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  2412. }
  2413. }