canvas.js
77.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('pdfjs/display/canvas', ['exports', 'pdfjs/shared/util',
'pdfjs/display/dom_utils', 'pdfjs/display/pattern_helper',
'pdfjs/display/webgl'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('../shared/util.js'), require('./dom_utils.js'),
require('./pattern_helper.js'), require('./webgl.js'));
} else {
factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper,
root.pdfjsDisplayWebGL);
}
}(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper,
displayWebGL) {
var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
var ImageKind = sharedUtil.ImageKind;
var OPS = sharedUtil.OPS;
var TextRenderingMode = sharedUtil.TextRenderingMode;
var Uint32ArrayView = sharedUtil.Uint32ArrayView;
var Util = sharedUtil.Util;
var assert = sharedUtil.assert;
var info = sharedUtil.info;
var isNum = sharedUtil.isNum;
var isArray = sharedUtil.isArray;
var isLittleEndian = sharedUtil.isLittleEndian;
var error = sharedUtil.error;
var shadow = sharedUtil.shadow;
var warn = sharedUtil.warn;
var TilingPattern = displayPatternHelper.TilingPattern;
var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
var WebGLUtils = displayWebGL.WebGLUtils;
var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
// <canvas> contexts store most of the state we need natively.
// However, PDF needs a bit more state, which we store here.
// Minimal font size that would be used during canvas fillText operations.
var MIN_FONT_SIZE = 16;
// Maximum font size that would be used during canvas fillText operations.
var MAX_FONT_SIZE = 100;
var MAX_GROUP_SIZE = 4096;
// Heuristic value used when enforcing minimum line widths.
var MIN_WIDTH_FACTOR = 0.65;
var COMPILE_TYPE3_GLYPHS = true;
var MAX_SIZE_TO_COMPILE = 1000;
var FULL_CHUNK_HEIGHT = 16;
var HasCanvasTypedArraysCached = {
get value() {
return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
}
};
var IsLittleEndianCached = {
get value() {
return shadow(IsLittleEndianCached, 'value', isLittleEndian());
}
};
function createScratchCanvas(width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}
function addContextCurrentTransform(ctx) {
// If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
if (!ctx.mozCurrentTransform) {
ctx._originalSave = ctx.save;
ctx._originalRestore = ctx.restore;
ctx._originalRotate = ctx.rotate;
ctx._originalScale = ctx.scale;
ctx._originalTranslate = ctx.translate;
ctx._originalTransform = ctx.transform;
ctx._originalSetTransform = ctx.setTransform;
ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
ctx._transformStack = [];
Object.defineProperty(ctx, 'mozCurrentTransform', {
get: function getCurrentTransform() {
return this._transformMatrix;
}
});
Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
get: function getCurrentTransformInverse() {
// Calculation done using WolframAlpha:
// http://www.wolframalpha.com/input/?
// i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
var m = this._transformMatrix;
var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
var ad_bc = a * d - b * c;
var bc_ad = b * c - a * d;
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
];
}
});
ctx.save = function ctxSave() {
var old = this._transformMatrix;
this._transformStack.push(old);
this._transformMatrix = old.slice(0, 6);
this._originalSave();
};
ctx.restore = function ctxRestore() {
var prev = this._transformStack.pop();
if (prev) {
this._transformMatrix = prev;
this._originalRestore();
}
};
ctx.translate = function ctxTranslate(x, y) {
var m = this._transformMatrix;
m[4] = m[0] * x + m[2] * y + m[4];
m[5] = m[1] * x + m[3] * y + m[5];
this._originalTranslate(x, y);
};
ctx.scale = function ctxScale(x, y) {
var m = this._transformMatrix;
m[0] = m[0] * x;
m[1] = m[1] * x;
m[2] = m[2] * y;
m[3] = m[3] * y;
this._originalScale(x, y);
};
ctx.transform = function ctxTransform(a, b, c, d, e, f) {
var m = this._transformMatrix;
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]
];
ctx._originalTransform(a, b, c, d, e, f);
};
ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
this._transformMatrix = [a, b, c, d, e, f];
ctx._originalSetTransform(a, b, c, d, e, f);
};
ctx.rotate = function ctxRotate(angle) {
var cosValue = Math.cos(angle);
var sinValue = Math.sin(angle);
var m = this._transformMatrix;
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]
];
this._originalRotate(angle);
};
}
}
var CachedCanvases = (function CachedCanvasesClosure() {
function CachedCanvases() {
this.cache = Object.create(null);
}
CachedCanvases.prototype = {
getCanvas: function CachedCanvases_getCanvas(id, width, height,
trackTransform) {
var canvasEntry;
if (this.cache[id] !== undefined) {
canvasEntry = this.cache[id];
canvasEntry.canvas.width = width;
canvasEntry.canvas.height = height;
// reset canvas transform for emulated mozCurrentTransform, if needed
canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
} else {
var canvas = createScratchCanvas(width, height);
var ctx = canvas.getContext('2d');
if (trackTransform) {
addContextCurrentTransform(ctx);
}
this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
}
return canvasEntry;
},
clear: function () {
for (var id in this.cache) {
var canvasEntry = this.cache[id];
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
canvasEntry.canvas.width = 0;
canvasEntry.canvas.height = 0;
delete this.cache[id];
}
}
};
return CachedCanvases;
})();
function compileType3Glyph(imgData) {
var POINT_TO_PROCESS_LIMIT = 1000;
var width = imgData.width, height = imgData.height;
var i, j, j0, width1 = width + 1;
var points = new Uint8Array(width1 * (height + 1));
var POINT_TYPES =
new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
// decodes bit-packed mask data
var lineSize = (width + 7) & ~7, data0 = imgData.data;
var data = new Uint8Array(lineSize * height), pos = 0, ii;
for (i = 0, ii = data0.length; i < ii; i++) {
var mask = 128, elem = data0[i];
while (mask > 0) {
data[pos++] = (elem & mask) ? 0 : 255;
mask >>= 1;
}
}
// finding iteresting points: every point is located between mask pixels,
// so there will be points of the (width + 1)x(height + 1) grid. Every point
// will have flags assigned based on neighboring mask pixels:
// 4 | 8
// --P--
// 2 | 1
// We are interested only in points with the flags:
// - outside corners: 1, 2, 4, 8;
// - inside corners: 7, 11, 13, 14;
// - and, intersections: 5, 10.
var count = 0;
pos = 0;
if (data[pos] !== 0) {
points[0] = 1;
++count;
}
for (j = 1; j < width; j++) {
if (data[pos] !== data[pos + 1]) {
points[j] = data[pos] ? 2 : 1;
++count;
}
pos++;
}
if (data[pos] !== 0) {
points[j] = 2;
++count;
}
for (i = 1; i < height; i++) {
pos = i * lineSize;
j0 = i * width1;
if (data[pos - lineSize] !== data[pos]) {
points[j0] = data[pos] ? 1 : 8;
++count;
}
// 'sum' is the position of the current pixel configuration in the 'TYPES'
// array (in order 8-1-2-4, so we can use '>>2' to shift the column).
var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
for (j = 1; j < width; j++) {
sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
(data[pos - lineSize + 1] ? 8 : 0);
if (POINT_TYPES[sum]) {
points[j0 + j] = POINT_TYPES[sum];
++count;
}
pos++;
}
if (data[pos - lineSize] !== data[pos]) {
points[j0 + j] = data[pos] ? 2 : 4;
++count;
}
if (count > POINT_TO_PROCESS_LIMIT) {
return null;
}
}
pos = lineSize * (height - 1);
j0 = i * width1;
if (data[pos] !== 0) {
points[j0] = 8;
++count;
}
for (j = 1; j < width; j++) {
if (data[pos] !== data[pos + 1]) {
points[j0 + j] = data[pos] ? 4 : 8;
++count;
}
pos++;
}
if (data[pos] !== 0) {
points[j0 + j] = 4;
++count;
}
if (count > POINT_TO_PROCESS_LIMIT) {
return null;
}
// building outlines
var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
var outlines = [];
for (i = 0; count && i <= height; i++) {
var p = i * width1;
var end = p + width;
while (p < end && !points[p]) {
p++;
}
if (p === end) {
continue;
}
var coords = [p % width1, i];
var type = points[p], p0 = p, pp;
do {
var step = steps[type];
do {
p += step;
} while (!points[p]);
pp = points[p];
if (pp !== 5 && pp !== 10) {
// set new direction
type = pp;
// delete mark
points[p] = 0;
} else { // type is 5 or 10, ie, a crossing
// set new direction
type = pp & ((0x33 * type) >> 4);
// set new type for "future hit"
points[p] &= (type >> 2 | type << 2);
}
coords.push(p % width1);
coords.push((p / width1) | 0);
--count;
} while (p0 !== p);
outlines.push(coords);
--i;
}
var drawOutline = function(c) {
c.save();
// the path shall be painted in [0..1]x[0..1] space
c.scale(1 / width, -1 / height);
c.translate(0, -height);
c.beginPath();
for (var i = 0, ii = outlines.length; i < ii; i++) {
var o = outlines[i];
c.moveTo(o[0], o[1]);
for (var j = 2, jj = o.length; j < jj; j += 2) {
c.lineTo(o[j], o[j + 1]);
}
}
c.fill();
c.beginPath();
c.restore();
};
return drawOutline;
}
var CanvasExtraState = (function CanvasExtraStateClosure() {
function CanvasExtraState(old) {
// Are soft masks and alpha values shapes or opacities?
this.alphaIsShape = false;
this.fontSize = 0;
this.fontSizeScale = 1;
this.textMatrix = IDENTITY_MATRIX;
this.textMatrixScale = 1;
this.fontMatrix = FONT_IDENTITY_MATRIX;
this.leading = 0;
// Current point (in user coordinates)
this.x = 0;
this.y = 0;
// Start of text line (in text coordinates)
this.lineX = 0;
this.lineY = 0;
// Character and word spacing
this.charSpacing = 0;
this.wordSpacing = 0;
this.textHScale = 1;
this.textRenderingMode = TextRenderingMode.FILL;
this.textRise = 0;
// Default fore and background colors
this.fillColor = '#000000';
this.strokeColor = '#000000';
this.patternFill = false;
// Note: fill alpha applies to all non-stroking operations
this.fillAlpha = 1;
this.strokeAlpha = 1;
this.lineWidth = 1;
this.activeSMask = null;
this.resumeSMaskCtx = null; // nonclonable field (see the save method below)
this.old = old;
}
CanvasExtraState.prototype = {
clone: function CanvasExtraState_clone() {
return Object.create(this);
},
setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
this.x = x;
this.y = y;
}
};
return CanvasExtraState;
})();
var CanvasGraphics = (function CanvasGraphicsClosure() {
// Defines the time the executeOperatorList is going to be executing
// before it stops and shedules a continue of execution.
var EXECUTION_TIME = 15;
// Defines the number of steps before checking the execution time
var EXECUTION_STEPS = 10;
function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
this.ctx = canvasCtx;
this.current = new CanvasExtraState();
this.stateStack = [];
this.pendingClip = null;
this.pendingEOFill = false;
this.res = null;
this.xobjs = null;
this.commonObjs = commonObjs;
this.objs = objs;
this.imageLayer = imageLayer;
this.groupStack = [];
this.processingType3 = null;
// Patterns are painted relative to the initial page/form transform, see pdf
// spec 8.7.2 NOTE 1.
this.baseTransform = null;
this.baseTransformStack = [];
this.groupLevel = 0;
this.smaskStack = [];
this.smaskCounter = 0;
this.tempSMask = null;
this.cachedCanvases = new CachedCanvases();
if (canvasCtx) {
// NOTE: if mozCurrentTransform is polyfilled, then the current state of
// the transformation must already be set in canvasCtx._transformMatrix.
addContextCurrentTransform(canvasCtx);
}
this.cachedGetSinglePixelWidth = null;
}
function putBinaryImageData(ctx, imgData) {
if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
ctx.putImageData(imgData, 0, 0);
return;
}
// Put the image data to the canvas in chunks, rather than putting the
// whole image at once. This saves JS memory, because the ImageData object
// is smaller. It also possibly saves C++ memory within the implementation
// of putImageData(). (E.g. in Firefox we make two short-lived copies of
// the data passed to putImageData()). |n| shouldn't be too small, however,
// because too many putImageData() calls will slow things down.
//
// Note: as written, if the last chunk is partial, the putImageData() call
// will (conceptually) put pixels past the bounds of the canvas. But
// that's ok; any such pixels are ignored.
var height = imgData.height, width = imgData.width;
var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
var srcPos = 0, destPos;
var src = imgData.data;
var dest = chunkImgData.data;
var i, j, thisChunkHeight, elemsInThisChunk;
// There are multiple forms in which the pixel data can be passed, and
// imgData.kind tells us which one this is.
if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
// Grayscale, 1 bit per pixel (i.e. black-and-white).
var srcLength = src.byteLength;
var dest32 = HasCanvasTypedArraysCached.value ?
new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
var dest32DataLength = dest32.length;
var fullSrcDiff = (width + 7) >> 3;
var white = 0xFFFFFFFF;
var black = (IsLittleEndianCached.value ||
!HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF;
for (i = 0; i < totalChunks; i++) {
thisChunkHeight =
(i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
destPos = 0;
for (j = 0; j < thisChunkHeight; j++) {
var srcDiff = srcLength - srcPos;
var k = 0;
var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
var kEndUnrolled = kEnd & ~7;
var mask = 0;
var srcByte = 0;
for (; k < kEndUnrolled; k += 8) {
srcByte = src[srcPos++];
dest32[destPos++] = (srcByte & 128) ? white : black;
dest32[destPos++] = (srcByte & 64) ? white : black;
dest32[destPos++] = (srcByte & 32) ? white : black;
dest32[destPos++] = (srcByte & 16) ? white : black;
dest32[destPos++] = (srcByte & 8) ? white : black;
dest32[destPos++] = (srcByte & 4) ? white : black;
dest32[destPos++] = (srcByte & 2) ? white : black;
dest32[destPos++] = (srcByte & 1) ? white : black;
}
for (; k < kEnd; k++) {
if (mask === 0) {
srcByte = src[srcPos++];
mask = 128;
}
dest32[destPos++] = (srcByte & mask) ? white : black;
mask >>= 1;
}
}
// We ran out of input. Make all remaining pixels transparent.
while (destPos < dest32DataLength) {
dest32[destPos++] = 0;
}
ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
}
} else if (imgData.kind === ImageKind.RGBA_32BPP) {
// RGBA, 32-bits per pixel.
j = 0;
elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
for (i = 0; i < fullChunks; i++) {
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
srcPos += elemsInThisChunk;
ctx.putImageData(chunkImgData, 0, j);
j += FULL_CHUNK_HEIGHT;
}
if (i < totalChunks) {
elemsInThisChunk = width * partialChunkHeight * 4;
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
ctx.putImageData(chunkImgData, 0, j);
}
} else if (imgData.kind === ImageKind.RGB_24BPP) {
// RGB, 24-bits per pixel.
thisChunkHeight = FULL_CHUNK_HEIGHT;
elemsInThisChunk = width * thisChunkHeight;
for (i = 0; i < totalChunks; i++) {
if (i >= fullChunks) {
thisChunkHeight = partialChunkHeight;
elemsInThisChunk = width * thisChunkHeight;
}
destPos = 0;
for (j = elemsInThisChunk; j--;) {
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = 255;
}
ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
}
} else {
error('bad image kind: ' + imgData.kind);
}
}
function putBinaryImageMask(ctx, imgData) {
var height = imgData.height, width = imgData.width;
var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
var srcPos = 0;
var src = imgData.data;
var dest = chunkImgData.data;
for (var i = 0; i < totalChunks; i++) {
var thisChunkHeight =
(i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
// Expand the mask so it can be used by the canvas. Any required
// inversion has already been handled.
var destPos = 3; // alpha component offset
for (var j = 0; j < thisChunkHeight; j++) {
var mask = 0;
for (var k = 0; k < width; k++) {
if (!mask) {
var elem = src[srcPos++];
mask = 128;
}
dest[destPos] = (elem & mask) ? 0 : 255;
destPos += 4;
mask >>= 1;
}
}
ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
}
}
function copyCtxState(sourceCtx, destCtx) {
var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
'globalCompositeOperation', 'font'];
for (var i = 0, ii = properties.length; i < ii; i++) {
var property = properties[i];
if (sourceCtx[property] !== undefined) {
destCtx[property] = sourceCtx[property];
}
}
if (sourceCtx.setLineDash !== undefined) {
destCtx.setLineDash(sourceCtx.getLineDash());
destCtx.lineDashOffset = sourceCtx.lineDashOffset;
}
}
function composeSMaskBackdrop(bytes, r0, g0, b0) {
var length = bytes.length;
for (var i = 3; i < length; i += 4) {
var alpha = bytes[i];
if (alpha === 0) {
bytes[i - 3] = r0;
bytes[i - 2] = g0;
bytes[i - 1] = b0;
} else if (alpha < 255) {
var alpha_ = 255 - alpha;
bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
}
}
}
function composeSMaskAlpha(maskData, layerData, transferMap) {
var length = maskData.length;
var scale = 1 / 255;
for (var i = 3; i < length; i += 4) {
var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
layerData[i] = (layerData[i] * alpha * scale) | 0;
}
}
function composeSMaskLuminosity(maskData, layerData, transferMap) {
var length = maskData.length;
for (var i = 3; i < length; i += 4) {
var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
(maskData[i - 2] * 152) + // * 0.59 ....
(maskData[i - 1] * 28); // * 0.11 ....
layerData[i] = transferMap ?
(layerData[i] * transferMap[y >> 8]) >> 8 :
(layerData[i] * y) >> 16;
}
}
function genericComposeSMask(maskCtx, layerCtx, width, height,
subtype, backdrop, transferMap) {
var hasBackdrop = !!backdrop;
var r0 = hasBackdrop ? backdrop[0] : 0;
var g0 = hasBackdrop ? backdrop[1] : 0;
var b0 = hasBackdrop ? backdrop[2] : 0;
var composeFn;
if (subtype === 'Luminosity') {
composeFn = composeSMaskLuminosity;
} else {
composeFn = composeSMaskAlpha;
}
// processing image in chunks to save memory
var PIXELS_TO_PROCESS = 1048576;
var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
for (var row = 0; row < height; row += chunkSize) {
var chunkHeight = Math.min(chunkSize, height - row);
var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
if (hasBackdrop) {
composeSMaskBackdrop(maskData.data, r0, g0, b0);
}
composeFn(maskData.data, layerData.data, transferMap);
maskCtx.putImageData(layerData, 0, row);
}
}
function composeSMask(ctx, smask, layerCtx) {
var mask = smask.canvas;
var maskCtx = smask.context;
ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
smask.offsetX, smask.offsetY);
var backdrop = smask.backdrop || null;
if (!smask.transferMap && WebGLUtils.isEnabled) {
var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
{subtype: smask.subtype, backdrop: backdrop});
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(composed, smask.offsetX, smask.offsetY);
return;
}
genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
smask.subtype, backdrop, smask.transferMap);
ctx.drawImage(mask, 0, 0);
}
var LINE_CAP_STYLES = ['butt', 'round', 'square'];
var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
var NORMAL_CLIP = {};
var EO_CLIP = {};
CanvasGraphics.prototype = {
beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
transparency) {
// For pdfs that use blend modes we have to clear the canvas else certain
// blend modes can look wrong since we'd be blending with a white
// backdrop. The problem with a transparent backdrop though is we then
// don't get sub pixel anti aliasing on text, creating temporary
// transparent canvas when we have blend modes.
var width = this.ctx.canvas.width;
var height = this.ctx.canvas.height;
this.ctx.save();
this.ctx.fillStyle = 'rgb(255, 255, 255)';
this.ctx.fillRect(0, 0, width, height);
this.ctx.restore();
if (transparency) {
var transparentCanvas = this.cachedCanvases.getCanvas(
'transparent', width, height, true);
this.compositeCtx = this.ctx;
this.transparentCanvas = transparentCanvas.canvas;
this.ctx = transparentCanvas.context;
this.ctx.save();
// The transform can be applied before rendering, transferring it to
// the new canvas.
this.ctx.transform.apply(this.ctx,
this.compositeCtx.mozCurrentTransform);
}
this.ctx.save();
if (transform) {
this.ctx.transform.apply(this.ctx, transform);
}
this.ctx.transform.apply(this.ctx, viewport.transform);
this.baseTransform = this.ctx.mozCurrentTransform.slice();
if (this.imageLayer) {
this.imageLayer.beginLayout();
}
},
executeOperatorList: function CanvasGraphics_executeOperatorList(
operatorList,
executionStartIdx, continueCallback,
stepper) {
var argsArray = operatorList.argsArray;
var fnArray = operatorList.fnArray;
var i = executionStartIdx || 0;
var argsArrayLen = argsArray.length;
// Sometimes the OperatorList to execute is empty.
if (argsArrayLen === i) {
return i;
}
var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
typeof continueCallback === 'function');
var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
var steps = 0;
var commonObjs = this.commonObjs;
var objs = this.objs;
var fnId;
while (true) {
if (stepper !== undefined && i === stepper.nextBreakPoint) {
stepper.breakIt(i, continueCallback);
return i;
}
fnId = fnArray[i];
if (fnId !== OPS.dependency) {
this[fnId].apply(this, argsArray[i]);
} else {
var deps = argsArray[i];
for (var n = 0, nn = deps.length; n < nn; n++) {
var depObjId = deps[n];
var common = depObjId[0] === 'g' && depObjId[1] === '_';
var objsPool = common ? commonObjs : objs;
// If the promise isn't resolved yet, add the continueCallback
// to the promise and bail out.
if (!objsPool.isResolved(depObjId)) {
objsPool.get(depObjId, continueCallback);
return i;
}
}
}
i++;
// If the entire operatorList was executed, stop as were done.
if (i === argsArrayLen) {
return i;
}
// If the execution took longer then a certain amount of time and
// `continueCallback` is specified, interrupt the execution.
if (chunkOperations && ++steps > EXECUTION_STEPS) {
if (Date.now() > endTime) {
continueCallback();
return i;
}
steps = 0;
}
// If the operatorList isn't executed completely yet OR the execution
// time was short enough, do another execution round.
}
},
endDrawing: function CanvasGraphics_endDrawing() {
// Finishing all opened operations such as SMask group painting.
if (this.current.activeSMask !== null) {
this.endSMaskGroup();
}
this.ctx.restore();
if (this.transparentCanvas) {
this.ctx = this.compositeCtx;
this.ctx.save();
this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
this.ctx.drawImage(this.transparentCanvas, 0, 0);
this.ctx.restore();
this.transparentCanvas = null;
}
this.cachedCanvases.clear();
WebGLUtils.clear();
if (this.imageLayer) {
this.imageLayer.endLayout();
}
},
// Graphics state
setLineWidth: function CanvasGraphics_setLineWidth(width) {
this.current.lineWidth = width;
this.ctx.lineWidth = width;
},
setLineCap: function CanvasGraphics_setLineCap(style) {
this.ctx.lineCap = LINE_CAP_STYLES[style];
},
setLineJoin: function CanvasGraphics_setLineJoin(style) {
this.ctx.lineJoin = LINE_JOIN_STYLES[style];
},
setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
this.ctx.miterLimit = limit;
},
setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
var ctx = this.ctx;
if (ctx.setLineDash !== undefined) {
ctx.setLineDash(dashArray);
ctx.lineDashOffset = dashPhase;
}
},
setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
// Maybe if we one day fully support color spaces this will be important
// for now we can ignore.
// TODO set rendering intent?
},
setFlatness: function CanvasGraphics_setFlatness(flatness) {
// There's no way to control this with canvas, but we can safely ignore.
// TODO set flatness?
},
setGState: function CanvasGraphics_setGState(states) {
for (var i = 0, ii = states.length; i < ii; i++) {
var state = states[i];
var key = state[0];
var value = state[1];
switch (key) {
case 'LW':
this.setLineWidth(value);
break;
case 'LC':
this.setLineCap(value);
break;
case 'LJ':
this.setLineJoin(value);
break;
case 'ML':
this.setMiterLimit(value);
break;
case 'D':
this.setDash(value[0], value[1]);
break;
case 'RI':
this.setRenderingIntent(value);
break;
case 'FL':
this.setFlatness(value);
break;
case 'Font':
this.setFont(value[0], value[1]);
break;
case 'CA':
this.current.strokeAlpha = state[1];
break;
case 'ca':
this.current.fillAlpha = state[1];
this.ctx.globalAlpha = state[1];
break;
case 'BM':
if (value && value.name && (value.name !== 'Normal')) {
var mode = value.name.replace(/([A-Z])/g,
function(c) {
return '-' + c.toLowerCase();
}
).substring(1);
this.ctx.globalCompositeOperation = mode;
if (this.ctx.globalCompositeOperation !== mode) {
warn('globalCompositeOperation "' + mode +
'" is not supported');
}
} else {
this.ctx.globalCompositeOperation = 'source-over';
}
break;
case 'SMask':
if (this.current.activeSMask) {
// If SMask is currrenly used, it needs to be suspended or
// finished. Suspend only makes sense when at least one save()
// was performed and state needs to be reverted on restore().
if (this.stateStack.length > 0 &&
(this.stateStack[this.stateStack.length - 1].activeSMask ===
this.current.activeSMask)) {
this.suspendSMaskGroup();
} else {
this.endSMaskGroup();
}
}
this.current.activeSMask = value ? this.tempSMask : null;
if (this.current.activeSMask) {
this.beginSMaskGroup();
}
this.tempSMask = null;
break;
}
}
},
beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
var activeSMask = this.current.activeSMask;
var drawnWidth = activeSMask.canvas.width;
var drawnHeight = activeSMask.canvas.height;
var cacheId = 'smaskGroupAt' + this.groupLevel;
var scratchCanvas = this.cachedCanvases.getCanvas(
cacheId, drawnWidth, drawnHeight, true);
var currentCtx = this.ctx;
var currentTransform = currentCtx.mozCurrentTransform;
this.ctx.save();
var groupCtx = scratchCanvas.context;
groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
groupCtx.transform.apply(groupCtx, currentTransform);
activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.setGState([
['BM', 'Normal'],
['ca', 1],
['CA', 1]
]);
this.groupStack.push(currentCtx);
this.groupLevel++;
},
suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
// Similar to endSMaskGroup, the intermediate canvas has to be composed
// and future ctx state restored.
var groupCtx = this.ctx;
this.groupLevel--;
this.ctx = this.groupStack.pop();
composeSMask(this.ctx, this.current.activeSMask, groupCtx);
this.ctx.restore();
this.ctx.save(); // save is needed since SMask will be resumed.
copyCtxState(groupCtx, this.ctx);
// Saving state for resuming.
this.current.resumeSMaskCtx = groupCtx;
// Transform was changed in the SMask canvas, reflecting this change on
// this.ctx.
var deltaTransform = Util.transform(
this.current.activeSMask.startTransformInverse,
groupCtx.mozCurrentTransform);
this.ctx.transform.apply(this.ctx, deltaTransform);
// SMask was composed, the results at the groupCtx can be cleared.
groupCtx.save();
groupCtx.setTransform(1, 0, 0, 1, 0, 0);
groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
groupCtx.restore();
},
resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
// Resuming state saved by suspendSMaskGroup. We don't need to restore
// any groupCtx state since restore() command (the only caller) will do
// that for us. See also beginSMaskGroup.
var groupCtx = this.current.resumeSMaskCtx;
var currentCtx = this.ctx;
this.ctx = groupCtx;
this.groupStack.push(currentCtx);
this.groupLevel++;
},
endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
var groupCtx = this.ctx;
this.groupLevel--;
this.ctx = this.groupStack.pop();
composeSMask(this.ctx, this.current.activeSMask, groupCtx);
this.ctx.restore();
copyCtxState(groupCtx, this.ctx);
// Transform was changed in the SMask canvas, reflecting this change on
// this.ctx.
var deltaTransform = Util.transform(
this.current.activeSMask.startTransformInverse,
groupCtx.mozCurrentTransform);
this.ctx.transform.apply(this.ctx, deltaTransform);
},
save: function CanvasGraphics_save() {
this.ctx.save();
var old = this.current;
this.stateStack.push(old);
this.current = old.clone();
this.current.resumeSMaskCtx = null;
},
restore: function CanvasGraphics_restore() {
// SMask was suspended, we just need to resume it.
if (this.current.resumeSMaskCtx) {
this.resumeSMaskGroup();
}
// SMask has to be finished once there is no states that are using the
// same SMask.
if (this.current.activeSMask !== null && (this.stateStack.length === 0 ||
this.stateStack[this.stateStack.length - 1].activeSMask !==
this.current.activeSMask)) {
this.endSMaskGroup();
}
if (this.stateStack.length !== 0) {
this.current = this.stateStack.pop();
this.ctx.restore();
// Ensure that the clipping path is reset (fixes issue6413.pdf).
this.pendingClip = null;
this.cachedGetSinglePixelWidth = null;
}
},
transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
this.ctx.transform(a, b, c, d, e, f);
this.cachedGetSinglePixelWidth = null;
},
// Path
constructPath: function CanvasGraphics_constructPath(ops, args) {
var ctx = this.ctx;
var current = this.current;
var x = current.x, y = current.y;
for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
switch (ops[i] | 0) {
case OPS.rectangle:
x = args[j++];
y = args[j++];
var width = args[j++];
var height = args[j++];
if (width === 0) {
width = this.getSinglePixelWidth();
}
if (height === 0) {
height = this.getSinglePixelWidth();
}
var xw = x + width;
var yh = y + height;
this.ctx.moveTo(x, y);
this.ctx.lineTo(xw, y);
this.ctx.lineTo(xw, yh);
this.ctx.lineTo(x, yh);
this.ctx.lineTo(x, y);
this.ctx.closePath();
break;
case OPS.moveTo:
x = args[j++];
y = args[j++];
ctx.moveTo(x, y);
break;
case OPS.lineTo:
x = args[j++];
y = args[j++];
ctx.lineTo(x, y);
break;
case OPS.curveTo:
x = args[j + 4];
y = args[j + 5];
ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
x, y);
j += 6;
break;
case OPS.curveTo2:
ctx.bezierCurveTo(x, y, args[j], args[j + 1],
args[j + 2], args[j + 3]);
x = args[j + 2];
y = args[j + 3];
j += 4;
break;
case OPS.curveTo3:
x = args[j + 2];
y = args[j + 3];
ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
j += 4;
break;
case OPS.closePath:
ctx.closePath();
break;
}
}
current.setCurrentPoint(x, y);
},
closePath: function CanvasGraphics_closePath() {
this.ctx.closePath();
},
stroke: function CanvasGraphics_stroke(consumePath) {
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
var ctx = this.ctx;
var strokeColor = this.current.strokeColor;
// Prevent drawing too thin lines by enforcing a minimum line width.
ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
this.current.lineWidth);
// For stroke we want to temporarily change the global alpha to the
// stroking alpha.
ctx.globalAlpha = this.current.strokeAlpha;
if (strokeColor && strokeColor.hasOwnProperty('type') &&
strokeColor.type === 'Pattern') {
// for patterns, we transform to pattern space, calculate
// the pattern, call stroke, and restore to user space
ctx.save();
ctx.strokeStyle = strokeColor.getPattern(ctx, this);
ctx.stroke();
ctx.restore();
} else {
ctx.stroke();
}
if (consumePath) {
this.consumePath();
}
// Restore the global alpha to the fill alpha
ctx.globalAlpha = this.current.fillAlpha;
},
closeStroke: function CanvasGraphics_closeStroke() {
this.closePath();
this.stroke();
},
fill: function CanvasGraphics_fill(consumePath) {
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
var ctx = this.ctx;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
var needRestore = false;
if (isPatternFill) {
ctx.save();
if (this.baseTransform) {
ctx.setTransform.apply(ctx, this.baseTransform);
}
ctx.fillStyle = fillColor.getPattern(ctx, this);
needRestore = true;
}
if (this.pendingEOFill) {
if (ctx.mozFillRule !== undefined) {
ctx.mozFillRule = 'evenodd';
ctx.fill();
ctx.mozFillRule = 'nonzero';
} else {
ctx.fill('evenodd');
}
this.pendingEOFill = false;
} else {
ctx.fill();
}
if (needRestore) {
ctx.restore();
}
if (consumePath) {
this.consumePath();
}
},
eoFill: function CanvasGraphics_eoFill() {
this.pendingEOFill = true;
this.fill();
},
fillStroke: function CanvasGraphics_fillStroke() {
this.fill(false);
this.stroke(false);
this.consumePath();
},
eoFillStroke: function CanvasGraphics_eoFillStroke() {
this.pendingEOFill = true;
this.fillStroke();
},
closeFillStroke: function CanvasGraphics_closeFillStroke() {
this.closePath();
this.fillStroke();
},
closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
this.pendingEOFill = true;
this.closePath();
this.fillStroke();
},
endPath: function CanvasGraphics_endPath() {
this.consumePath();
},
// Clipping
clip: function CanvasGraphics_clip() {
this.pendingClip = NORMAL_CLIP;
},
eoClip: function CanvasGraphics_eoClip() {
this.pendingClip = EO_CLIP;
},
// Text
beginText: function CanvasGraphics_beginText() {
this.current.textMatrix = IDENTITY_MATRIX;
this.current.textMatrixScale = 1;
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
},
endText: function CanvasGraphics_endText() {
var paths = this.pendingTextPaths;
var ctx = this.ctx;
if (paths === undefined) {
ctx.beginPath();
return;
}
ctx.save();
ctx.beginPath();
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
ctx.setTransform.apply(ctx, path.transform);
ctx.translate(path.x, path.y);
path.addToPath(ctx, path.fontSize);
}
ctx.restore();
ctx.clip();
ctx.beginPath();
delete this.pendingTextPaths;
},
setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
this.current.charSpacing = spacing;
},
setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
this.current.wordSpacing = spacing;
},
setHScale: function CanvasGraphics_setHScale(scale) {
this.current.textHScale = scale / 100;
},
setLeading: function CanvasGraphics_setLeading(leading) {
this.current.leading = -leading;
},
setFont: function CanvasGraphics_setFont(fontRefName, size) {
var fontObj = this.commonObjs.get(fontRefName);
var current = this.current;
if (!fontObj) {
error('Can\'t find font for ' + fontRefName);
}
current.fontMatrix = (fontObj.fontMatrix ?
fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
// A valid matrix needs all main diagonal elements to be non-zero
// This also ensures we bypass FF bugzilla bug #719844.
if (current.fontMatrix[0] === 0 ||
current.fontMatrix[3] === 0) {
warn('Invalid font matrix for font ' + fontRefName);
}
// The spec for Tf (setFont) says that 'size' specifies the font 'scale',
// and in some docs this can be negative (inverted x-y axes).
if (size < 0) {
size = -size;
current.fontDirection = -1;
} else {
current.fontDirection = 1;
}
this.current.font = fontObj;
this.current.fontSize = size;
if (fontObj.isType3Font) {
return; // we don't need ctx.font for Type3 fonts
}
var name = fontObj.loadedName || 'sans-serif';
var bold = fontObj.black ? '900' : (fontObj.bold ? 'bold' : 'normal');
var italic = fontObj.italic ? 'italic' : 'normal';
var typeface = '"' + name + '", ' + fontObj.fallbackName;
// Some font backends cannot handle fonts below certain size.
// Keeping the font at minimal size and using the fontSizeScale to change
// the current transformation matrix before the fillText/strokeText.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
this.current.fontSizeScale = size / browserFontSize;
var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
this.ctx.font = rule;
},
setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
this.current.textRenderingMode = mode;
},
setTextRise: function CanvasGraphics_setTextRise(rise) {
this.current.textRise = rise;
},
moveText: function CanvasGraphics_moveText(x, y) {
this.current.x = this.current.lineX += x;
this.current.y = this.current.lineY += y;
},
setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
this.setLeading(-y);
this.moveText(x, y);
},
setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
this.current.textMatrix = [a, b, c, d, e, f];
this.current.textMatrixScale = Math.sqrt(a * a + b * b);
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
},
nextLine: function CanvasGraphics_nextLine() {
this.moveText(0, this.current.leading);
},
paintChar: function CanvasGraphics_paintChar(character, x, y) {
var ctx = this.ctx;
var current = this.current;
var font = current.font;
var textRenderingMode = current.textRenderingMode;
var fontSize = current.fontSize / current.fontSizeScale;
var fillStrokeMode = textRenderingMode &
TextRenderingMode.FILL_STROKE_MASK;
var isAddToPathSet = !!(textRenderingMode &
TextRenderingMode.ADD_TO_PATH_FLAG);
var addToPath;
if (font.disableFontFace || isAddToPathSet) {
addToPath = font.getPathGenerator(this.commonObjs, character);
}
if (font.disableFontFace) {
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
addToPath(ctx, fontSize);
if (fillStrokeMode === TextRenderingMode.FILL ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.fill();
}
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.stroke();
}
ctx.restore();
} else {
if (fillStrokeMode === TextRenderingMode.FILL ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.fillText(character, x, y);
}
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.strokeText(character, x, y);
}
}
if (isAddToPathSet) {
var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
paths.push({
transform: ctx.mozCurrentTransform,
x: x,
y: y,
fontSize: fontSize,
addToPath: addToPath
});
}
},
get isFontSubpixelAAEnabled() {
// Checks if anti-aliasing is enabled when scaled text is painted.
// On Windows GDI scaled fonts looks bad.
var ctx = document.createElement('canvas').getContext('2d');
ctx.scale(1.5, 1);
ctx.fillText('I', 0, 10);
var data = ctx.getImageData(0, 0, 10, 10).data;
var enabled = false;
for (var i = 3; i < data.length; i += 4) {
if (data[i] > 0 && data[i] < 255) {
enabled = true;
break;
}
}
return shadow(this, 'isFontSubpixelAAEnabled', enabled);
},
showText: function CanvasGraphics_showText(glyphs) {
var current = this.current;
var font = current.font;
if (font.isType3Font) {
return this.showType3Text(glyphs);
}
var fontSize = current.fontSize;
if (fontSize === 0) {
return;
}
var ctx = this.ctx;
var fontSizeScale = current.fontSizeScale;
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var fontDirection = current.fontDirection;
var textHScale = current.textHScale * fontDirection;
var glyphsLength = glyphs.length;
var vertical = font.vertical;
var spacingDir = vertical ? 1 : -1;
var defaultVMetrics = font.defaultVMetrics;
var widthAdvanceScale = fontSize * current.fontMatrix[0];
var simpleFillText =
current.textRenderingMode === TextRenderingMode.FILL &&
!font.disableFontFace;
ctx.save();
ctx.transform.apply(ctx, current.textMatrix);
ctx.translate(current.x, current.y + current.textRise);
if (current.patternFill) {
// TODO: Some shading patterns are not applied correctly to text,
// e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
ctx.fillStyle = current.fillColor.getPattern(ctx, this);
}
if (fontDirection > 0) {
ctx.scale(textHScale, -1);
} else {
ctx.scale(textHScale, 1);
}
var lineWidth = current.lineWidth;
var scale = current.textMatrixScale;
if (scale === 0 || lineWidth === 0) {
var fillStrokeMode = current.textRenderingMode &
TextRenderingMode.FILL_STROKE_MASK;
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
this.cachedGetSinglePixelWidth = null;
lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
}
} else {
lineWidth /= scale;
}
if (fontSizeScale !== 1.0) {
ctx.scale(fontSizeScale, fontSizeScale);
lineWidth /= fontSizeScale;
}
ctx.lineWidth = lineWidth;
var x = 0, i;
for (i = 0; i < glyphsLength; ++i) {
var glyph = glyphs[i];
if (isNum(glyph)) {
x += spacingDir * glyph * fontSize / 1000;
continue;
}
var restoreNeeded = false;
var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
var character = glyph.fontChar;
var accent = glyph.accent;
var scaledX, scaledY, scaledAccentX, scaledAccentY;
var width = glyph.width;
if (vertical) {
var vmetric, vx, vy;
vmetric = glyph.vmetric || defaultVMetrics;
vx = glyph.vmetric ? vmetric[1] : width * 0.5;
vx = -vx * widthAdvanceScale;
vy = vmetric[2] * widthAdvanceScale;
width = vmetric ? -vmetric[0] : width;
scaledX = vx / fontSizeScale;
scaledY = (x + vy) / fontSizeScale;
} else {
scaledX = x / fontSizeScale;
scaledY = 0;
}
if (font.remeasure && width > 0) {
// Some standard fonts may not have the exact width: rescale per
// character if measured width is greater than expected glyph width
// and subpixel-aa is enabled, otherwise just center the glyph.
var measuredWidth = ctx.measureText(character).width * 1000 /
fontSize * fontSizeScale;
if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
var characterScaleX = width / measuredWidth;
restoreNeeded = true;
ctx.save();
ctx.scale(characterScaleX, 1);
scaledX /= characterScaleX;
} else if (width !== measuredWidth) {
scaledX += (width - measuredWidth) / 2000 *
fontSize / fontSizeScale;
}
}
// Only attempt to draw the glyph if it is actually in the embedded font
// file or if there isn't a font file so the fallback font is shown.
if (glyph.isInFont || font.missingFile) {
if (simpleFillText && !accent) {
// common case
ctx.fillText(character, scaledX, scaledY);
} else {
this.paintChar(character, scaledX, scaledY);
if (accent) {
scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
}
}
}
var charWidth = width * widthAdvanceScale + spacing * fontDirection;
x += charWidth;
if (restoreNeeded) {
ctx.restore();
}
}
if (vertical) {
current.y -= x * textHScale;
} else {
current.x += x * textHScale;
}
ctx.restore();
},
showType3Text: function CanvasGraphics_showType3Text(glyphs) {
// Type3 fonts - each glyph is a "mini-PDF"
var ctx = this.ctx;
var current = this.current;
var font = current.font;
var fontSize = current.fontSize;
var fontDirection = current.fontDirection;
var spacingDir = font.vertical ? 1 : -1;
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var textHScale = current.textHScale * fontDirection;
var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
var glyphsLength = glyphs.length;
var isTextInvisible =
current.textRenderingMode === TextRenderingMode.INVISIBLE;
var i, glyph, width, spacingLength;
if (isTextInvisible || fontSize === 0) {
return;
}
this.cachedGetSinglePixelWidth = null;
ctx.save();
ctx.transform.apply(ctx, current.textMatrix);
ctx.translate(current.x, current.y);
ctx.scale(textHScale, fontDirection);
for (i = 0; i < glyphsLength; ++i) {
glyph = glyphs[i];
if (isNum(glyph)) {
spacingLength = spacingDir * glyph * fontSize / 1000;
this.ctx.translate(spacingLength, 0);
current.x += spacingLength * textHScale;
continue;
}
var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
var operatorList = font.charProcOperatorList[glyph.operatorListId];
if (!operatorList) {
warn('Type3 character \"' + glyph.operatorListId +
'\" is not available');
continue;
}
this.processingType3 = glyph;
this.save();
ctx.scale(fontSize, fontSize);
ctx.transform.apply(ctx, fontMatrix);
this.executeOperatorList(operatorList);
this.restore();
var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
width = transformed[0] * fontSize + spacing;
ctx.translate(width, 0);
current.x += width * textHScale;
}
ctx.restore();
this.processingType3 = null;
},
// Type3 fonts
setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
// We can safely ignore this since the width should be the same
// as the width in the Widths array.
},
setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
yWidth,
llx,
lly,
urx,
ury) {
// TODO According to the spec we're also suppose to ignore any operators
// that set color or include images while processing this type3 font.
this.ctx.rect(llx, lly, urx - llx, ury - lly);
this.clip();
this.endPath();
},
// Color
getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
var pattern;
if (IR[0] === 'TilingPattern') {
var color = IR[1];
var baseTransform = this.baseTransform ||
this.ctx.mozCurrentTransform.slice();
var self = this;
var canvasGraphicsFactory = {
createCanvasGraphics: function (ctx) {
return new CanvasGraphics(ctx, self.commonObjs, self.objs);
}
};
pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
baseTransform);
} else {
pattern = getShadingPatternFromIR(IR);
}
return pattern;
},
setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
this.current.strokeColor = this.getColorN_Pattern(arguments);
},
setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
this.current.fillColor = this.getColorN_Pattern(arguments);
this.current.patternFill = true;
},
setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
var color = Util.makeCssRgb(r, g, b);
this.ctx.strokeStyle = color;
this.current.strokeColor = color;
},
setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
var color = Util.makeCssRgb(r, g, b);
this.ctx.fillStyle = color;
this.current.fillColor = color;
this.current.patternFill = false;
},
shadingFill: function CanvasGraphics_shadingFill(patternIR) {
var ctx = this.ctx;
this.save();
var pattern = getShadingPatternFromIR(patternIR);
ctx.fillStyle = pattern.getPattern(ctx, this, true);
var inv = ctx.mozCurrentTransformInverse;
if (inv) {
var canvas = ctx.canvas;
var width = canvas.width;
var height = canvas.height;
var bl = Util.applyTransform([0, 0], inv);
var br = Util.applyTransform([0, height], inv);
var ul = Util.applyTransform([width, 0], inv);
var ur = Util.applyTransform([width, height], inv);
var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
} else {
// HACK to draw the gradient onto an infinite rectangle.
// PDF gradients are drawn across the entire image while
// Canvas only allows gradients to be drawn in a rectangle
// The following bug should allow us to remove this.
// https://bugzilla.mozilla.org/show_bug.cgi?id=664884
this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
}
this.restore();
},
// Images
beginInlineImage: function CanvasGraphics_beginInlineImage() {
error('Should not call beginInlineImage');
},
beginImageData: function CanvasGraphics_beginImageData() {
error('Should not call beginImageData');
},
paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
bbox) {
this.save();
this.baseTransformStack.push(this.baseTransform);
if (isArray(matrix) && matrix.length === 6) {
this.transform.apply(this, matrix);
}
this.baseTransform = this.ctx.mozCurrentTransform;
if (isArray(bbox) && bbox.length === 4) {
var width = bbox[2] - bbox[0];
var height = bbox[3] - bbox[1];
this.ctx.rect(bbox[0], bbox[1], width, height);
this.clip();
this.endPath();
}
},
paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
this.restore();
this.baseTransform = this.baseTransformStack.pop();
},
beginGroup: function CanvasGraphics_beginGroup(group) {
this.save();
var currentCtx = this.ctx;
// TODO non-isolated groups - according to Rik at adobe non-isolated
// group results aren't usually that different and they even have tools
// that ignore this setting. Notes from Rik on implementing:
// - When you encounter an transparency group, create a new canvas with
// the dimensions of the bbox
// - copy the content from the previous canvas to the new canvas
// - draw as usual
// - remove the backdrop alpha:
// alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
// value of your transparency group and 'alphaBackdrop' the alpha of the
// backdrop
// - remove background color:
// colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
if (!group.isolated) {
info('TODO: Support non-isolated groups.');
}
// TODO knockout - supposedly possible with the clever use of compositing
// modes.
if (group.knockout) {
warn('Knockout groups not supported.');
}
var currentTransform = currentCtx.mozCurrentTransform;
if (group.matrix) {
currentCtx.transform.apply(currentCtx, group.matrix);
}
assert(group.bbox, 'Bounding box is required.');
// Based on the current transform figure out how big the bounding box
// will actually be.
var bounds = Util.getAxialAlignedBoundingBox(
group.bbox,
currentCtx.mozCurrentTransform);
// Clip the bounding box to the current canvas.
var canvasBounds = [0,
0,
currentCtx.canvas.width,
currentCtx.canvas.height];
bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
// Use ceil in case we're between sizes so we don't create canvas that is
// too small and make the canvas at least 1x1 pixels.
var offsetX = Math.floor(bounds[0]);
var offsetY = Math.floor(bounds[1]);
var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
var scaleX = 1, scaleY = 1;
if (drawnWidth > MAX_GROUP_SIZE) {
scaleX = drawnWidth / MAX_GROUP_SIZE;
drawnWidth = MAX_GROUP_SIZE;
}
if (drawnHeight > MAX_GROUP_SIZE) {
scaleY = drawnHeight / MAX_GROUP_SIZE;
drawnHeight = MAX_GROUP_SIZE;
}
var cacheId = 'groupAt' + this.groupLevel;
if (group.smask) {
// Using two cache entries is case if masks are used one after another.
cacheId += '_smask_' + ((this.smaskCounter++) % 2);
}
var scratchCanvas = this.cachedCanvases.getCanvas(
cacheId, drawnWidth, drawnHeight, true);
var groupCtx = scratchCanvas.context;
// Since we created a new canvas that is just the size of the bounding box
// we have to translate the group ctx.
groupCtx.scale(1 / scaleX, 1 / scaleY);
groupCtx.translate(-offsetX, -offsetY);
groupCtx.transform.apply(groupCtx, currentTransform);
if (group.smask) {
// Saving state and cached mask to be used in setGState.
this.smaskStack.push({
canvas: scratchCanvas.canvas,
context: groupCtx,
offsetX: offsetX,
offsetY: offsetY,
scaleX: scaleX,
scaleY: scaleY,
subtype: group.smask.subtype,
backdrop: group.smask.backdrop,
transferMap: group.smask.transferMap || null,
startTransformInverse: null, // used during suspend operation
});
} else {
// Setup the current ctx so when the group is popped we draw it at the
// right location.
currentCtx.setTransform(1, 0, 0, 1, 0, 0);
currentCtx.translate(offsetX, offsetY);
currentCtx.scale(scaleX, scaleY);
}
// The transparency group inherits all off the current graphics state
// except the blend mode, soft mask, and alpha constants.
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.setGState([
['BM', 'Normal'],
['ca', 1],
['CA', 1]
]);
this.groupStack.push(currentCtx);
this.groupLevel++;
// Reseting mask state, masks will be applied on restore of the group.
this.current.activeSMask = null;
},
endGroup: function CanvasGraphics_endGroup(group) {
this.groupLevel--;
var groupCtx = this.ctx;
this.ctx = this.groupStack.pop();
// Turn off image smoothing to avoid sub pixel interpolation which can
// look kind of blurry for some pdfs.
if (this.ctx.imageSmoothingEnabled !== undefined) {
this.ctx.imageSmoothingEnabled = false;
} else {
this.ctx.mozImageSmoothingEnabled = false;
}
if (group.smask) {
this.tempSMask = this.smaskStack.pop();
} else {
this.ctx.drawImage(groupCtx.canvas, 0, 0);
}
this.restore();
},
beginAnnotations: function CanvasGraphics_beginAnnotations() {
this.save();
this.current = new CanvasExtraState();
if (this.baseTransform) {
this.ctx.setTransform.apply(this.ctx, this.baseTransform);
}
},
endAnnotations: function CanvasGraphics_endAnnotations() {
this.restore();
},
beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
matrix) {
this.save();
if (isArray(rect) && rect.length === 4) {
var width = rect[2] - rect[0];
var height = rect[3] - rect[1];
this.ctx.rect(rect[0], rect[1], width, height);
this.clip();
this.endPath();
}
this.transform.apply(this, transform);
this.transform.apply(this, matrix);
},
endAnnotation: function CanvasGraphics_endAnnotation() {
this.restore();
},
paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
var domImage = this.objs.get(objId);
if (!domImage) {
warn('Dependent image isn\'t ready yet');
return;
}
this.save();
var ctx = this.ctx;
// scale the image to the unit square
ctx.scale(1 / w, -1 / h);
ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
0, -h, w, h);
if (this.imageLayer) {
var currentTransform = ctx.mozCurrentTransformInverse;
var position = this.getCanvasPosition(0, 0);
this.imageLayer.appendImage({
objId: objId,
left: position[0],
top: position[1],
width: w / currentTransform[0],
height: h / currentTransform[3]
});
}
this.restore();
},
paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
var ctx = this.ctx;
var width = img.width, height = img.height;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
var glyph = this.processingType3;
if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
glyph.compiled =
compileType3Glyph({data: img.data, width: width, height: height});
} else {
glyph.compiled = null;
}
}
if (glyph && glyph.compiled) {
glyph.compiled(ctx);
return;
}
var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, img);
maskCtx.globalCompositeOperation = 'source-in';
maskCtx.fillStyle = isPatternFill ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
this.paintInlineImageXObject(maskCanvas.canvas);
},
paintImageMaskXObjectRepeat:
function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
scaleY, positions) {
var width = imgData.width;
var height = imgData.height;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, imgData);
maskCtx.globalCompositeOperation = 'source-in';
maskCtx.fillStyle = isPatternFill ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
var ctx = this.ctx;
for (var i = 0, ii = positions.length; i < ii; i += 2) {
ctx.save();
ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
ctx.scale(1, -1);
ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
0, -1, 1, 1);
ctx.restore();
}
},
paintImageMaskXObjectGroup:
function CanvasGraphics_paintImageMaskXObjectGroup(images) {
var ctx = this.ctx;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
for (var i = 0, ii = images.length; i < ii; i++) {
var image = images[i];
var width = image.width, height = image.height;
var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, image);
maskCtx.globalCompositeOperation = 'source-in';
maskCtx.fillStyle = isPatternFill ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
ctx.save();
ctx.transform.apply(ctx, image.transform);
ctx.scale(1, -1);
ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
0, -1, 1, 1);
ctx.restore();
}
},
paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
this.paintInlineImageXObject(imgData);
},
paintImageXObjectRepeat:
function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
positions) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
var width = imgData.width;
var height = imgData.height;
var map = [];
for (var i = 0, ii = positions.length; i < ii; i += 2) {
map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
positions[i + 1]], x: 0, y: 0, w: width, h: height});
}
this.paintInlineImageXObjectGroup(imgData, map);
},
paintInlineImageXObject:
function CanvasGraphics_paintInlineImageXObject(imgData) {
var width = imgData.width;
var height = imgData.height;
var ctx = this.ctx;
this.save();
// scale the image to the unit square
ctx.scale(1 / width, -1 / height);
var currentTransform = ctx.mozCurrentTransformInverse;
var a = currentTransform[0], b = currentTransform[1];
var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
var c = currentTransform[2], d = currentTransform[3];
var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
var imgToPaint, tmpCanvas;
// instanceof HTMLElement does not work in jsdom node.js module
if (imgData instanceof HTMLElement || !imgData.data) {
imgToPaint = imgData;
} else {
tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
width, height);
var tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
imgToPaint = tmpCanvas.canvas;
}
var paintWidth = width, paintHeight = height;
var tmpCanvasId = 'prescale1';
// Vertial or horizontal scaling shall not be more than 2 to not loose the
// pixels during drawImage operation, painting on the temporary canvas(es)
// that are twice smaller in size
while ((widthScale > 2 && paintWidth > 1) ||
(heightScale > 2 && paintHeight > 1)) {
var newWidth = paintWidth, newHeight = paintHeight;
if (widthScale > 2 && paintWidth > 1) {
newWidth = Math.ceil(paintWidth / 2);
widthScale /= paintWidth / newWidth;
}
if (heightScale > 2 && paintHeight > 1) {
newHeight = Math.ceil(paintHeight / 2);
heightScale /= paintHeight / newHeight;
}
tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
newWidth, newHeight);
tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, newWidth, newHeight);
tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
0, 0, newWidth, newHeight);
imgToPaint = tmpCanvas.canvas;
paintWidth = newWidth;
paintHeight = newHeight;
tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
}
ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
0, -height, width, height);
if (this.imageLayer) {
var position = this.getCanvasPosition(0, -height);
this.imageLayer.appendImage({
imgData: imgData,
left: position[0],
top: position[1],
width: width / currentTransform[0],
height: height / currentTransform[3]
});
}
this.restore();
},
paintInlineImageXObjectGroup:
function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
var ctx = this.ctx;
var w = imgData.width;
var h = imgData.height;
var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
var tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
for (var i = 0, ii = map.length; i < ii; i++) {
var entry = map[i];
ctx.save();
ctx.transform.apply(ctx, entry.transform);
ctx.scale(1, -1);
ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
0, -1, 1, 1);
if (this.imageLayer) {
var position = this.getCanvasPosition(entry.x, entry.y);
this.imageLayer.appendImage({
imgData: imgData,
left: position[0],
top: position[1],
width: w,
height: h
});
}
ctx.restore();
}
},
paintSolidColorImageMask:
function CanvasGraphics_paintSolidColorImageMask() {
this.ctx.fillRect(0, 0, 1, 1);
},
paintXObject: function CanvasGraphics_paintXObject() {
warn('Unsupported \'paintXObject\' command.');
},
// Marked content
markPoint: function CanvasGraphics_markPoint(tag) {
// TODO Marked content.
},
markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
// TODO Marked content.
},
beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
// TODO Marked content.
},
beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
tag, properties) {
// TODO Marked content.
},
endMarkedContent: function CanvasGraphics_endMarkedContent() {
// TODO Marked content.
},
// Compatibility
beginCompat: function CanvasGraphics_beginCompat() {
// TODO ignore undefined operators (should we do that anyway?)
},
endCompat: function CanvasGraphics_endCompat() {
// TODO stop ignoring undefined operators
},
// Helper functions
consumePath: function CanvasGraphics_consumePath() {
var ctx = this.ctx;
if (this.pendingClip) {
if (this.pendingClip === EO_CLIP) {
if (ctx.mozFillRule !== undefined) {
ctx.mozFillRule = 'evenodd';
ctx.clip();
ctx.mozFillRule = 'nonzero';
} else {
ctx.clip('evenodd');
}
} else {
ctx.clip();
}
this.pendingClip = null;
}
ctx.beginPath();
},
getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
if (this.cachedGetSinglePixelWidth === null) {
// NOTE: The `save` and `restore` commands used below is a workaround
// that is necessary in order to prevent `mozCurrentTransformInverse`
// from intermittently returning incorrect values in Firefox, see:
// https://github.com/mozilla/pdf.js/issues/7188.
this.ctx.save();
var inverse = this.ctx.mozCurrentTransformInverse;
this.ctx.restore();
// max of the current horizontal and vertical scale
this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
(inverse[0] * inverse[0] + inverse[1] * inverse[1]),
(inverse[2] * inverse[2] + inverse[3] * inverse[3])));
}
return this.cachedGetSinglePixelWidth;
},
getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
var transform = this.ctx.mozCurrentTransform;
return [
transform[0] * x + transform[2] * y + transform[4],
transform[1] * x + transform[3] * y + transform[5]
];
}
};
for (var op in OPS) {
CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
}
return CanvasGraphics;
})();
exports.CanvasGraphics = CanvasGraphics;
exports.createScratchCanvas = createScratchCanvas;
}));