canvas.js 62 KB

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