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
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
|
#============================================================+
# File name : tcpdf.rb
# Begin : 2002-08-03
# Last Update : 2007-03-20
# Author : Nicola Asuni
# Version : 1.53.0.TC031
# License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
#
# Description : This is a Ruby class for generating PDF files
# on-the-fly without requiring external
# extensions.
#
# IMPORTANT:
# This class is an extension and improvement of the Public Domain
# FPDF class by Olivier Plathey (http://www.fpdf.org).
#
# Main changes by Nicola Asuni:
# Ruby porting;
# UTF-8 Unicode support;
# code refactoring;
# source code clean up;
# code style and formatting;
# source code documentation using phpDocumentor (www.phpdoc.org);
# All ISO page formats were included;
# image scale factor;
# includes methods to parse and printsome XHTML code, supporting the following elements: h1, h2, h3, h4, h5, h6, b, u, i, a, img, p, br, strong, em, font, blockquote, li, ul, ol, hr, td, th, tr, table, sup, sub, small;
# includes a method to print various barcode formats using an improved version of "Generic Barcode Render Class" by Karim Mribti (http://www.mribti.com/barcode/) (require GD library: http://www.boutell.com/gd/);
# defines standard Header() and Footer() methods.
#
# Ported to Ruby by Ed Moss 2007-08-06
#
#============================================================+
#
# TCPDF Class.
# @package com.tecnick.tcpdf
#
@@version = "1.53.0.TC031"
@@fpdf_charwidths = {}
PDF_PRODUCER = 'TCPDF via RFPDF 1.53.0.TC031 (http://tcpdf.sourceforge.net)'
module TCPDFFontDescriptor
@@descriptors = { 'freesans' => {} }
@@font_name = 'freesans'
def self.font(font_name)
@@descriptors[font_name.gsub(".rb", "")]
end
def self.define(font_name = 'freesans')
@@descriptors[font_name] ||= {}
yield @@descriptors[font_name]
end
end
# This is a Ruby class for generating PDF files on-the-fly without requiring external extensions.<br>
# This class is an extension and improvement of the FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
# This version contains some changes: [porting to Ruby, support for UTF-8 Unicode, code style and formatting, php documentation (www.phpdoc.org), ISO page formats, minor improvements, image scale factor]<br>
# TCPDF project (http://tcpdf.sourceforge.net) is based on the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
# To add your own TTF fonts please read /fonts/README.TXT
# @name TCPDF
# @package com.tecnick.tcpdf
# @@version 1.53.0.TC031
# @author Nicola Asuni
# @link http://tcpdf.sourceforge.net
# @license http://www.gnu.org/copyleft/lesser.html LGPL
#
class TCPDF
include RFPDF
include Core::RFPDF
include RFPDF::Math
def logger
Rails.logger
end
cattr_accessor :k_cell_height_ratio
@@k_cell_height_ratio = 1.25
cattr_accessor :k_blank_image
@@k_blank_image = ""
cattr_accessor :k_small_ratio
@@k_small_ratio = 2/3.0
cattr_accessor :k_path_cache
@@k_path_cache = Rails.root.join('tmp')
cattr_accessor :k_path_url_cache
@@k_path_url_cache = Rails.root.join('tmp')
cattr_accessor :decoder
attr_accessor :barcode
attr_accessor :buffer
attr_accessor :diffs
attr_accessor :color_flag
attr_accessor :default_table_columns
attr_accessor :max_table_columns
attr_accessor :default_font
attr_accessor :draw_color
attr_accessor :encoding
attr_accessor :fill_color
attr_accessor :fonts
attr_accessor :font_family
attr_accessor :font_files
cattr_accessor :font_path
attr_accessor :font_style
attr_accessor :font_size_pt
attr_accessor :header_width
attr_accessor :header_logo
attr_accessor :header_logo_width
attr_accessor :header_title
attr_accessor :header_string
attr_accessor :images
attr_accessor :img_scale
attr_accessor :in_footer
attr_accessor :is_unicode
attr_accessor :lasth
attr_accessor :links
attr_accessor :list_ordered
attr_accessor :list_count
attr_accessor :li_spacer
attr_accessor :n
attr_accessor :offsets
attr_accessor :orientation_changes
attr_accessor :page
attr_accessor :page_links
attr_accessor :pages
attr_accessor :pdf_version
attr_accessor :prevfill_color
attr_accessor :prevtext_color
attr_accessor :print_header
attr_accessor :print_footer
attr_accessor :state
attr_accessor :tableborder
attr_accessor :tdbegin
attr_accessor :tdwidth
attr_accessor :tdheight
attr_accessor :tdalign
attr_accessor :tdfill
attr_accessor :tempfontsize
attr_accessor :text_color
attr_accessor :underline
attr_accessor :ws
#
# This is the class constructor.
# It allows to set up the page format, the orientation and
# the measure unit used in all the methods (except for the font sizes).
# @since 1.0
# @param string :orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
# @param string :unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
# @param mixed :format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
# @param boolean :unicode TRUE means that the input text is unicode (default = true)
# @param String :encoding charset encoding; default is UTF-8
#
def initialize(orientation = 'P', unit = 'mm', format = 'A4', unicode = true, encoding = "UTF-8")
# Set internal character encoding to ASCII#
#FIXME 2007-05-25 (EJM) Level=0 -
# if (respond_to?("mb_internal_encoding") and mb_internal_encoding())
# @internal_encoding = mb_internal_encoding();
# mb_internal_encoding("ASCII");
# }
#Some checks
dochecks();
begin
@@decoder = HTMLEntities.new
rescue
@@decoder = nil
end
#Initialization of properties
@barcode ||= false
@buffer ||= ''
@diffs ||= []
@color_flag ||= false
@default_table_columns ||= 4
@table_columns ||= 0
@max_table_columns ||= []
@tr_id ||= 0
@max_td_page ||= []
@max_td_y ||= []
@t_columns ||= 0
@default_font ||= "FreeSans" if unicode
@default_font ||= "Helvetica"
@draw_color ||= '0 G'
@encoding ||= "UTF-8"
@fill_color ||= '0 g'
@fonts ||= {}
@font_family ||= ''
@font_files ||= {}
@font_style ||= ''
@font_size ||= 12
@font_size_pt ||= 12
@header_width ||= 0
@header_logo ||= ""
@header_logo_width ||= 30
@header_title ||= ""
@header_string ||= ""
@images ||= {}
@img_scale ||= 1
@in_footer ||= false
@is_unicode = unicode
@lasth ||= 0
@links ||= []
@list_ordered ||= []
@list_count ||= []
@li_spacer ||= ""
@li_count ||= 0
@spacer ||= ""
@quote_count ||= 0
@prevquote_count ||= 0
@quote_top ||= []
@quote_page ||= []
@n ||= 2
@offsets ||= []
@orientation_changes ||= []
@page ||= 0
@page_links ||= {}
@pages ||= []
@pdf_version ||= "1.3"
@prevfill_color ||= [255,255,255]
@prevtext_color ||= [0,0,0]
@print_header ||= false
@print_footer ||= false
@state ||= 0
@tableborder ||= 0
@tdbegin ||= false
@tdwidth ||= 0
@tdheight ||= 0
@tdalign ||= "L"
@tdfill ||= 0
@tempfontsize ||= 10
@text_color ||= '0 g'
@underline ||= false
@deleted ||= false
@ws ||= 0
#Standard Unicode fonts
@core_fonts = {
'courier'=>'Courier',
'courierB'=>'Courier-Bold',
'courierI'=>'Courier-Oblique',
'courierBI'=>'Courier-BoldOblique',
'helvetica'=>'Helvetica',
'helveticaB'=>'Helvetica-Bold',
'helveticaI'=>'Helvetica-Oblique',
'helveticaBI'=>'Helvetica-BoldOblique',
'times'=>'Times-Roman',
'timesB'=>'Times-Bold',
'timesI'=>'Times-Italic',
'timesBI'=>'Times-BoldItalic',
'symbol'=>'Symbol',
'zapfdingbats'=>'ZapfDingbats'}
#Scale factor
case unit.downcase
when 'pt' ; @k=1
when 'mm' ; @k=72/25.4
when 'cm' ; @k=72/2.54
when 'in' ; @k=72
else Error("Incorrect unit: #{unit}")
end
#Page format
if format.is_a?(String)
# Page formats (45 standard ISO paper formats and 4 american common formats).
# Paper cordinates are calculated in this way: (inches# 72) where (1 inch = 2.54 cm)
case (format.upcase)
when '4A0' ; format = [4767.87,6740.79]
when '2A0' ; format = [3370.39,4767.87]
when 'A0' ; format = [2383.94,3370.39]
when 'A1' ; format = [1683.78,2383.94]
when 'A2' ; format = [1190.55,1683.78]
when 'A3' ; format = [841.89,1190.55]
when 'A4' ; format = [595.28,841.89] # ; default
when 'A5' ; format = [419.53,595.28]
when 'A6' ; format = [297.64,419.53]
when 'A7' ; format = [209.76,297.64]
when 'A8' ; format = [147.40,209.76]
when 'A9' ; format = [104.88,147.40]
when 'A10' ; format = [73.70,104.88]
when 'B0' ; format = [2834.65,4008.19]
when 'B1' ; format = [2004.09,2834.65]
when 'B2' ; format = [1417.32,2004.09]
when 'B3' ; format = [1000.63,1417.32]
when 'B4' ; format = [708.66,1000.63]
when 'B5' ; format = [498.90,708.66]
when 'B6' ; format = [354.33,498.90]
when 'B7' ; format = [249.45,354.33]
when 'B8' ; format = [175.75,249.45]
when 'B9' ; format = [124.72,175.75]
when 'B10' ; format = [87.87,124.72]
when 'C0' ; format = [2599.37,3676.54]
when 'C1' ; format = [1836.85,2599.37]
when 'C2' ; format = [1298.27,1836.85]
when 'C3' ; format = [918.43,1298.27]
when 'C4' ; format = [649.13,918.43]
when 'C5' ; format = [459.21,649.13]
when 'C6' ; format = [323.15,459.21]
when 'C7' ; format = [229.61,323.15]
when 'C8' ; format = [161.57,229.61]
when 'C9' ; format = [113.39,161.57]
when 'C10' ; format = [79.37,113.39]
when 'RA0' ; format = [2437.80,3458.27]
when 'RA1' ; format = [1729.13,2437.80]
when 'RA2' ; format = [1218.90,1729.13]
when 'RA3' ; format = [864.57,1218.90]
when 'RA4' ; format = [609.45,864.57]
when 'SRA0' ; format = [2551.18,3628.35]
when 'SRA1' ; format = [1814.17,2551.18]
when 'SRA2' ; format = [1275.59,1814.17]
when 'SRA3' ; format = [907.09,1275.59]
when 'SRA4' ; format = [637.80,907.09]
when 'LETTER' ; format = [612.00,792.00]
when 'LEGAL' ; format = [612.00,1008.00]
when 'EXECUTIVE' ; format = [521.86,756.00]
when 'FOLIO' ; format = [612.00,936.00]
#else then Error("Unknown page format: #{format}"
end
@fw_pt = format[0]
@fh_pt = format[1]
else
@fw_pt = format[0]*@k
@fh_pt = format[1]*@k
end
@fw = @fw_pt/@k
@fh = @fh_pt/@k
#Page orientation
orientation = orientation.downcase
if orientation == 'p' or orientation == 'portrait'
@def_orientation = 'P'
@w_pt = @fw_pt
@h_pt = @fh_pt
elsif orientation == 'l' or orientation == 'landscape'
@def_orientation = 'L'
@w_pt = @fh_pt
@h_pt = @fw_pt
else
Error("Incorrect orientation: #{orientation}")
end
@cur_orientation = @def_orientation
@w = @w_pt/@k
@h = @h_pt/@k
#Page margins (1 cm)
margin = 28.35/@k
SetMargins(margin, margin)
#Interior cell margin (1 mm)
@c_margin = margin / 10
#Line width (0.2 mm)
@line_width = 0.567 / @k
#Automatic page break
SetAutoPageBreak(true, 2 * margin)
#Full width display mode
SetDisplayMode('fullwidth')
#Compression
SetCompression(true)
#Set default PDF version number
@pdf_version = "1.3"
@encoding = encoding
@b = 0
@i = 0
@u = 0
@href = ''
@fontlist = ["arial", "times", "courier", "helvetica", "symbol"]
@issetfont = false
@issetcolor = false
SetFillColor(200, 200, 200, true)
SetTextColor(0, 0, 0, true)
end
#
# Set the image scale.
# @param float :scale image scale.
# @author Nicola Asuni
# @since 1.5.2
#
def SetImageScale(scale)
@img_scale = scale;
end
alias_method :set_image_scale, :SetImageScale
#
# Returns the image scale.
# @return float image scale.
# @author Nicola Asuni
# @since 1.5.2
#
def GetImageScale()
return @img_scale;
end
alias_method :get_image_scale, :GetImageScale
#
# Returns the page width in units.
# @return int page width.
# @author Nicola Asuni
# @since 1.5.2
#
def GetPageWidth()
return @w;
end
alias_method :get_page_width, :GetPageWidth
#
# Returns the page height in units.
# @return int page height.
# @author Nicola Asuni
# @since 1.5.2
#
def GetPageHeight()
return @h;
end
alias_method :get_page_height, :GetPageHeight
#
# Returns the page break margin.
# @return int page break margin.
# @author Nicola Asuni
# @since 1.5.2
#
def GetBreakMargin()
return @b_margin;
end
alias_method :get_break_margin, :GetBreakMargin
#
# Returns the scale factor (number of points in user unit).
# @return int scale factor.
# @author Nicola Asuni
# @since 1.5.2
#
def GetScaleFactor()
return @k;
end
alias_method :get_scale_factor, :GetScaleFactor
#
# Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
# @param float :left Left margin.
# @param float :top Top margin.
# @param float :right Right margin. Default value is the left one.
# @since 1.0
# @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
#
def SetMargins(left, top, right=-1)
#Set left, top and right margins
@l_margin = left
@t_margin = top
if (right == -1)
right = left
end
@r_margin = right
end
alias_method :set_margins, :SetMargins
#
# Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
# @param float :margin The margin.
# @since 1.4
# @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
#
def SetLeftMargin(margin)
#Set left margin
@l_margin = margin
if ((@page>0) and (@x < margin))
@x = margin
end
end
alias_method :set_left_margin, :SetLeftMargin
#
# Defines the top margin. The method can be called before creating the first page.
# @param float :margin The margin.
# @since 1.5
# @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
#
def SetTopMargin(margin)
#Set top margin
@t_margin = margin
end
alias_method :set_top_margin, :SetTopMargin
#
# Defines the right margin. The method can be called before creating the first page.
# @param float :margin The margin.
# @since 1.5
# @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
#
def SetRightMargin(margin)
#Set right margin
@r_margin = margin
end
alias_method :set_right_margin, :SetRightMargin
#
# Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
# @param boolean :auto Boolean indicating if mode should be on or off.
# @param float :margin Distance from the bottom of the page.
# @since 1.0
# @see Cell(), MultiCell(), AcceptPageBreak()
#
def SetAutoPageBreak(auto, margin=0)
#Set auto page break mode and triggering margin
@auto_page_break = auto
@b_margin = margin
@page_break_trigger = @h - margin
end
alias_method :set_auto_page_break, :SetAutoPageBreak
#
# Defines the way the document is to be displayed by the viewer. The zoom level can be set: pages can be displayed entirely on screen, occupy the full width of the window, use real size, be scaled by a specific zooming factor or use viewer default (configured in the Preferences menu of Acrobat). The page layout can be specified too: single at once, continuous display, two columns or viewer default. By default, documents use the full width mode with continuous display.
# @param mixed :zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
# @param string :layout The page layout. Possible values are:<ul><li>single: displays one page at once</li><li>continuous: displays pages continuously (default)</li><li>two: displays two pages on two columns</li><li>default: uses viewer default mode</li></ul>
# @since 1.2
#
def SetDisplayMode(zoom, layout = 'continuous')
#Set display mode in viewer
if (zoom == 'fullpage' or zoom == 'fullwidth' or zoom == 'real' or zoom == 'default' or !zoom.is_a?(String))
@zoom_mode = zoom
else
Error("Incorrect zoom display mode: #{zoom}")
end
if (layout == 'single' or layout == 'continuous' or layout == 'two' or layout == 'default')
@layout_mode = layout
else
Error("Incorrect layout display mode: #{layout}")
end
end
alias_method :set_display_mode, :SetDisplayMode
#
# Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
# Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
# @param boolean :compress Boolean indicating if compression must be enabled.
# @since 1.4
#
def SetCompression(compress)
#Set page compression
if (respond_to?('gzcompress'))
@compress = compress
else
@compress = false
end
end
alias_method :set_compression, :SetCompression
#
# Defines the title of the document.
# @param string :title The title.
# @since 1.2
# @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
#
def SetTitle(title)
#Title of document
@title = title
end
alias_method :set_title, :SetTitle
#
# Defines the subject of the document.
# @param string :subject The subject.
# @since 1.2
# @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
#
def SetSubject(subject)
#Subject of document
@subject = subject
end
alias_method :set_subject, :SetSubject
#
# Defines the author of the document.
# @param string :author The name of the author.
# @since 1.2
# @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
#
def SetAuthor(author)
#Author of document
@author = author
end
alias_method :set_author, :SetAuthor
#
# Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
# @param string :keywords The list of keywords.
# @since 1.2
# @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
#
def SetKeywords(keywords)
#Keywords of document
@keywords = keywords
end
alias_method :set_keywords, :SetKeywords
#
# Defines the creator of the document. This is typically the name of the application that generates the PDF.
# @param string :creator The name of the creator.
# @since 1.2
# @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
#
def SetCreator(creator)
#Creator of document
@creator = creator
end
alias_method :set_creator, :SetCreator
#
# Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
# <b>Example:</b><br />
# <pre>
# class PDF extends TCPDF {
# def Footer()
# #Go to 1.5 cm from bottom
# SetY(-15);
# #Select Arial italic 8
# SetFont('Arial','I',8);
# #Print current and total page numbers
# Cell(0,10,'Page '.PageNo().'/{nb}',0,0,'C');
# end
# }
# :pdf=new PDF();
# :pdf->alias_nb_pages();
# </pre>
# @param string :alias The alias. Default valuenb}.
# @since 1.4
# @see PageNo(), Footer()
#
def AliasNbPages(alias_nb ='{nb}')
#Define an alias for total number of pages
@alias_nb_pages = escapetext(alias_nb)
end
alias_method :alias_nb_pages, :AliasNbPages
#
# This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
# 2004-06-11 :: Nicola Asuni : changed bold tag with strong
# @param string :msg The error message
# @since 1.0
#
def Error(msg)
#Fatal error
raise ("TCPDF error: #{msg}")
end
alias_method :error, :Error
#
# This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
# Note: no page is created by this method
# @since 1.0
# @see AddPage(), Close()
#
def Open()
#Begin document
@state = 1
end
# alias_method :open, :Open
#
# Terminates the PDF document. It is not necessary to call this method explicitly because Output() does it automatically. If the document contains no page, AddPage() is called to prevent from getting an invalid document.
# @since 1.0
# @see Open(), Output()
#
def Close()
#Terminate document
if (@state==3)
return;
end
if (@page==0)
AddPage();
end
#Page footer
@in_footer=true;
Footer();
@in_footer=false;
#Close page
endpage();
#Close document
enddoc();
end
# alias_method :close, :Close
#
# Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer. Then the page is added, the current position set to the top-left corner according to the left and top margins, and Header() is called to display the header.
# The font which was set before calling is automatically restored. There is no need to call SetFont() again if you want to continue with the same font. The same is true for colors and line width.
# The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
# @param string :orientation Page orientation. Possible values are (case insensitive):<ul><li>P or Portrait</li><li>L or Landscape</li></ul> The default value is the one passed to the constructor.
# @since 1.0
# @see TCPDF(), Header(), Footer(), SetMargins()
#
def AddPage(orientation='')
#Start a new page
if (@state==0)
Open();
end
family=@font_family;
style=@font_style + (@underline ? 'U' : '') + (@deleted ? 'D' : '');
size=@font_size_pt;
lw=@line_width;
dc=@draw_color;
fc=@fill_color;
tc=@text_color;
cf=@color_flag;
if (@page>0)
#Page footer
@in_footer=true;
Footer();
@in_footer=false;
#Close page
endpage();
end
#Start new page
beginpage(orientation);
#Set line cap style to square
out('2 J');
#Set line width
@line_width = lw;
out(sprintf('%.2f w', lw*@k));
#Set font
if (family)
SetFont(family, style, size);
end
#Set colors
@draw_color = dc;
if (dc!='0 G')
out(dc);
end
@fill_color = fc;
if (fc!='0 g')
out(fc);
end
@text_color = tc;
@color_flag = cf;
#Page header
Header();
#Restore line width
if (@line_width != lw)
@line_width = lw;
out(sprintf('%.2f w', lw*@k));
end
#Restore font
if (family)
SetFont(family, style, size);
end
#Restore colors
if (@draw_color != dc)
@draw_color = dc;
out(dc);
end
if (@fill_color != fc)
@fill_color = fc;
out(fc);
end
@text_color = tc;
@color_flag = cf;
end
alias_method :add_page, :AddPage
#
# Rotate object.
# @param float :angle angle in degrees for counter-clockwise rotation
# @param int :x abscissa of the rotation center. Default is current x position
# @param int :y ordinate of the rotation center. Default is current y position
#
def Rotate(angle, x="", y="")
if (x == '')
x = @x;
end
if (y == '')
y = @y;
end
if (@rtl)
x = @w - x;
angle = -@angle;
end
y = (@h - y) * @k;
x *= @k;
# calculate elements of transformation matrix
tm = []
tm[0] = ::Math::cos(deg2rad(angle));
tm[1] = ::Math::sin(deg2rad(angle));
tm[2] = -tm[1];
tm[3] = tm[0];
tm[4] = x + tm[1] * y - tm[0] * x;
tm[5] = y - tm[0] * y - tm[1] * x;
# generate the transformation matrix
Transform(tm);
end
alias_method :rotate, :Rotate
#
# Starts a 2D tranformation saving current graphic state.
# This function must be called before scaling, mirroring, translation, rotation and skewing.
# Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
#
def StartTransform
out('q');
end
alias_method :start_transform, :StartTransform
#
# Stops a 2D tranformation restoring previous graphic state.
# This function must be called after scaling, mirroring, translation, rotation and skewing.
# Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
#
def StopTransform
out('Q');
end
alias_method :stop_transform, :StopTransform
#
# Apply graphic transformations.
# @since 2.1.000 (2008-01-07)
# @see StartTransform(), StopTransform()
#
def Transform(tm)
x = out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]));
end
alias_method :transform, :Transform
#
# Set header data.
# @param string :ln header image logo
# @param string :lw header image logo width in mm
# @param string :ht string to print as title on document header
# @param string :hs string to print on document header
#
def SetHeaderData(ln="", lw=0, ht="", hs="")
@header_logo = ln || ""
@header_logo_width = lw || 0
@header_title = ht || ""
@header_string = hs || ""
end
alias_method :set_header_data, :SetHeaderData
#
# Set header margin.
# (minimum distance between header and top page margin)
# @param int :hm distance in millimeters
#
def SetHeaderMargin(hm=10)
@header_margin = hm;
end
alias_method :set_header_margin, :SetHeaderMargin
#
# Set footer margin.
# (minimum distance between footer and bottom page margin)
# @param int :fm distance in millimeters
#
def SetFooterMargin(fm=10)
@footer_margin = fm;
end
alias_method :set_footer_margin, :SetFooterMargin
#
# Set a flag to print page header.
# @param boolean :val set to true to print the page header (default), false otherwise.
#
def SetPrintHeader(val=true)
@print_header = val;
end
alias_method :set_print_header, :SetPrintHeader
#
# Set a flag to print page footer.
# @param boolean :value set to true to print the page footer (default), false otherwise.
#
def SetPrintFooter(val=true)
@print_footer = val;
end
alias_method :set_print_footer, :SetPrintFooter
#
# This method is used to render the page header.
# It is automatically called by AddPage() and could be overwritten in your own inherited class.
#
def Header()
if (@print_header)
if (@original_l_margin.nil?)
@original_l_margin = @l_margin;
end
if (@original_r_margin.nil?)
@original_r_margin = @r_margin;
end
#set current position
SetXY(@original_l_margin, @header_margin);
if ((@header_logo) and (@header_logo != @@k_blank_image))
Image(@header_logo, @original_l_margin, @header_margin, @header_logo_width);
else
@img_rb_y = GetY();
end
cell_height = ((@@k_cell_height_ratio * @header_font[2]) / @k).round(2)
header_x = @original_l_margin + (@header_logo_width * 1.05); #set left margin for text data cell
# header title
SetFont(@header_font[0], 'B', @header_font[2] + 1);
SetX(header_x);
Cell(@header_width, cell_height, @header_title, 0, 1, 'L');
# header string
SetFont(@header_font[0], @header_font[1], @header_font[2]);
SetX(header_x);
MultiCell(@header_width, cell_height, @header_string, 0, 'L', 0);
# print an ending header line
if (@header_width)
#set style for cell border
SetLineWidth(0.3);
SetDrawColor(0, 0, 0);
SetY(1 + (@img_rb_y > GetY() ? @img_rb_y : GetY()));
SetX(@original_l_margin);
Cell(0, 0, '', 'T', 0, 'C');
end
#restore position
SetXY(@original_l_margin, @t_margin);
end
end
alias_method :header, :Header
#
# This method is used to render the page footer.
# It is automatically called by AddPage() and could be overwritten in your own inherited class.
#
def Footer()
if (@print_footer)
if (@original_l_margin.nil?)
@original_l_margin = @l_margin;
end
if (@original_r_margin.nil?)
@original_r_margin = @r_margin;
end
#set font
SetFont(@footer_font[0], @footer_font[1] , @footer_font[2]);
#set style for cell border
line_width = 0.3;
SetLineWidth(line_width);
SetDrawColor(0, 0, 0);
footer_height = ((@@k_cell_height_ratio * @footer_font[2]) / @k).round; #footer height, was , 2)
#get footer y position
footer_y = @h - @footer_margin - footer_height;
#set current position
SetXY(@original_l_margin, footer_y);
#print document barcode
if (@barcode)
Ln();
barcode_width = ((@w - @original_l_margin - @original_r_margin)).round; #max width
writeBarcode(@original_l_margin, footer_y + line_width, barcode_width, footer_height - line_width, "C128B", false, false, 2, @barcode);
end
SetXY(@original_l_margin, footer_y);
#Print page number
Cell(0, footer_height, @l['w_page'] + " " + PageNo().to_s + ' / {nb}', 'T', 0, 'R');
end
end
alias_method :footer, :Footer
#
# Returns the current page number.
# @return int page number
# @since 1.0
# @see alias_nb_pages()
#
def PageNo()
#Get current page number
return @page;
end
alias_method :page_no, :PageNo
#
# Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
# @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
# @param int :g Green component (between 0 and 255)
# @param int :b Blue component (between 0 and 255)
# @since 1.3
# @see SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
#
def SetDrawColor(r, g=-1, b=-1)
#Set color for all stroking operations
if ((r==0 and g==0 and b==0) or g==-1)
@draw_color=sprintf('%.3f G', r/255.0);
else
@draw_color=sprintf('%.3f %.3f %.3f RG', r/255.0, g/255.0, b/255.0);
end
if (@page>0)
out(@draw_color);
end
end
alias_method :set_draw_color, :SetDrawColor
#
# Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
# @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
# @param int :g Green component (between 0 and 255)
# @param int :b Blue component (between 0 and 255)
# @param boolean :storeprev if true stores the RGB array on :prevfill_color variable.
# @since 1.3
# @see SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
#
def SetFillColor(r, g=-1, b=-1, storeprev=false)
#Set color for all filling operations
if ((r==0 and g==0 and b==0) or g==-1)
@fill_color=sprintf('%.3f g', r/255.0);
else
@fill_color=sprintf('%.3f %.3f %.3f rg', r/255.0, g/255.0, b/255.0);
end
@color_flag=(@fill_color!=@text_color);
if (@page>0)
out(@fill_color);
end
if (storeprev)
# store color as previous value
@prevfill_color = [r, g, b]
end
end
alias_method :set_fill_color, :SetFillColor
# This hasn't been ported from tcpdf, it's a variation on SetTextColor for setting cmyk colors
def SetCmykFillColor(c, m, y, k, storeprev=false)
#Set color for all filling operations
@fill_color=sprintf('%.3f %.3f %.3f %.3f k', c, m, y, k);
@color_flag=(@fill_color!=@text_color);
if (storeprev)
# store color as previous value
@prevtext_color = [c, m, y, k]
end
if (@page>0)
out(@fill_color);
end
end
alias_method :set_cmyk_fill_color, :SetCmykFillColor
#
# Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
# @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
# @param int :g Green component (between 0 and 255)
# @param int :b Blue component (between 0 and 255)
# @param boolean :storeprev if true stores the RGB array on :prevtext_color variable.
# @since 1.3
# @see SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
#
def SetTextColor(r, g=-1, b=-1, storeprev=false)
#Set color for text
if ((r==0 and :g==0 and :b==0) or :g==-1)
@text_color=sprintf('%.3f g', r/255.0);
else
@text_color=sprintf('%.3f %.3f %.3f rg', r/255.0, g/255.0, b/255.0);
end
@color_flag=(@fill_color!=@text_color);
if (storeprev)
# store color as previous value
@prevtext_color = [r, g, b]
end
end
alias_method :set_text_color, :SetTextColor
# This hasn't been ported from tcpdf, it's a variation on SetTextColor for setting cmyk colors
def SetCmykTextColor(c, m, y, k, storeprev=false)
#Set color for text
@text_color=sprintf('%.3f %.3f %.3f %.3f k', c, m, y, k);
@color_flag=(@fill_color!=@text_color);
if (storeprev)
# store color as previous value
@prevtext_color = [c, m, y, k]
end
end
alias_method :set_cmyk_text_color, :SetCmykTextColor
#
# Returns the length of a string in user unit. A font must be selected.<br>
# Support UTF-8 Unicode [Nicola Asuni, 2005-01-02]
# @param string :s The string whose length is to be computed
# @return int
# @since 1.2
#
def GetStringWidth(s)
#Get width of a string in the current font
s = s.to_s;
cw = @current_font['cw']
w = 0;
if (@is_unicode)
unicode = UTF8StringToArray(s);
unicode.each do |char|
if (!cw[char].nil?)
w += cw[char];
# This should not happen. UTF8StringToArray should guarentee the array is ascii values.
# elsif (c!cw[char[0]].nil?)
# w += cw[char[0]];
# elsif (!cw[char.chr].nil?)
# w += cw[char.chr];
elsif (!@current_font['desc']['MissingWidth'].nil?)
w += @current_font['desc']['MissingWidth']; # set default size
else
w += 500;
end
end
else
s.each_byte do |c|
if cw[c.chr]
w += cw[c.chr];
elsif cw[?c.chr]
w += cw[?c.chr]
end
end
end
return (w * @font_size / 1000.0);
end
alias_method :get_string_width, :GetStringWidth
#
# Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
# @param float :width The width.
# @since 1.0
# @see Line(), Rect(), Cell(), MultiCell()
#
def SetLineWidth(width)
#Set line width
@line_width = width;
if (@page>0)
out(sprintf('%.2f w', width*@k));
end
end
alias_method :set_line_width, :SetLineWidth
#
# Draws a line between two points.
# @param float :x1 Abscissa of first point
# @param float :y1 Ordinate of first point
# @param float :x2 Abscissa of second point
# @param float :y2 Ordinate of second point
# @since 1.0
# @see SetLineWidth(), SetDrawColor()
#
def Line(x1, y1, x2, y2)
#Draw a line
out(sprintf('%.2f %.2f m %.2f %.2f l S', x1 * @k, (@h - y1) * @k, x2 * @k, (@h - y2) * @k));
end
alias_method :line, :Line
def Circle(mid_x, mid_y, radius, style='')
mid_y = (@h-mid_y)*@k
out(sprintf("q\n")) # postscript content in pdf
# init line type etc. with /GSD gs G g (grey) RG rg (RGB) w=line witdh etc.
out(sprintf("1 j\n")) # line join
# translate ("move") circle to mid_y, mid_y
out(sprintf("1 0 0 1 %f %f cm", mid_x, mid_y))
kappa = 0.5522847498307933984022516322796
# Quadrant 1
x_s = 0.0 # 12 o'clock
y_s = 0.0 + radius
x_e = 0.0 + radius # 3 o'clock
y_e = 0.0
out(sprintf("%f %f m\n", x_s, y_s)) # move to 12 o'clock
# cubic bezier control point 1, start height and kappa * radius to the right
bx_e1 = x_s + (radius * kappa)
by_e1 = y_s
# cubic bezier control point 2, end and kappa * radius above
bx_e2 = x_e
by_e2 = y_e + (radius * kappa)
# draw cubic bezier from current point to x_e/y_e with bx_e1/by_e1 and bx_e2/by_e2 as bezier control points
out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
# Quadrant 2
x_s = x_e
y_s = y_e # 3 o'clock
x_e = 0.0
y_e = 0.0 - radius # 6 o'clock
bx_e1 = x_s # cubic bezier point 1
by_e1 = y_s - (radius * kappa)
bx_e2 = x_e + (radius * kappa) # cubic bezier point 2
by_e2 = y_e
out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
# Quadrant 3
x_s = x_e
y_s = y_e # 6 o'clock
x_e = 0.0 - radius
y_e = 0.0 # 9 o'clock
bx_e1 = x_s - (radius * kappa) # cubic bezier point 1
by_e1 = y_s
bx_e2 = x_e # cubic bezier point 2
by_e2 = y_e - (radius * kappa)
out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
# Quadrant 4
x_s = x_e
y_s = y_e # 9 o'clock
x_e = 0.0
y_e = 0.0 + radius # 12 o'clock
bx_e1 = x_s # cubic bezier point 1
by_e1 = y_s + (radius * kappa)
bx_e2 = x_e - (radius * kappa) # cubic bezier point 2
by_e2 = y_e
out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
if style=='F'
op='f'
elsif style=='FD' or style=='DF'
op='b'
else
op='s'
end
out(sprintf("#{op}\n")) # stroke circle, do not fill and close path
# for filling etc. b, b*, f, f*
out(sprintf("Q\n")) # finish postscript in PDF
end
alias_method :circle, :Circle
#
# Outputs a rectangle. It can be drawn (border only), filled (with no border) or both.
# @param float :x Abscissa of upper-left corner
# @param float :y Ordinate of upper-left corner
# @param float :w Width
# @param float :h Height
# @param string :style Style of rendering. Possible values are:<ul><li>D or empty string: draw (default)</li><li>F: fill</li><li>DF or FD: draw and fill</li></ul>
# @since 1.0
# @see SetLineWidth(), SetDrawColor(), SetFillColor()
#
def Rect(x, y, w, h, style='')
#Draw a rectangle
if (style=='F')
op='f';
elsif (style=='FD' or style=='DF')
op='B';
else
op='S';
end
out(sprintf('%.2f %.2f %.2f %.2f re %s', x * @k, (@h - y) * @k, w * @k, -h * @k, op));
end
alias_method :rect, :Rect
#
# Imports a TrueType or Type1 font and makes it available. It is necessary to generate a font definition file first with the makefont.rb utility. The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by FPDF_FONTPATH if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.
# Support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
# <b>Example</b>:<br />
# <pre>
# :pdf->AddFont('Comic','I');
# # is equivalent to:
# :pdf->AddFont('Comic','I','comici.rb');
# </pre>
# @param string :family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
# @param string :style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
# @param string :file The font definition file. By default, the name is built from the family and style, in lower case with no space.
# @since 1.5
# @see SetFont()
#
def AddFont(family, style='', file='')
if (family.empty?)
return;
end
#Add a TrueType or Type1 font
family = family.downcase
if ((!@is_unicode) and (family == 'arial'))
family = 'helvetica';
end
style=style.upcase
style=style.gsub('U','');
style=style.gsub('D','');
if (style == 'IB')
style = 'BI';
end
fontkey = family + style;
# check if the font has been already added
if !@fonts[fontkey].nil?
return;
end
if (file=='')
file = family.gsub(' ', '') + style.downcase + '.rb';
end
font_file_name = getfontpath(file)
if (font_file_name.nil?)
# try to load the basic file without styles
file = family.gsub(' ', '') + '.rb';
font_file_name = getfontpath(file)
end
if font_file_name.nil?
Error("Could not find font #{file}.")
end
require(getfontpath(file))
font_desc = TCPDFFontDescriptor.font(file)
if (font_desc[:name].nil? and @@fpdf_charwidths.nil?)
Error('Could not include font definition file');
end
i = @fonts.length+1;
if (@is_unicode)
@fonts[fontkey] = {'i' => i, 'type' => font_desc[:type], 'name' => font_desc[:name], 'desc' => font_desc[:desc], 'up' => font_desc[:up], 'ut' => font_desc[:ut], 'cw' => font_desc[:cw], 'enc' => font_desc[:enc], 'file' => font_desc[:file], 'ctg' => font_desc[:ctg], 'cMap' => font_desc[:cMap], 'registry' => font_desc[:registry]}
@@fpdf_charwidths[fontkey] = font_desc[:cw];
else
@fonts[fontkey]={'i' => i, 'type'=>'core', 'name'=>@core_fonts[fontkey], 'up'=>-100, 'ut'=>50, 'cw' => font_desc[:cw]}
@@fpdf_charwidths[fontkey] = font_desc[:cw];
end
if (!font_desc[:diff].nil? and (!font_desc[:diff].empty?))
#Search existing encodings
d=0;
nb=@diffs.length;
1.upto(nb) do |i|
if (@diffs[i]== font_desc[:diff])
d = i;
break;
end
end
if (d==0)
d = nb+1;
@diffs[d] = font_desc[:diff];
end
@fonts[fontkey]['diff'] = d;
end
if (font_desc[:file] and font_desc[:file].length > 0)
if (font_desc[:type] == "TrueType") or (font_desc[:type] == "TrueTypeUnicode")
@font_files[font_desc[:file]] = {'length1' => font_desc[:originalsize]}
else
@font_files[font_desc[:file]] = {'length1' => font_desc[:size1], 'length2' => font_desc[:size2]}
end
end
end
alias_method :add_font, :AddFont
#
# Sets the font used to print character strings. It is mandatory to call this method at least once before printing text or the resulting document would not be valid.
# The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
# The method can be called before the first page is created and the font is retained from page to page.
# If you just wish to change the current font size, it is simpler to call SetFontSize().
# Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the FPDF_FONTPATH constant</li></ul><br />
# Example for the last case (note the trailing slash):<br />
# <pre>
# define('FPDF_FONTPATH','/home/www/font/');
# require('tcpdf.rb');
#
# #Times regular 12
# :pdf->SetFont('Times');
# #Arial bold 14
# :pdf->SetFont('Arial','B',14);
# #Removes bold
# :pdf->SetFont('');
# #Times bold, italic and underlined 14
# :pdf->SetFont('Times','BIUD');
# </pre><br />
# If the file corresponding to the requested font is not found, the error "Could not include font metric file" is generated.
# @param string :family Family font. It can be either a name defined by AddFont() or one of the standard families (case insensitive):<ul><li>Courier (fixed-width)</li><li>Helvetica or Arial (synonymous; sans serif)</li><li>Times (serif)</li><li>Symbol (symbolic)</li><li>ZapfDingbats (symbolic)</li></ul>It is also possible to pass an empty string. In that case, the current family is retained.
# @param string :style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li></ul>or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats
# @param float :size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
# @since 1.0
# @see AddFont(), SetFontSize(), Cell(), MultiCell(), Write()
#
def SetFont(family, style='', size=0)
# save previous values
@prevfont_family = @font_family;
@prevfont_style = @font_style;
family=family.downcase;
if (family=='')
family=@font_family;
end
if ((!@is_unicode) and (family == 'arial'))
family = 'helvetica';
elsif ((family=="symbol") or (family=="zapfdingbats"))
style='';
end
style=style.upcase;
if (style.include?('U'))
@underline=true;
style= style.gsub('U','');
else
@underline=false;
end
if (style.include?('D'))
@deleted=true;
style= style.gsub('D','');
else
@deleted=false;
end
if (style=='IB')
style='BI';
end
if (size==0)
size=@font_size_pt;
end
# try to add font (if not already added)
AddFont(family, style);
#Test if font is already selected
if ((@font_family == family) and (@font_style == style) and (@font_size_pt == size))
return;
end
fontkey = family + style;
style = '' if (@fonts[fontkey].nil? and !@fonts[family].nil?)
#Test if used for the first time
if (@fonts[fontkey].nil?)
#Check if one of the standard fonts
if (!@core_fonts[fontkey].nil?)
if @@fpdf_charwidths[fontkey].nil?
#Load metric file
file = family;
if ((family!='symbol') and (family!='zapfdingbats'))
file += style.downcase;
end
if (getfontpath(file + '.rb').nil?)
# try to load the basic file without styles
file = family;
fontkey = family;
end
require(getfontpath(file + '.rb'));
font_desc = TCPDFFontDescriptor.font(file)
if ((@is_unicode and ctg.nil?) or ((!@is_unicode) and (@@fpdf_charwidths[fontkey].nil?)) )
Error("Could not include font metric file [" + fontkey + "]: " + getfontpath(file + ".rb"));
end
end
i = @fonts.length + 1;
if (@is_unicode)
@fonts[fontkey] = {'i' => i, 'type' => font_desc[:type], 'name' => font_desc[:name], 'desc' => font_desc[:desc], 'up' => font_desc[:up], 'ut' => font_desc[:ut], 'cw' => font_desc[:cw], 'enc' => font_desc[:enc], 'file' => font_desc[:file], 'ctg' => font_desc[:ctg]}
@@fpdf_charwidths[fontkey] = font_desc[:cw];
else
@fonts[fontkey] = {'i' => i, 'type'=>'core', 'name'=>@core_fonts[fontkey], 'up'=>-100, 'ut'=>50, 'cw' => font_desc[:cw]}
@@fpdf_charwidths[fontkey] = font_desc[:cw];
end
else
Error('Undefined font: ' + family + ' ' + style);
end
end
#Select it
@font_family = family;
@font_style = style;
@font_size_pt = size;
@font_size = size / @k;
@current_font = @fonts[fontkey]; # was & may need deep copy?
if (@page>0)
out(sprintf('BT /F%d %.2f Tf ET', @current_font['i'], @font_size_pt));
end
end
alias_method :set_font, :SetFont
#
# Defines the size of the current font.
# @param float :size The size (in points)
# @since 1.0
# @see SetFont()
#
def SetFontSize(size)
#Set font size in points
if (@font_size_pt== size)
return;
end
@font_size_pt = size;
@font_size = size.to_f / @k;
if (@page > 0)
out(sprintf('BT /F%d %.2f Tf ET', @current_font['i'], @font_size_pt));
end
end
alias_method :set_font_size, :SetFontSize
#
# Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br />
# The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
# @since 1.5
# @see Cell(), Write(), Image(), Link(), SetLink()
#
def AddLink()
#Create a new internal link
n=@links.length+1;
@links[n]=[0,0];
return n;
end
alias_method :add_link, :AddLink
#
# Defines the page and position a link points to
# @param int :link The link identifier returned by AddLink()
# @param float :y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
# @param int :page Number of target page; -1 indicates the current page. This is the default value
# @since 1.5
# @see AddLink()
#
def SetLink(link, y=0, page=-1)
#Set destination of internal link
if (y==-1)
y=@y;
end
if (page==-1)
page=@page;
end
@links[link] = [page, y]
end
alias_method :set_link, :SetLink
#
# Puts a link on a rectangular area of the page. Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
# @param float :x Abscissa of the upper-left corner of the rectangle
# @param float :y Ordinate of the upper-left corner of the rectangle
# @param float :w Width of the rectangle
# @param float :h Height of the rectangle
# @param mixed :link URL or identifier returned by AddLink()
# @since 1.5
# @see AddLink(), Cell(), Write(), Image()
#
def Link(x, y, w, h, link)
#Put a link on the page
@page_links ||= Array.new
@page_links[@page] ||= Array.new
@page_links[@page].push([x * @k, @h_pt - y * @k, w * @k, h*@k, link]);
end
alias_method :link, :Link
#
# Prints a character string. The origin is on the left of the first charcter, on the baseline. This method allows to place a string precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write() which are the standard methods to print text.
# @param float :x Abscissa of the origin
# @param float :y Ordinate of the origin
# @param string :txt String to print
# @since 1.0
# @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
#
def Text(x, y, txt)
#Output a string
s=sprintf('BT %.2f %.2f Td (%s) Tj ET', x * @k, (@h-y) * @k, escapetext(txt));
if (@underline and (txt!=''))
s += ' ' + dolinetxt(x, y, txt);
end
if (@color_flag)
s='q ' + @text_color + ' ' + s + ' Q';
end
out(s);
end
alias_method :text, :Text
#
# Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value. The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
# This method is called automatically and should not be called directly by the application.<br />
# <b>Example:</b><br />
# The method is overriden in an inherited class in order to obtain a 3 column layout:<br />
# <pre>
# class PDF extends TCPDF {
# var :col=0;
#
# def SetCol(col)
# #Move position to a column
# @col = col;
# :x=10+:col*65;
# SetLeftMargin(x);
# SetX(x);
# end
#
# def AcceptPageBreak()
# if (@col<2)
# #Go to next column
# SetCol(@col+1);
# SetY(10);
# return false;
# end
# else
# #Go back to first column and issue page break
# SetCol(0);
# return true;
# end
# end
# }
#
# :pdf=new PDF();
# :pdf->Open();
# :pdf->AddPage();
# :pdf->SetFont('Arial','',12);
# for(i=1;:i<=300;:i++)
# :pdf->Cell(0,5,"Line :i",0,1);
# }
# :pdf->Output();
# </pre>
# @return boolean
# @since 1.4
# @see SetAutoPageBreak()
#
def AcceptPageBreak()
#Accept automatic page break or not
return @auto_page_break;
end
alias_method :accept_page_break, :AcceptPageBreak
def BreakThePage?(h)
if ((@y + h) > @page_break_trigger and !@in_footer and AcceptPageBreak())
true
else
false
end
end
alias_method :break_the_page?, :BreakThePage?
#
# Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
# If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
# @param float :w Cell width. If 0, the cell extends up to the right margin.
# @param float :h Cell height. Default value: 0.
# @param string :txt String to print. Default value: empty string.
# @param mixed :border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
# @param int :ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
# Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
# @param string :align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li></ul>
# @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
# @param mixed :link URL or identifier returned by AddLink().
# @since 1.0
# @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
#
def Cell(w, h=0, txt='', border=0, ln=0, align='', fill=0, link=nil)
#Output a cell
k=@k;
if ((@y + h) > @page_break_trigger and !@in_footer and AcceptPageBreak())
#Automatic page break
if @pages[@page+1].nil?
x = @x;
ws = @ws;
if (ws > 0)
@ws = 0;
out('0 Tw');
end
AddPage(@cur_orientation);
@x = x;
if (ws > 0)
@ws = ws;
out(sprintf('%.3f Tw', ws * k));
end
else
@page += 1;
@y=@t_margin;
end
end
if (w == 0)
w = @w - @r_margin - @x;
end
s = '';
if ((fill.to_i == 1) or (border.to_i == 1))
if (fill.to_i == 1)
op = (border.to_i == 1) ? 'B' : 'f';
else
op = 'S';
end
s = sprintf('%.2f %.2f %.2f %.2f re %s ', @x * k, (@h - @y) * k, w * k, -h * k, op);
end
if (border.is_a?(String))
x=@x;
y=@y;
if (border.include?('L'))
s<<sprintf('%.2f %.2f m %.2f %.2f l S ', x*k,(@h-y)*k, x*k,(@h-(y+h))*k);
end
if (border.include?('T'))
s<<sprintf('%.2f %.2f m %.2f %.2f l S ', x*k,(@h-y)*k,(x+w)*k,(@h-y)*k);
end
if (border.include?('R'))
s<<sprintf('%.2f %.2f m %.2f %.2f l S ',(x+w)*k,(@h-y)*k,(x+w)*k,(@h-(y+h))*k);
end
if (border.include?('B'))
s<<sprintf('%.2f %.2f m %.2f %.2f l S ', x*k,(@h-(y+h))*k,(x+w)*k,(@h-(y+h))*k);
end
end
if (txt != '')
width = GetStringWidth(txt);
if (align == 'R' || align == 'right')
dx = w - @c_margin - width;
elsif (align=='C' || align == 'center')
dx = (w - width)/2;
else
dx = @c_margin;
end
if (@color_flag)
s << 'q ' + @text_color + ' ';
end
txt2 = escapetext(txt);
s<<sprintf('BT %.2f %.2f Td (%s) Tj ET', (@x + dx) * k, (@h - (@y + 0.5 * h + 0.3 * @font_size)) * k, txt2);
if (@underline)
s<<' ' + dolinetxt(@x + dx, @y + 0.5 * h + 0.3 * @font_size, txt);
end
if (@deleted)
s<<' ' + dolinetxt(@x + dx, @y + 0.3 * h + 0.2 * @font_size, txt);
end
if (@color_flag)
s<<' Q';
end
if link && !link.empty?
Link(@x + dx, @y + 0.5 * h - 0.5 * @font_size, width, @font_size, link);
end
end
if (s)
out(s);
end
@lasth = h;
if (ln.to_i>0)
# Go to next line
@y += h;
if (ln == 1)
@x = @l_margin;
end
else
@x += w;
end
end
alias_method :cell, :Cell
#
# This method allows printing text with line breaks. They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br />
# Text can be aligned, centered or justified. The cell block can be framed and the background painted.
# @param float :w Width of cells. If 0, they extend up to the right margin of the page.
# @param float :h Height of cells.
# @param string :txt String to print
# @param mixed :border Indicates if borders must be drawn around the cell block. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
# @param string :align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value)</li></ul>
# @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
# @param int :ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
# @since 1.3
# @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
#
def MultiCell(w, h, txt, border=0, align='J', fill=0, ln=1)
# save current position
prevx = @x;
prevy = @y;
prevpage = @page;
#Output text with automatic or explicit line breaks
if (w == 0)
w = @w - @r_margin - @x;
end
wmax = (w - 2 * @c_margin);
s = txt.gsub("\r", ''); # remove carriage returns
nb = s.length;
b=0;
if (border)
if (border==1)
border='LTRB';
b='LRT';
b2='LR';
elsif border.is_a?(String)
b2='';
if (border.include?('L'))
b2<<'L';
end
if (border.include?('R'))
b2<<'R';
end
b=(border.include?('T')) ? b2 + 'T' : b2;
end
end
sep=-1;
to_index=0;
from_j=0;
l=0;
ns=0;
nl=1;
while to_index < nb
#Get next character
c = s[to_index];
if c == "\n"[0]
#Explicit line break
if @ws > 0
@ws = 0
out('0 Tw')
end
#Ed Moss - change begin
end_i = to_index == 0 ? 0 : to_index - 1
# Changed from s[from_j..to_index] to fix bug reported by Hans Allis.
from_j = to_index == 0 ? 1 : from_j
Cell(w, h, s[from_j..end_i], b, 2, align, fill)
#change end
to_index += 1
sep=-1
from_j=to_index
l=0
ns=0
nl += 1
b = b2 if border and nl==2
next
end
if (c == " "[0])
sep = to_index;
ls = l;
ns += 1;
end
l = GetStringWidth(s[from_j, to_index - from_j + 1]);
if (l > wmax)
#Automatic line break
if (sep == -1)
if (to_index == from_j)
to_index += 1;
end
if (@ws > 0)
@ws = 0;
out('0 Tw');
end
Cell(w, h, s[from_j..to_index-1], b, 2, align, fill) # my FPDF version
else
if (align=='J' || align=='justify' || align=='justified')
@ws = (ns>1) ? (wmax-ls)/(ns-1) : 0;
out(sprintf('%.3f Tw', @ws * @k));
end
Cell(w, h, s[from_j..sep], b, 2, align, fill);
to_index = sep + 1;
end
sep=-1;
from_j = to_index;
l=0;
ns=0;
nl += 1;
if (border and (nl==2))
b = b2;
end
else
to_index += 1;
end
end
#Last chunk
if (@ws>0)
@ws=0;
out('0 Tw');
end
if (border.is_a?(String) and border.include?('B'))
b<<'B';
end
Cell(w, h, s[from_j, to_index-from_j], b, 2, align, fill);
# move cursor to specified position
# since 2007-03-03
if (ln == 1)
# go to the beginning of the next line
@x = @l_margin;
elsif (ln == 0)
# go to the top-right of the cell
@page = prevpage;
@y = prevy;
@x = prevx + w;
elsif (ln == 2)
# go to the bottom-left of the cell
@x = prevx;
end
end
alias_method :multi_cell, :MultiCell
#
# This method prints text from the current position. When the right margin is reached (or the \n character is met) a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text. It is possible to put a link on the text.<br />
# <b>Example:</b><br />
# <pre>
# #Begin with regular font
# :pdf->SetFont('Arial','',14);
# :pdf->Write(5,'Visit ');
# #Then put a blue underlined link
# :pdf->SetTextColor(0,0,255);
# :pdf->SetFont('','U');
# :pdf->Write(5,'www.tecnick.com','http://www.tecnick.com');
# </pre>
# @param float :h Line height
# @param string :txt String to print
# @param mixed :link URL or identifier returned by AddLink()
# @param int :fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
# @since 1.5
# @see SetFont(), SetTextColor(), AddLink(), MultiCell(), SetAutoPageBreak()
#
def Write(h, txt, link=nil, fill=0)
#Output text in flowing mode
w = @w - @r_margin - @x;
wmax = (w - 2 * @c_margin);
s = txt.gsub("\r", '');
nb = s.length;
# handle single space character
if ((nb==1) and (s == " "))
@x += GetStringWidth(s);
return;
end
sep=-1;
i=0;
j=0;
l=0;
nl=1;
while(i<nb)
#Get next character
c = s[i];
if (c == "\n"[0])
#Explicit line break
Cell(w, h, s[j,i-j], 0, 2, '', fill, link);
i += 1;
sep = -1;
j = i;
l = 0;
if (nl == 1)
@x = @l_margin;
w = @w - @r_margin - @x;
wmax = (w - 2 * @c_margin);
end
nl += 1;
next
end
if (c == " "[0])
sep= i;
end
l = GetStringWidth(s[j, i - j + 1]);
if (l > wmax)
#Automatic line break (word wrapping)
if (sep == -1)
if (@x > @l_margin)
#Move to next line
@x = @l_margin;
@y += h;
w=@w - @r_margin - @x;
wmax=(w - 2 * @c_margin);
i += 1
nl += 1
next
end
if (i == j)
i += 1
end
Cell(w, h, s[j, (i-1)], 0, 2, '', fill, link);
else
Cell(w, h, s[j, (sep-j)], 0, 2, '', fill, link);
i = sep+1;
end
sep = -1;
j = i;
l = 0;
if (nl==1)
@x = @l_margin;
w = @w - @r_margin - @x;
wmax = (w - 2 * @c_margin);
end
nl += 1;
else
i += 1;
end
end
#Last chunk
if (i != j)
Cell(GetStringWidth(s[j..i]), h, s[j..i], 0, 0, '', fill, link);
end
end
alias_method :write, :Write
#
# Puts an image in the page. The upper-left corner must be given. The dimensions can be specified in different ways:<ul><li>explicit width and height (expressed in user unit)</li><li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li><li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
# Supported formats are JPEG and PNG.
# For JPEG, all flavors are allowed:<ul><li>gray scales</li><li>true colors (24 bits)</li><li>CMYK (32 bits)</li></ul>
# For PNG, are allowed:<ul><li>gray scales on at most 8 bits (256 levels)</li><li>indexed colors</li><li>true colors (24 bits)</li></ul>
# but are not supported:<ul><li>Interlacing</li><li>Alpha channel</li></ul>
# If a transparent color is defined, it will be taken into account (but will be only interpreted by Acrobat 4 and above).<br />
# The format can be specified explicitly or inferred from the file extension.<br />
# It is possible to put a link on the image.<br />
# Remark: if an image is used several times, only one copy will be embedded in the file.<br />
# @param string :file Name of the file containing the image.
# @param float :x Abscissa of the upper-left corner.
# @param float :y Ordinate of the upper-left corner.
# @param float :w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
# @param float :h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
# @param string :type Image format. Possible values are (case insensitive): JPG, JPEG, PNG. If not specified, the type is inferred from the file extension.
# @param mixed :link URL or identifier returned by AddLink().
# @since 1.1
# @see AddLink()
#
def Image(file, x, y, w=0, h=0, type='', link=nil)
#Put an image on the page
if (@images[file].nil?)
#First use of image, get info
if (type == '')
pos = File::basename(file).rindex('.');
if (pos.nil? or pos == 0)
Error('Image file has no extension and no type was specified: ' + file);
end
pos = file.rindex('.');
type = file[pos+1..-1];
end
type.downcase!
if (type == 'jpg' or type == 'jpeg')
info=parsejpg(file);
elsif (type == 'png' or type == 'gif')
img = Magick::ImageList.new(file)
img.format = "PNG" # convert to PNG from gif
img.opacity = 0 # PNG alpha channel delete
File.open( @@k_path_cache + File::basename(file), 'w'){|f|
f.binmode
f.print img.to_blob
f.close
}
info=parsepng( @@k_path_cache + File::basename(file));
File.delete( @@k_path_cache + File::basename(file))
else
#Allow for additional formats
mtd='parse' + type;
if (!self.respond_to?(mtd))
Error('Unsupported image type: ' + type);
end
info=send(mtd, file);
end
info['i']=@images.length+1;
@images[file] = info;
else
info=@images[file];
end
#Automatic width and height calculation if needed
if ((w == 0) and (h == 0))
rescale_x = (@w - @r_margin - x) / (info['w'] / (@img_scale * @k))
rescale_x = 1 if rescale_x >= 1
if (y + info['h'] * rescale_x / (@img_scale * @k) > @page_break_trigger and !@in_footer and AcceptPageBreak())
#Automatic page break
if @pages[@page+1].nil?
ws = @ws;
if (ws > 0)
@ws = 0;
out('0 Tw');
end
AddPage(@cur_orientation);
if (ws > 0)
@ws = ws;
out(sprintf('%.3f Tw', ws * @k));
end
else
@page += 1;
end
y=@t_margin;
end
rescale_y = (@page_break_trigger - y) / (info['h'] / (@img_scale * @k))
rescale_y = 1 if rescale_y >= 1
rescale = rescale_y >= rescale_x ? rescale_x : rescale_y
#Put image at 72 dpi
# 2004-06-14 :: Nicola Asuni, scale factor where added
w = info['w'] * rescale / (@img_scale * @k);
h = info['h'] * rescale / (@img_scale * @k);
elsif (w == 0)
w = h * info['w'] / info['h'];
elsif (h == 0)
h = w * info['h'] / info['w'];
end
out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q', w*@k, h*@k, x*@k, (@h-(y+h))*@k, info['i']));
if (link)
Link(x, y, w, h, link);
end
#2002-07-31 - Nicola Asuni
# set right-bottom corner coordinates
@img_rb_x = x + w;
@img_rb_y = y + h;
end
alias_method :image, :Image
#
# Performs a line break. The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
# @param float :h The height of the break. By default, the value equals the height of the last printed cell.
# @since 1.0
# @see Cell()
#
def Ln(h='')
#Line feed; default value is last cell height
@x=@l_margin;
if (h.is_a?(String))
@y += @lasth;
else
@y += h;
end
k=@k;
if (@y > @page_break_trigger and !@in_footer and AcceptPageBreak())
#Automatic page break
if @pages[@page+1].nil?
x = @x;
ws = @ws;
if (ws > 0)
@ws = 0;
out('0 Tw');
end
AddPage(@cur_orientation);
@x = x;
if (ws > 0)
@ws = ws;
out(sprintf('%.3f Tw', ws * k));
end
else
@page += 1;
@y=@t_margin;
end
end
end
alias_method :ln, :Ln
#
# Returns the abscissa of the current position.
# @return float
# @since 1.2
# @see SetX(), GetY(), SetY()
#
def GetX()
#Get x position
return @x;
end
alias_method :get_x, :GetX
#
# Defines the abscissa of the current position. If the passed value is negative, it is relative to the right of the page.
# @param float :x The value of the abscissa.
# @since 1.2
# @see GetX(), GetY(), SetY(), SetXY()
#
def SetX(x)
#Set x position
if (x>=0)
@x = x;
else
@x=@w+x;
end
end
alias_method :set_x, :SetX
#
# Returns the ordinate of the current position.
# @return float
# @since 1.0
# @see SetY(), GetX(), SetX()
#
def GetY()
#Get y position
return @y;
end
alias_method :get_y, :GetY
#
# Moves the current abscissa back to the left margin and sets the ordinate. If the passed value is negative, it is relative to the bottom of the page.
# @param float :y The value of the ordinate.
# @since 1.0
# @see GetX(), GetY(), SetY(), SetXY()
#
def SetY(y)
#Set y position and reset x
@x=@l_margin;
if (y>=0)
@y = y;
else
@y=@h+y;
end
end
alias_method :set_y, :SetY
#
# Defines the abscissa and ordinate of the current position. If the passed values are negative, they are relative respectively to the right and bottom of the page.
# @param float :x The value of the abscissa
# @param float :y The value of the ordinate
# @since 1.2
# @see SetX(), SetY()
#
def SetXY(x, y)
#Set x and y positions
SetY(y);
SetX(x);
end
alias_method :set_xy, :SetXY
#
# Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
# The method first calls Close() if necessary to terminate the document.
# @param string :name The name of the file. If not given, the document will be sent to the browser (destination I) with the name doc.pdf.
# @param string :dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser. The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>If the parameter is not specified but a name is given, destination is F. If no parameter is specified at all, destination is I.<br />
# @since 1.0
# @see Close()
#
def Output(name='', dest='')
#Output PDF to some destination
#Finish document if necessary
if (@state < 3)
Close();
end
#Normalize parameters
# Boolean no longer supported
# if (dest.is_a?(Boolean))
# dest = dest ? 'D' : 'F';
# end
dest = dest.upcase
if (dest=='')
if (name=='')
name='doc.pdf';
dest='I';
else
dest='F';
end
end
case (dest)
when 'I'
# This is PHP specific code
##Send to standard output
# if (ob_get_contents())
# Error('Some data has already been output, can\'t send PDF file');
# end
# if (php_sapi_name()!='cli')
# #We send to a browser
# header('Content-Type: application/pdf');
# if (headers_sent())
# Error('Some data has already been output to browser, can\'t send PDF file');
# end
# header('Content-Length: ' + @buffer.length);
# header('Content-disposition: inline; filename="' + name + '"');
# end
return @buffer;
when 'D'
# PHP specific
#Download file
# if (ob_get_contents())
# Error('Some data has already been output, can\'t send PDF file');
# end
# if (!_SERVER['HTTP_USER_AGENT'].nil? && SERVER['HTTP_USER_AGENT'].include?('MSIE'))
# header('Content-Type: application/force-download');
# else
# header('Content-Type: application/octet-stream');
# end
# if (headers_sent())
# Error('Some data has already been output to browser, can\'t send PDF file');
# end
# header('Content-Length: '+ @buffer.length);
# header('Content-disposition: attachment; filename="' + name + '"');
return @buffer;
when 'F'
open(name,'wb') do |f|
f.write(@buffer)
end
# PHP code
# #Save to local file
# f=open(name,'wb');
# if (!f)
# Error('Unable to create output file: ' + name);
# end
# fwrite(f,@buffer,@buffer.length);
# f.close
when 'S'
#Return as a string
return @buffer;
else
Error('Incorrect output destination: ' + dest);
end
return '';
end
alias_method :output, :Output
# Protected methods
#
# Check for locale-related bug
# @access protected
#
def dochecks()
#Check for locale-related bug
if (1.1==1)
Error('Don\'t alter the locale before including class file');
end
#Check for decimal separator
if (sprintf('%.1f',1.0)!='1.0')
setlocale(LC_NUMERIC,'C');
end
end
#
# Return fonts path
# @access protected
#
def getfontpath(file)
# Is it in the @@font_path?
if @@font_path
fpath = File.join @@font_path, file
if File.exists?(fpath)
return fpath
end
end
# Is it in this plugin's font folder?
fpath = File.join File.dirname(__FILE__), 'fonts', file
if File.exists?(fpath)
return fpath
end
# Could not find it.
nil
end
#
# Start document
# @access protected
#
def begindoc()
#Start document
@state=1;
out('%PDF-1.3');
end
#
# putpages
# @access protected
#
def putpages()
nb = @page;
if (@alias_nb_pages)
nbstr = UTF8ToUTF16BE(nb.to_s, false);
#Replace number of pages
1.upto(nb) do |n|
@pages[n].gsub!(@alias_nb_pages, nbstr)
end
end
if @def_orientation=='P'
w_pt=@fw_pt
h_pt=@fh_pt
else
w_pt=@fh_pt
h_pt=@fw_pt
end
filter=(@compress) ? '/Filter /FlateDecode ' : ''
1.upto(nb) do |n|
#Page
newobj
out('<</Type /Page')
out('/Parent 1 0 R')
unless @orientation_changes[n].nil?
out(sprintf('/MediaBox [0 0 %.2f %.2f]', h_pt, w_pt))
end
out('/Resources 2 0 R')
if @page_links[n]
#Links
annots='/Annots ['
@page_links[n].each do |pl|
rect=sprintf('%.2f %.2f %.2f %.2f', pl[0], pl[1], pl[0]+pl[2], pl[1]-pl[3]);
annots<<'<</Type /Annot /Subtype /Link /Rect [' + rect + '] /Border [0 0 0] ';
if (pl[4].is_a?(String))
annots<<'/A <</S /URI /URI (' + escape(pl[4]) + ')>>>>';
else
l=@links[pl[4]];
h=!@orientation_changes[l[0]].nil? ? w_pt : h_pt;
annots<<sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*l[0], h-l[1]*@k);
end
end
out(annots + ']');
end
out('/Contents ' + (@n+1).to_s + ' 0 R>>');
out('endobj');
#Page content
p=(@compress) ? gzcompress(@pages[n]) : @pages[n];
newobj();
out('<<' + filter + '/Length '+ p.length.to_s + '>>');
putstream(p);
out('endobj');
end
#Pages root
@offsets[1]=@buffer.length;
out('1 0 obj');
out('<</Type /Pages');
kids='/Kids [';
0.upto(nb) do |i|
kids<<(3+2*i).to_s + ' 0 R ';
end
out(kids + ']');
out('/Count ' + nb.to_s);
out(sprintf('/MediaBox [0 0 %.2f %.2f]', w_pt, h_pt));
out('>>');
out('endobj');
end
#
# Adds fonts
# putfonts
# @access protected
#
def putfonts()
nf=@n;
@diffs.each do |diff|
#Encodings
newobj();
out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [' + diff + ']>>');
out('endobj');
end
@font_files.each do |file, info|
#Font file embedding
newobj();
@font_files[file]['n']=@n;
font='';
open(getfontpath(file),'rb') do |f|
font = f.read();
end
compressed=(file[-2,2]=='.z');
if (!compressed && !info['length2'].nil?)
header=((font[0][0])==128);
if (header)
#Strip first binary header
font=font[6];
end
if header && (font[info['length1']][0] == 128)
#Strip second binary header
font=font[0..info['length1']] + font[info['length1']+6];
end
end
out('<</Length '+ font.length.to_s);
if (compressed)
out('/Filter /FlateDecode');
end
out('/Length1 ' + info['length1'].to_s);
if (!info['length2'].nil?)
out('/Length2 ' + info['length2'].to_s + ' /Length3 0');
end
out('>>');
open(getfontpath(file),'rb') do |f|
putstream(font)
end
out('endobj');
end
@fonts.each do |k, font|
#Font objects
@fonts[k]['n']=@n+1;
type = font['type'];
name = font['name'];
if (type=='core')
#Standard font
newobj();
out('<</Type /Font');
out('/BaseFont /' + name);
out('/Subtype /Type1');
if (name!='Symbol' && name!='ZapfDingbats')
out('/Encoding /WinAnsiEncoding');
end
out('>>');
out('endobj');
elsif type == 'Type0'
putType0(font)
elsif (type=='Type1' || type=='TrueType')
#Additional Type1 or TrueType font
newobj();
out('<</Type /Font');
out('/BaseFont /' + name);
out('/Subtype /' + type);
out('/FirstChar 32 /LastChar 255');
out('/Widths ' + (@n+1).to_s + ' 0 R');
out('/FontDescriptor ' + (@n+2).to_s + ' 0 R');
if (font['enc'])
if (!font['diff'].nil?)
out('/Encoding ' + (nf+font['diff']).to_s + ' 0 R');
else
out('/Encoding /WinAnsiEncoding');
end
end
out('>>');
out('endobj');
#Widths
newobj();
cw=font['cw']; # &
s='[';
32.upto(255) do |i|
s << cw[i.chr] + ' ';
end
out(s + ']');
out('endobj');
#Descriptor
newobj();
s='<</Type /FontDescriptor /FontName /' + name;
font['desc'].each do |k, v|
s<<' /' + k + ' ' + v;
end
file = font['file'];
if (file)
s<<' /FontFile' + (type=='Type1' ? '' : '2') + ' ' + @font_files[file]['n'] + ' 0 R';
end
out(s + '>>');
out('endobj');
else
#Allow for additional types
mtd='put' + type.downcase;
if (!self.respond_to?(mtd))
Error('Unsupported font type: ' + type)
else
self.send(mtd,font)
end
end
end
end
def putType0(font)
#Type0
newobj();
out('<</Type /Font')
out('/Subtype /Type0')
out('/BaseFont /'+font['name']+'-'+font['cMap'])
out('/Encoding /'+font['cMap'])
out('/DescendantFonts ['+(@n+1).to_s+' 0 R]')
out('>>')
out('endobj')
#CIDFont
newobj()
out('<</Type /Font')
out('/Subtype /CIDFontType0')
out('/BaseFont /'+font['name'])
out('/CIDSystemInfo <</Registry (Adobe) /Ordering ('+font['registry']['ordering']+') /Supplement '+font['registry']['supplement'].to_s+'>>')
out('/FontDescriptor '+(@n+1).to_s+' 0 R')
w='/W [1 ['
font['cw'].keys.sort.each {|key|
w+=font['cw'][key].to_s + " "
# ActionController::Base::logger.debug key.to_s
# ActionController::Base::logger.debug font['cw'][key].to_s
}
out(w+'] 231 325 500 631 [500] 326 389 500]')
out('>>')
out('endobj')
#Font descriptor
newobj()
out('<</Type /FontDescriptor')
out('/FontName /'+font['name'])
out('/Flags 6')
out('/FontBBox [0 -200 1000 900]')
out('/ItalicAngle 0')
out('/Ascent 800')
out('/Descent -200')
out('/CapHeight 800')
out('/StemV 60')
out('>>')
out('endobj')
end
#
# putimages
# @access protected
#
def putimages()
filter=(@compress) ? '/Filter /FlateDecode ' : '';
@images.each do |file, info| # was while(list(file, info)=each(@images))
newobj();
@images[file]['n']=@n;
out('<</Type /XObject');
out('/Subtype /Image');
out('/Width ' + info['w'].to_s);
out('/Height ' + info['h'].to_s);
if (info['cs']=='Indexed')
out('/ColorSpace [/Indexed /DeviceRGB ' + (info['pal'].length/3-1).to_s + ' ' + (@n+1).to_s + ' 0 R]');
else
out('/ColorSpace /' + info['cs']);
if (info['cs']=='DeviceCMYK')
out('/Decode [1 0 1 0 1 0 1 0]');
end
end
out('/BitsPerComponent ' + info['bpc'].to_s);
if (!info['f'].nil?)
out('/Filter /' + info['f']);
end
if (!info['parms'].nil?)
out(info['parms']);
end
if (!info['trns'].nil? and info['trns'].kind_of?(Array))
trns='';
0.upto(info['trns'].length) do |i|
trns << info['trns'][i] + ' ' + info['trns'][i] + ' ';
end
out('/Mask [' + trns + ']');
end
out('/Length ' + info['data'].length.to_s + '>>');
putstream(info['data']);
@images[file]['data']=nil
out('endobj');
#Palette
if (info['cs']=='Indexed')
newobj();
pal=(@compress) ? gzcompress(info['pal']) : info['pal'];
out('<<' + filter + '/Length ' + pal.length.to_s + '>>');
putstream(pal);
out('endobj');
end
end
end
#
# putxobjectdict
# @access protected
#
def putxobjectdict()
@images.each_value do |image|
out('/I' + image['i'].to_s + ' ' + image['n'].to_s + ' 0 R');
end
end
#
# putresourcedict
# @access protected
#
def putresourcedict()
out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
out('/Font <<');
@fonts.each_value do |font|
out('/F' + font['i'].to_s + ' ' + font['n'].to_s + ' 0 R');
end
out('>>');
out('/XObject <<');
putxobjectdict();
out('>>');
end
#
# putresources
# @access protected
#
def putresources()
putfonts();
putimages();
#Resource dictionary
@offsets[2]=@buffer.length;
out('2 0 obj');
out('<<');
putresourcedict();
out('>>');
out('endobj');
end
#
# putinfo
# @access protected
#
def putinfo()
out('/Producer ' + textstring(PDF_PRODUCER));
if (!@title.nil?)
out('/Title ' + textstring(@title));
end
if (!@subject.nil?)
out('/Subject ' + textstring(@subject));
end
if (!@author.nil?)
out('/Author ' + textstring(@author));
end
if (!@keywords.nil?)
out('/Keywords ' + textstring(@keywords));
end
if (!@creator.nil?)
out('/Creator ' + textstring(@creator));
end
out('/CreationDate ' + textstring('D:' + Time.now.strftime('%Y%m%d%H%M%S')));
end
#
# putcatalog
# @access protected
#
def putcatalog()
out('/Type /Catalog');
out('/Pages 1 0 R');
if (@zoom_mode=='fullpage')
out('/OpenAction [3 0 R /Fit]');
elsif (@zoom_mode=='fullwidth')
out('/OpenAction [3 0 R /FitH null]');
elsif (@zoom_mode=='real')
out('/OpenAction [3 0 R /XYZ null null 1]');
elsif (!@zoom_mode.is_a?(String))
out('/OpenAction [3 0 R /XYZ null null ' + (@zoom_mode/100) + ']');
end
if (@layout_mode=='single')
out('/PageLayout /SinglePage');
elsif (@layout_mode=='continuous')
out('/PageLayout /OneColumn');
elsif (@layout_mode=='two')
out('/PageLayout /TwoColumnLeft');
end
end
#
# puttrailer
# @access protected
#
def puttrailer()
out('/Size ' + (@n+1).to_s);
out('/Root ' + @n.to_s + ' 0 R');
out('/Info ' + (@n-1).to_s + ' 0 R');
end
#
# putheader
# @access protected
#
def putheader()
out('%PDF-' + @pdf_version);
end
#
# enddoc
# @access protected
#
def enddoc()
putheader();
putpages();
putresources();
#Info
newobj();
out('<<');
putinfo();
out('>>');
out('endobj');
#Catalog
newobj();
out('<<');
putcatalog();
out('>>');
out('endobj');
#Cross-ref
o=@buffer.length;
out('xref');
out('0 ' + (@n+1).to_s);
out('0000000000 65535 f ');
1.upto(@n) do |i|
out(sprintf('%010d 00000 n ',@offsets[i]));
end
#Trailer
out('trailer');
out('<<');
puttrailer();
out('>>');
out('startxref');
out(o);
out('%%EOF');
@state=3;
end
#
# beginpage
# @access protected
#
def beginpage(orientation)
@page += 1;
@pages[@page]='';
@state=2;
@x=@l_margin;
@y=@t_margin;
@font_family='';
#Page orientation
if (orientation.empty?)
orientation=@def_orientation;
else
orientation.upcase!
if (orientation!=@def_orientation)
@orientation_changes[@page]=true;
end
end
if (orientation!=@cur_orientation)
#Change orientation
if (orientation=='P')
@w_pt=@fw_pt;
@h_pt=@fh_pt;
@w=@fw;
@h=@fh;
else
@w_pt=@fh_pt;
@h_pt=@fw_pt;
@w=@fh;
@h=@fw;
end
@page_break_trigger=@h-@b_margin;
@cur_orientation = orientation;
end
end
#
# End of page contents
# @access protected
#
def endpage()
@state=1;
end
#
# Begin a new object
# @access protected
#
def newobj()
@n += 1;
@offsets[@n]=@buffer.length;
out(@n.to_s + ' 0 obj');
end
#
# Underline and Deleted text
# @access protected
#
def dolinetxt(x, y, txt)
up = @current_font['up'];
ut = @current_font['ut'];
w = GetStringWidth(txt) + @ws * txt.count(' ');
sprintf('%.2f %.2f %.2f %.2f re f', x * @k, (@h - (y - up / 1000.0 * @font_size)) * @k, w * @k, -ut / 1000.0 * @font_size_pt);
end
#
# Extract info from a JPEG file
# @access protected
#
def parsejpg(file)
a=getimagesize(file);
if (a.empty?)
Error('Missing or incorrect image file: ' + file);
end
if (!a[2].nil? and a[2]!='JPEG')
Error('Not a JPEG file: ' + file);
end
if (a['channels'].nil? or a['channels']==3)
colspace='DeviceRGB';
elsif (a['channels']==4)
colspace='DeviceCMYK';
else
colspace='DeviceGray';
end
bpc=!a['bits'].nil? ? a['bits'] : 8;
#Read whole file
data='';
open( @@k_path_cache + File::basename(file),'rb') do |f|
data<<f.read();
end
File.delete( @@k_path_cache + File::basename(file))
return {'w' => a[0],'h' => a[1],'cs' => colspace,'bpc' => bpc,'f'=>'DCTDecode','data' => data}
end
#
# Extract info from a PNG file
# @access protected
#
def parsepng(file)
f=open(file,'rb');
#Check signature
if (f.read(8)!=137.chr + 'PNG' + 13.chr + 10.chr + 26.chr + 10.chr)
Error('Not a PNG file: ' + file);
end
#Read header chunk
f.read(4);
if (f.read(4)!='IHDR')
Error('Incorrect PNG file: ' + file);
end
w=freadint(f);
h=freadint(f);
bpc=f.read(1).unpack('C')[0];
if (bpc>8)
Error('16-bit depth not supported: ' + file);
end
ct=f.read(1).unpack('C')[0];
if (ct==0)
colspace='DeviceGray';
elsif (ct==2)
colspace='DeviceRGB';
elsif (ct==3)
colspace='Indexed';
else
Error('Alpha channel not supported: ' + file);
end
if (f.read(1).unpack('C')[0] != 0)
Error('Unknown compression method: ' + file);
end
if (f.read(1).unpack('C')[0] != 0)
Error('Unknown filter method: ' + file);
end
if (f.read(1).unpack('C')[0] != 0)
Error('Interlacing not supported: ' + file);
end
f.read(4);
parms='/DecodeParms <</Predictor 15 /Colors ' + (ct==2 ? 3 : 1).to_s + ' /BitsPerComponent ' + bpc.to_s + ' /Columns ' + w.to_s + '>>';
#Scan chunks looking for palette, transparency and image data
pal='';
trns='';
data='';
begin
n=freadint(f);
type=f.read(4);
if (type=='PLTE')
#Read palette
pal=f.read( n);
f.read(4);
elsif (type=='tRNS')
#Read transparency info
t=f.read( n);
if (ct==0)
trns = t[1].unpack('C')[0]
elsif (ct==2)
trns = t[[1].unpack('C')[0], t[3].unpack('C')[0], t[5].unpack('C')[0]]
else
pos=t.include?(0.chr);
if (pos!=false)
trns = [pos]
end
end
f.read(4);
elsif (type=='IDAT')
#Read image data block
data<<f.read( n);
f.read(4);
elsif (type=='IEND')
break;
else
f.read( n+4);
end
end while(n)
if (colspace=='Indexed' and pal.empty?)
Error('Missing palette in ' + file);
end
f.close
return {'w' => w, 'h' => h, 'cs' => colspace, 'bpc' => bpc, 'f'=>'FlateDecode', 'parms' => parms, 'pal' => pal, 'trns' => trns, 'data' => data}
end
#
# Read a 4-byte integer from file
# @access protected
#
def freadint(f)
# Read a 4-byte integer from file
a = f.read(4).unpack('N')
return a[0]
end
#
# Format a text string
# @access protected
#
def textstring(s)
if (@is_unicode)
#Convert string to UTF-16BE
s = UTF8ToUTF16BE(s, true);
end
return '(' + escape(s) + ')';
end
#
# Format a text string
# @access protected
#
def escapetext(s)
if (@is_unicode)
#Convert string to UTF-16BE
s = UTF8ToUTF16BE(s, false);
end
return escape(s);
end
#
# Add \ before \, ( and )
# @access protected
#
def escape(s)
# Add \ before \, ( and )
s.gsub('\\','\\\\\\').gsub('(','\\(').gsub(')','\\)').gsub(13.chr, '\r')
end
#
#
# @access protected
#
def putstream(s)
out('stream');
out(s);
out('endstream');
end
#
# Add a line to the document
# @access protected
#
def out(s)
if (@state==2)
@pages[@page] << s.to_s + "\n";
else
@buffer << s.to_s + "\n";
end
end
#
# Adds unicode fonts.<br>
# Based on PDF Reference 1.3 (section 5)
# @access protected
# @author Nicola Asuni
# @since 1.52.0.TC005 (2005-01-05)
#
def puttruetypeunicode(font)
# Type0 Font
# A composite font composed of other fonts, organized hierarchically
newobj();
out('<</Type /Font');
out('/Subtype /Type0');
out('/BaseFont /' + font['name'] + '');
out('/Encoding /Identity-H'); #The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values.
out('/DescendantFonts [' + (@n + 1).to_s + ' 0 R]');
out('/ToUnicode ' + (@n + 2).to_s + ' 0 R');
out('>>');
out('endobj');
# CIDFontType2
# A CIDFont whose glyph descriptions are based on TrueType font technology
newobj();
out('<</Type /Font');
out('/Subtype /CIDFontType2');
out('/BaseFont /' + font['name'] + '');
out('/CIDSystemInfo ' + (@n + 2).to_s + ' 0 R');
out('/FontDescriptor ' + (@n + 3).to_s + ' 0 R');
if (!font['desc']['MissingWidth'].nil?)
out('/DW ' + font['desc']['MissingWidth'].to_s + ''); # The default width for glyphs in the CIDFont MissingWidth
end
w = "";
font['cw'].each do |cid, width|
w << '' + cid.to_s + ' [' + width.to_s + '] '; # define a specific width for each individual CID
end
out('/W [' + w + ']'); # A description of the widths for the glyphs in the CIDFont
out('/CIDToGIDMap ' + (@n + 4).to_s + ' 0 R');
out('>>');
out('endobj');
# ToUnicode
# is a stream object that contains the definition of the CMap
# (PDF Reference 1.3 chap. 5.9)
newobj();
out('<</Length 383>>');
out('stream');
out('/CIDInit /ProcSet findresource begin');
out('12 dict begin');
out('begincmap');
out('/CIDSystemInfo');
out('<</Registry (Adobe)');
out('/Ordering (UCS)');
out('/Supplement 0');
out('>> def');
out('/CMapName /Adobe-Identity-UCS def');
out('/CMapType 2 def');
out('1 begincodespacerange');
out('<0000> <FFFF>');
out('endcodespacerange');
out('1 beginbfrange');
out('<0000> <FFFF> <0000>');
out('endbfrange');
out('endcmap');
out('CMapName currentdict /CMap defineresource pop');
out('end');
out('end');
out('endstream');
out('endobj');
# CIDSystemInfo dictionary
# A dictionary containing entries that define the character collection of the CIDFont.
newobj();
out('<</Registry (Adobe)'); # A string identifying an issuer of character collections
out('/Ordering (UCS)'); # A string that uniquely names a character collection issued by a specific registry
out('/Supplement 0'); # The supplement number of the character collection.
out('>>');
out('endobj');
# Font descriptor
# A font descriptor describing the CIDFont default metrics other than its glyph widths
newobj();
out('<</Type /FontDescriptor');
out('/FontName /' + font['name']);
font['desc'].each do |key, value|
out('/' + key.to_s + ' ' + value.to_s);
end
if (font['file'])
# A stream containing a TrueType font program
out('/FontFile2 ' + @font_files[font['file']]['n'].to_s + ' 0 R');
end
out('>>');
out('endobj');
# Embed CIDToGIDMap
# A specification of the mapping from CIDs to glyph indices
newobj();
ctgfile = getfontpath(font['ctg'])
if (!ctgfile)
Error('Font file not found: ' + ctgfile);
end
size = File.size(ctgfile);
out('<</Length ' + size.to_s + '');
if (ctgfile[-2,2] == '.z') # check file extension
# Decompresses data encoded using the public-domain
# zlib/deflate compression method, reproducing the
# original text or binary data#
out('/Filter /FlateDecode');
end
out('>>');
open(ctgfile, "rb") do |f|
putstream(f.read())
end
out('endobj');
end
#
# Converts UTF-8 strings to codepoints array.<br>
# Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
# Based on: http://www.faqs.org/rfcs/rfc3629.html
# <pre>
# Char. number range | UTF-8 octet sequence
# (hexadecimal) | (binary)
# --------------------+-----------------------------------------------
# 0000 0000-0000 007F | 0xxxxxxx
# 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
# 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
# 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
# ---------------------------------------------------------------------
#
# ABFN notation:
# ---------------------------------------------------------------------
# UTF8-octets =#( UTF8-char )
# UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
# UTF8-1 = %x00-7F
# UTF8-2 = %xC2-DF UTF8-tail
#
# UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
# %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
# UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
# %xF4 %x80-8F 2( UTF8-tail )
# UTF8-tail = %x80-BF
# ---------------------------------------------------------------------
# </pre>
# @param string :str string to process.
# @return array containing codepoints (UTF-8 characters values)
# @access protected
# @author Nicola Asuni
# @since 1.53.0.TC005 (2005-01-05)
#
def UTF8StringToArray(str)
if (!@is_unicode)
return str; # string is not in unicode
end
unicode = [] # array containing unicode values
bytes = [] # array containing single character byte sequences
numbytes = 1; # number of octetc needed to represent the UTF-8 character
str = str.to_s; # force :str to be a string
str.each_byte do |char|
if (bytes.length == 0) # get starting octect
if (char <= 0x7F)
unicode << char # use the character "as is" because is ASCII
numbytes = 1
elsif ((char >> 0x05) == 0x06) # 2 bytes character (0x06 = 110 BIN)
bytes << ((char - 0xC0) << 0x06)
numbytes = 2
elsif ((char >> 0x04) == 0x0E) # 3 bytes character (0x0E = 1110 BIN)
bytes << ((char - 0xE0) << 0x0C)
numbytes = 3
elsif ((char >> 0x03) == 0x1E) # 4 bytes character (0x1E = 11110 BIN)
bytes << ((char - 0xF0) << 0x12)
numbytes = 4
else
# use replacement character for other invalid sequences
unicode << 0xFFFD
bytes = []
numbytes = 1
end
elsif ((char >> 0x06) == 0x02) # bytes 2, 3 and 4 must start with 0x02 = 10 BIN
bytes << (char - 0x80)
if (bytes.length == numbytes)
# compose UTF-8 bytes to a single unicode value
char = bytes[0]
1.upto(numbytes-1) do |j|
char += (bytes[j] << ((numbytes - j - 1) * 0x06))
end
if (((char >= 0xD800) and (char <= 0xDFFF)) or (char >= 0x10FFFF))
# The definition of UTF-8 prohibits encoding character numbers between
# U+D800 and U+DFFF, which are reserved for use with the UTF-16
# encoding form (as surrogate pairs) and do not directly represent
# characters
unicode << 0xFFFD; # use replacement character
else
unicode << char; # add char to array
end
# reset data for next char
bytes = []
numbytes = 1;
end
else
# use replacement character for other invalid sequences
unicode << 0xFFFD;
bytes = []
numbytes = 1;
end
end
return unicode;
end
#
# Converts UTF-8 strings to UTF16-BE.<br>
# Based on: http://www.faqs.org/rfcs/rfc2781.html
# <pre>
# Encoding UTF-16:
#
# Encoding of a single character from an ISO 10646 character value to
# UTF-16 proceeds as follows. Let U be the character number, no greater
# than 0x10FFFF.
#
# 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
# terminate.
#
# 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
# U' must be less than or equal to 0xFFFFF. That is, U' can be
# represented in 20 bits.
#
# 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
# 0xDC00, respectively. These integers each have 10 bits free to
# encode the character value, for a total of 20 bits.
#
# 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
# bits of W1 and the 10 low-order bits of U' to the 10 low-order
# bits of W2. Terminate.
#
# Graphically, steps 2 through 4 look like:
# U' = yyyyyyyyyyxxxxxxxxxx
# W1 = 110110yyyyyyyyyy
# W2 = 110111xxxxxxxxxx
# </pre>
# @param string :str string to process.
# @param boolean :setbom if true set the Byte Order Mark (BOM = 0xFEFF)
# @return string
# @access protected
# @author Nicola Asuni
# @since 1.53.0.TC005 (2005-01-05)
# @uses UTF8StringToArray
#
def UTF8ToUTF16BE(str, setbom=true)
if (!@is_unicode)
return str; # string is not in unicode
end
outstr = ""; # string to be returned
unicode = UTF8StringToArray(str); # array containing UTF-8 unicode values
numitems = unicode.length;
if (setbom)
outstr << "\xFE\xFF"; # Byte Order Mark (BOM)
end
unicode.each do |char|
if (char == 0xFFFD)
outstr << "\xFF\xFD"; # replacement character
elsif (char < 0x10000)
outstr << (char >> 0x08).chr;
outstr << (char & 0xFF).chr;
else
char -= 0x10000;
w1 = 0xD800 | (char >> 0x10);
w2 = 0xDC00 | (char & 0x3FF);
outstr << (w1 >> 0x08).chr;
outstr << (w1 & 0xFF).chr;
outstr << (w2 >> 0x08).chr;
outstr << (w2 & 0xFF).chr;
end
end
return outstr;
end
# ====================================================
#
# Set header font.
# @param array :font font
# @since 1.1
#
def SetHeaderFont(font)
@header_font = font;
end
alias_method :set_header_font, :SetHeaderFont
#
# Set footer font.
# @param array :font font
# @since 1.1
#
def SetFooterFont(font)
@footer_font = font;
end
alias_method :set_footer_font, :SetFooterFont
#
# Set language array.
# @param array :language
# @since 1.1
#
def SetLanguageArray(language)
@l = language;
end
alias_method :set_language_array, :SetLanguageArray
#
# Set document barcode.
# @param string :bc barcode
#
def SetBarcode(bc="")
@barcode = bc;
end
#
# Print Barcode.
# @param int :x x position in user units
# @param int :y y position in user units
# @param int :w width in user units
# @param int :h height position in user units
# @param string :type type of barcode (I25, C128A, C128B, C128C, C39)
# @param string :style barcode style
# @param string :font font for text
# @param int :xres x resolution
# @param string :code code to print
#
def writeBarcode(x, y, w, h, type, style, font, xres, code)
require(File.dirname(__FILE__) + "/barcode/barcode.rb");
require(File.dirname(__FILE__) + "/barcode/i25object.rb");
require(File.dirname(__FILE__) + "/barcode/c39object.rb");
require(File.dirname(__FILE__) + "/barcode/c128aobject.rb");
require(File.dirname(__FILE__) + "/barcode/c128bobject.rb");
require(File.dirname(__FILE__) + "/barcode/c128cobject.rb");
if (code.empty?)
return;
end
if (style.empty?)
style = BCS_ALIGN_LEFT;
style |= BCS_IMAGE_PNG;
style |= BCS_TRANSPARENT;
#:style |= BCS_BORDER;
#:style |= BCS_DRAW_TEXT;
#:style |= BCS_STRETCH_TEXT;
#:style |= BCS_REVERSE_COLOR;
end
if (font.empty?) then font = BCD_DEFAULT_FONT; end
if (xres.empty?) then xres = BCD_DEFAULT_XRES; end
scale_factor = 1.5 * xres * @k;
bc_w = (w * scale_factor).round #width in points
bc_h = (h * scale_factor).round #height in points
case (type.upcase)
when "I25"
obj = I25Object.new(bc_w, bc_h, style, code);
when "C128A"
obj = C128AObject.new(bc_w, bc_h, style, code);
when "C128B"
obj = C128BObject.new(bc_w, bc_h, style, code);
when "C128C"
obj = C128CObject.new(bc_w, bc_h, style, code);
when "C39"
obj = C39Object.new(bc_w, bc_h, style, code);
end
obj.SetFont(font);
obj.DrawObject(xres);
#use a temporary file....
tmpName = tempnam(@@k_path_cache,'img');
imagepng(obj.getImage(), tmpName);
Image(tmpName, x, y, w, h, 'png');
obj.DestroyObject();
obj = nil
unlink(tmpName);
end
#
# Returns the PDF data.
#
def GetPDFData()
if (@state < 3)
Close();
end
return @buffer;
end
# --- HTML PARSER FUNCTIONS ---
#
# Allows to preserve some HTML formatting.<br />
# Supports: h1, h2, h3, h4, h5, h6, b, u, i, a, img, p, br, strong, em, ins, del, font, blockquote, li, ul, ol, hr, td, th, tr, table, sup, sub, small
# @param string :html text to display
# @param boolean :ln if true add a new line after text (default = true)
# @param int :fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
#
def writeHTML(html, ln=true, fill=0, h=0)
@lasth = h if h > 0
if (@lasth == 0)
#set row height
@lasth = @font_size * @@k_cell_height_ratio;
end
@href = nil
@style = "";
@t_cells = [[]];
@table_id = 0;
# pre calculate
html.split(/(<[^>]+>)/).each do |element|
if "<" == element[0,1]
#Tag
if (element[1, 1] == '/')
closedHTMLTagCalc(element[2..-2].downcase);
else
#Extract attributes
# get tag name
tag = element.scan(/([a-zA-Z0-9]*)/).flatten.delete_if {|x| x.length == 0}
tag = tag[0].downcase;
# get attributes
attr_array = element.scan(/([^=\s]*)=["\']?([^"\']*)["\']?/)
attrs = {}
attr_array.each do |name, value|
attrs[name.downcase] = value;
end
openHTMLTagCalc(tag, attrs);
end
end
end
@table_id = 0;
html.split(/(<[A-Za-z!?\/][^>]*?>)/).each do |element|
if "<" == element[0,1]
#Tag
if (element[1, 1] == '/')
closedHTMLTagHandler(element[2..-2].downcase);
else
#Extract attributes
# get tag name
tag = element.scan(/([a-zA-Z0-9]*)/).flatten.delete_if {|x| x.length == 0}
tag = tag[0].downcase;
# get attributes
attr_array = element.scan(/([^=\s]*)=["\']?([^"\']*)["\']?/)
attrs = {}
attr_array.each do |name, value|
attrs[name.downcase] = value;
end
openHTMLTagHandler(tag, attrs, fill);
end
else
#Text
if (@href)
element.gsub!(/[\t\r\n\f]/, "");
addHtmlLink(@href, element, fill);
elsif (@tdbegin)
element.gsub!(/[\t\r\n\f]/, "");
element.gsub!(/ /, " ");
base_page = @page;
base_x = @x;
base_y = @y;
MultiCell(@tdwidth, @tdheight, unhtmlentities(element.strip), @tableborder, @tdalign, @tdfill, 1);
tr_end = @t_cells[@table_id][@tr_id][@td_id]['j1'] + 1;
if @max_td_page[tr_end].nil? or (@max_td_page[tr_end] < @page)
@max_td_page[tr_end] = @page
@max_td_y[tr_end] = @y
elsif (@max_td_page[tr_end] == @page)
@max_td_y[tr_end] = @y if @max_td_y[tr_end].nil? or (@max_td_y[tr_end] < @y)
end
@page = base_page;
@x = base_x + @tdwidth;
@y = base_y;
elsif (element.strip.length > 0)
if @pre_state != true
element.gsub!(/[\t\r\n\f]/, "");
element.gsub!(/ /, " ");
end
Write(@lasth, unhtmlentities(element), '', fill);
end
end
end
if (ln)
Ln(@lasth);
end
end
alias_method :write_html, :writeHTML
#
# Prints a cell (rectangular area) with optional borders, background color and html text string. The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.<br />
# If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
# @param float :w Cell width. If 0, the cell extends up to the right margin.
# @param float :h Cell minimum height. The cell extends automatically if needed.
# @param float :x upper-left corner X coordinate
# @param float :y upper-left corner Y coordinate
# @param string :html html text to print. Default value: empty string.
# @param mixed :border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
# @param int :ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
# Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
# @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
# @see Cell()
#
def writeHTMLCell(w, h, x, y, html='', border=0, ln=1, fill=0)
if (@lasth == 0)
#set row height
@lasth = @font_size * @@k_cell_height_ratio;
end
if (x == 0)
x = GetX();
end
if (y == 0)
y = GetY();
end
# get current page number
pagenum = @page;
SetX(x);
SetY(y);
if (w == 0)
w = @fw - x - @r_margin;
end
b=0;
if (border)
if (border==1)
border='LTRB';
b='LRT';
b2='LR';
elsif border.is_a?(String)
b2='';
if (border.include?('L'))
b2<<'L';
end
if (border.include?('R'))
b2<<'R';
end
b=(border.include?('T')) ? b2 + 'T' : b2;
end
end
# store original margin values
l_margin = @l_margin;
r_margin = @r_margin;
# set new margin values
SetLeftMargin(x);
SetRightMargin(@fw - x - w);
# calculate remaining vertical space on page
restspace = GetPageHeight() - GetY() - GetBreakMargin();
writeHTML(html, true, fill); # write html text
currentY = GetY();
@auto_page_break = false;
# check if a new page has been created
if (@page > pagenum)
# design a cell around the text on first page
currentpage = @page;
@page = pagenum;
SetY(GetPageHeight() - restspace - GetBreakMargin());
Cell(w, restspace - 1, "", b, 0, 'L', 0);
b = b2;
@page += 1;
while @page < currentpage
SetY(@t_margin); # put cursor at the beginning of text
Cell(w, @page_break_trigger - @t_margin, "", b, 0, 'L', 0);
@page += 1;
end
if (border.is_a?(String) and border.include?('B'))
b<<'B';
end
# design a cell around the text on last page
SetY(@t_margin); # put cursor at the beginning of text
Cell(w, currentY - @t_margin, "", b, 0, 'L', 0);
else
SetY(y); # put cursor at the beginning of text
# design a cell around the text
Cell(w, [h, (currentY - y)].max, "", border, 0, 'L', 0);
end
@auto_page_break = true;
# restore original margin values
SetLeftMargin(l_margin);
SetRightMargin(r_margin);
@lasth = h
# move cursor to specified position
if (ln == 0)
# go to the top-right of the cell
@x = x + w;
@y = y;
elsif (ln == 1)
# go to the beginning of the next line
@x = @l_margin;
@y = currentY;
elsif (ln == 2)
# go to the bottom-left of the cell (below)
@x = x;
@y = currentY;
end
end
alias_method :write_html_cell, :writeHTMLCell
#
# Check html table tag position.
#
# @param array :table potision array
# @param int :current tr tag id number
# @param int :current td tag id number
# @access private
# @return int : next td_id position.
# value 0 mean that can use position.
#
def checkTableBlockingCellPosition(table, tr_id, td_id )
0.upto(tr_id) do |j|
0.upto(@t_cells[table][j].size - 1) do |i|
if @t_cells[table][j][i]['i0'] <= td_id and td_id <= @t_cells[table][j][i]['i1']
if @t_cells[table][j][i]['j0'] <= tr_id and tr_id <= @t_cells[table][j][i]['j1']
return @t_cells[table][j][i]['i1'] - td_id + 1;
end
end
end
end
return 0;
end
#
# Calculate opening tags.
#
# html table cell array : @t_cells
#
# i0: table cell start position
# i1: table cell end position
# j0: table row start position
# j1: table row end position
#
# +------+
# |i0,j0 |
# | i1,j1|
# +------+
#
# example html:
# <table>
# <tr><td></td><td></td><td></td></tr>
# <tr><td colspan=2></td><td></td></tr>
# <tr><td rowspan=2></td><td></td><td></td></tr>
# <tr><td></td><td></td></tr>
# </table>
#
# i: 0 1 2
# j+----+----+----+
# :|0,0 |1,0 |2,0 |
# 0| 0,0| 1,0| 2,0|
# +----+----+----+
# |0,1 |2,1 |
# 1| 1,1| 2,1|
# +----+----+----+
# |0,2 |1,2 |2,2 |
# 2| | 1,2| 2,2|
# + +----+----+
# | |1,3 |2,3 |
# 3| 0,3| 1,3| 2,3|
# +----+----+----+
#
# html table cell array :
# [[[i0=>0,j0=>0,i1=>0,j1=>0],[i0=>1,j0=>0,i1=>1,j1=>0],[i0=>2,j0=>0,i1=>2,j1=>0]],
# [[i0=>0,j0=>1,i1=>1,j1=>1],[i0=>2,j0=>1,i1=>2,j1=>1]],
# [[i0=>0,j0=>2,i1=>0,j1=>3],[i0=>1,j0=>2,i1=>1,j1=>2],[i0=>2,j0=>2,i1=>2,j1=>2]]
# [[i0=>1,j0=>3,i1=>1,j1=>3],[i0=>2,j0=>3,i1=>2,j1=>3]]]
#
# @param string :tag tag name (in upcase)
# @param string :attr tag attribute (in upcase)
# @access private
#
def openHTMLTagCalc(tag, attrs)
#Opening tag
case (tag)
when 'table'
@max_table_columns[@table_id] = 0;
@t_columns = 0;
@tr_id = -1;
when 'tr'
if @max_table_columns[@table_id] < @t_columns
@max_table_columns[@table_id] = @t_columns;
end
@t_columns = 0;
@tr_id += 1;
@td_id = -1;
@t_cells[@table_id].push []
when 'td', 'th'
@td_id += 1;
if attrs['colspan'].nil? or attrs['colspan'] == ''
colspan = 1;
else
colspan = attrs['colspan'].to_i;
end
if attrs['rowspan'].nil? or attrs['rowspan'] == ''
rowspan = 1;
else
rowspan = attrs['rowspan'].to_i;
end
i = 0;
while true
next_i_distance = checkTableBlockingCellPosition(@table_id, @tr_id, @td_id + i);
if next_i_distance == 0
@t_cells[@table_id][@tr_id].push "i0"=>@td_id + i, "j0"=>@tr_id, "i1"=>(@td_id + i + colspan - 1), "j1"=>@tr_id + rowspan - 1
break;
end
i += next_i_distance;
end
@t_columns += colspan;
end
end
#
# Calculate closing tags.
# @param string :tag tag name (in upcase)
# @access private
#
def closedHTMLTagCalc(tag)
#Closing tag
case (tag)
when 'table'
if @max_table_columns[@table_id] < @t_columns
@max_table_columns[@table_id] = @t_columns;
end
@table_id += 1;
@t_cells.push []
end
end
#
# Convert to accessible file path
# @param string :attrname image file name
#
def getImageFilename( attrname )
nil
end
#
# Process opening tags.
# @param string :tag tag name (in upcase)
# @param string :attr tag attribute (in upcase)
# @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
# @access private
#
def openHTMLTagHandler(tag, attrs, fill=0)
#Opening tag
case (tag)
when 'pre'
@pre_state = true;
@l_margin += 5;
@r_margin += 5;
@x += 5;
when 'table'
if @default_table_columns < @max_table_columns[@table_id]
@table_columns = @max_table_columns[@table_id];
else
@table_columns = @default_table_columns;
end
@l_margin += 5;
@r_margin += 5;
@x += 5;
if attrs['border'].nil? or attrs['border'] == ''
@tableborder = 0;
else
@tableborder = attrs['border'];
end
@tr_id = -1;
@max_td_page[0] = @page;
@max_td_y[0] = @y;
when 'tr', 'td', 'th'
if tag == 'th'
SetStyle('b', true);
@tdalign = "C";
end
if ((!attrs['width'].nil?) and (attrs['width'] != ''))
@tdwidth = (attrs['width'].to_i/4);
else
@tdwidth = ((@w - @l_margin - @r_margin) / @table_columns);
end
if tag == 'tr'
@tr_id += 1;
@td_id = -1;
else
@td_id += 1;
@x = @l_margin + @tdwidth * @t_cells[@table_id][@tr_id][@td_id]['i0'];
end
if attrs['colspan'].nil? or attrs['border'] == ''
@colspan = 1;
else
@colspan = attrs['colspan'].to_i;
end
@tdwidth *= @colspan;
if ((!attrs['height'].nil?) and (attrs['height'] != ''))
@tdheight=(attrs['height'].to_i / @k);
else
@tdheight = @lasth;
end
if ((!attrs['align'].nil?) and (attrs['align'] != ''))
case (attrs['align'])
when 'center'
@tdalign = "C";
when 'right'
@tdalign = "R";
when 'left'
@tdalign = "L";
end
end
if ((!attrs['bgcolor'].nil?) and (attrs['bgcolor'] != ''))
coul = convertColorHexToDec(attrs['bgcolor']);
SetFillColor(coul['R'], coul['G'], coul['B']);
@tdfill=1;
end
@tdbegin=true;
when 'hr'
margin = 1;
if ((!attrs['width'].nil?) and (attrs['width'] != ''))
hrWidth = attrs['width'];
else
hrWidth = @w - @l_margin - @r_margin - margin;
end
SetLineWidth(0.2);
Line(@x + margin, @y, @x + hrWidth, @y);
Ln();
when 'strong'
SetStyle('b', true);
when 'em'
SetStyle('i', true);
when 'ins'
SetStyle('u', true);
when 'del'
SetStyle('d', true);
when 'b', 'i', 'u'
SetStyle(tag, true);
when 'a'
@href = attrs['href'];
when 'img'
if (!attrs['src'].nil?)
# Only generates image include a pdf if RMagick is avalaible
unless Object.const_defined?(:Magick)
Write(@lasth, attrs['src'], '', fill);
return
end
file = getImageFilename(attrs['src'])
if (file.nil?)
Write(@lasth, attrs['src'], '', fill);
return
end
if (attrs['width'].nil?)
attrs['width'] = 0;
end
if (attrs['height'].nil?)
attrs['height'] = 0;
end
begin
Image(file, GetX(),GetY(), pixelsToMillimeters(attrs['width']), pixelsToMillimeters(attrs['height']));
#SetX(@img_rb_x);
SetY(@img_rb_y);
rescue => err
logger.error "pdf: Image: error: #{err.message}"
Write(@lasth, attrs['src'], '', fill);
if File.file?( @@k_path_cache + File::basename(file))
File.delete( @@k_path_cache + File::basename(file))
end
end
end
when 'ul', 'ol'
if @li_count == 0
Ln() if @prevquote_count == @quote_count; # insert Ln for keeping quote lines
@prevquote_count = @quote_count;
end
if @li_state == true
Ln();
@li_state = false;
end
if tag == 'ul'
@list_ordered[@li_count] = false;
else
@list_ordered[@li_count] = true;
end
@list_count[@li_count] = 0;
@li_count += 1
when 'li'
Ln() if @li_state == true
if (@list_ordered[@li_count - 1])
@list_count[@li_count - 1] += 1;
@li_spacer = " " * @li_count + (@list_count[@li_count - 1]).to_s + ". ";
else
#unordered list simbol
@li_spacer = " " * @li_count + "- ";
end
Write(@lasth, @spacer + @li_spacer, '', fill);
@li_state = true;
when 'blockquote'
if (@quote_count == 0)
SetStyle('i', true);
@l_margin += 5;
else
@l_margin += 5 / 2;
end
@x = @l_margin;
@quote_top[@quote_count] = @y;
@quote_page[@quote_count] = @page;
@quote_count += 1
when 'br'
Ln();
if (@li_spacer.length > 0)
@x += GetStringWidth(@li_spacer);
end
when 'p'
Ln();
0.upto(@quote_count - 1) do |i|
if @quote_page[i] == @page;
if @quote_top[i] == @y - @lasth; # fix start line
@quote_top[i] = @y;
end
else
if @quote_page[i] == @page - 1;
@quote_page[i] = @page; # fix start line
@quote_top[i] = @t_margin;
end
end
end
when 'sup'
currentfont_size = @font_size;
@tempfontsize = @font_size_pt;
SetFontSize(@font_size_pt * @@k_small_ratio);
SetXY(GetX(), GetY() - ((currentfont_size - @font_size)*(@@k_small_ratio)));
when 'sub'
currentfont_size = @font_size;
@tempfontsize = @font_size_pt;
SetFontSize(@font_size_pt * @@k_small_ratio);
SetXY(GetX(), GetY() + ((currentfont_size - @font_size)*(@@k_small_ratio)));
when 'small'
currentfont_size = @font_size;
@tempfontsize = @font_size_pt;
SetFontSize(@font_size_pt * @@k_small_ratio);
SetXY(GetX(), GetY() + ((currentfont_size - @font_size)/3));
when 'font'
if (!attrs['color'].nil? and attrs['color']!='')
coul = convertColorHexToDec(attrs['color']);
SetTextColor(coul['R'], coul['G'], coul['B']);
@issetcolor=true;
end
if (!attrs['face'].nil? and @fontlist.include?(attrs['face'].downcase))
SetFont(attrs['face'].downcase);
@issetfont=true;
end
if (!attrs['size'].nil?)
headsize = attrs['size'].to_i;
else
headsize = 0;
end
currentfont_size = @font_size;
@tempfontsize = @font_size_pt;
SetFontSize(@font_size_pt + headsize);
@lasth = @font_size * @@k_cell_height_ratio;
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
Ln();
headsize = (4 - tag[1,1].to_f) * 2
@tempfontsize = @font_size_pt;
SetFontSize(@font_size_pt + headsize);
SetStyle('b', true);
@lasth = @font_size * @@k_cell_height_ratio;
end
end
#
# Process closing tags.
# @param string :tag tag name (in upcase)
# @access private
#
def closedHTMLTagHandler(tag)
#Closing tag
case (tag)
when 'pre'
@pre_state = false;
@l_margin -= 5;
@r_margin -= 5;
@x = @l_margin;
Ln();
when 'td','th'
@tdbegin = false;
@tdwidth = 0;
@tdheight = 0;
@tdalign = "L";
SetStyle('b', false);
@tdfill = 0;
SetFillColor(@prevfill_color[0], @prevfill_color[1], @prevfill_color[2]);
when 'tr'
@y = @max_td_y[@tr_id + 1];
@x = @l_margin;
@page = @max_td_page[@tr_id + 1];
when 'table'
# Write Table Line
width = (@w - @l_margin - @r_margin) / @table_columns;
0.upto(@t_cells[@table_id].size - 1) do |j|
0.upto(@t_cells[@table_id][j].size - 1) do |i|
@page = @max_td_page[j]
i0=@t_cells[@table_id][j][i]['i0'];
j0=@t_cells[@table_id][j][i]['j0'];
i1=@t_cells[@table_id][j][i]['i1'];
j1=@t_cells[@table_id][j][i]['j1'];
Line(@l_margin + width * i0, @max_td_y[j0], @l_margin + width * (i1+1), @max_td_y[j0]) # top
if ( @page == @max_td_page[j1 + 1])
Line(@l_margin + width * i0, @max_td_y[j0], @l_margin + width * i0, @max_td_y[j1+1]) # left
Line(@l_margin + width * (i1+1), @max_td_y[j0], @l_margin + width * (i1+1), @max_td_y[j1+1]) # right
else
Line(@l_margin + width * i0, @max_td_y[j0], @l_margin + width * i0, @page_break_trigger) # left
Line(@l_margin + width * (i1+1), @max_td_y[j0], @l_margin + width * (i1+1), @page_break_trigger) # right
@page += 1;
while @page < @max_td_page[j1 + 1]
Line(@l_margin + width * i0, @t_margin, @l_margin + width * i0, @page_break_trigger) # left
Line(@l_margin + width * (i1+1), @t_margin, @l_margin + width * (i1+1), @page_break_trigger) # right
@page += 1;
end
Line(@l_margin + width * i0, @t_margin, @l_margin + width * i0, @max_td_y[j1+1]) # left
Line(@l_margin + width * (i1+1), @t_margin, @l_margin + width * (i1+1), @max_td_y[j1+1]) # right
end
Line(@l_margin + width * i0, @max_td_y[j1+1], @l_margin + width * (i1+1), @max_td_y[j1+1]) # bottom
end
end
@l_margin -= 5;
@r_margin -= 5;
@tableborder=0;
Ln();
@table_id += 1;
when 'strong'
SetStyle('b', false);
when 'em'
SetStyle('i', false);
when 'ins'
SetStyle('u', false);
when 'del'
SetStyle('d', false);
when 'b', 'i', 'u'
SetStyle(tag, false);
when 'a'
@href = nil;
when 'p'
Ln();
when 'sup'
currentfont_size = @font_size;
SetFontSize(@tempfontsize);
@tempfontsize = @font_size_pt;
SetXY(GetX(), GetY() - ((currentfont_size - @font_size)*(@@k_small_ratio)));
when 'sub'
currentfont_size = @font_size;
SetFontSize(@tempfontsize);
@tempfontsize = @font_size_pt;
SetXY(GetX(), GetY() + ((currentfont_size - @font_size)*(@@k_small_ratio)));
when 'small'
currentfont_size = @font_size;
SetFontSize(@tempfontsize);
@tempfontsize = @font_size_pt;
SetXY(GetX(), GetY() - ((@font_size - currentfont_size)/3));
when 'font'
if (@issetcolor == true)
SetTextColor(@prevtext_color[0], @prevtext_color[1], @prevtext_color[2]);
end
if (@issetfont)
@font_family = @prevfont_family;
@font_style = @prevfont_style;
SetFont(@font_family);
@issetfont = false;
end
currentfont_size = @font_size;
SetFontSize(@tempfontsize);
@tempfontsize = @font_size_pt;
#@text_color = @prevtext_color;
@lasth = @font_size * @@k_cell_height_ratio;
when 'blockquote'
@quote_count -= 1
if (@quote_page[@quote_count] == @page)
Line(@l_margin - 1, @quote_top[@quote_count], @l_margin - 1, @y) # quoto line
else
cur_page = @page;
cur_y = @y;
@page = @quote_page[@quote_count];
if (@quote_top[@quote_count] < @page_break_trigger)
Line(@l_margin - 1, @quote_top[@quote_count], @l_margin - 1, @page_break_trigger) # quoto line
end
@page += 1;
while @page < cur_page
Line(@l_margin - 1, @t_margin, @l_margin - 1, @page_break_trigger) # quoto line
@page += 1;
end
@y = cur_y;
Line(@l_margin - 1, @t_margin, @l_margin - 1, @y) # quoto line
end
if (@quote_count <= 0)
SetStyle('i', false);
@l_margin -= 5;
else
@l_margin -= 5 / 2;
end
@x = @l_margin;
Ln() if @quote_count == 0
when 'ul', 'ol'
@li_count -= 1
if @li_state == true
Ln();
@li_state = false;
end
when 'li'
@li_spacer = "";
if @li_state == true
Ln();
@li_state = false;
end
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
SetFontSize(@tempfontsize);
@tempfontsize = @font_size_pt;
SetStyle('b', false);
Ln();
@lasth = @font_size * @@k_cell_height_ratio;
if tag == 'h1' or tag == 'h2' or tag == 'h3' or tag == 'h4'
margin = 1;
hrWidth = @w - @l_margin - @r_margin - margin;
if tag == 'h1' or tag == 'h2'
SetLineWidth(0.2);
else
SetLineWidth(0.1);
end
Line(@x + margin, @y, @x + hrWidth, @y);
end
end
end
#
# Sets font style.
# @param string :tag tag name (in lowercase)
# @param boolean :enable
# @access private
#
def SetStyle(tag, enable)
#Modify style and select corresponding font
['b', 'i', 'u', 'd'].each do |s|
if tag.downcase == s
if enable
@style << s if ! @style.include?(s)
else
@style = @style.gsub(s,'')
end
end
end
SetFont('', @style);
end
#
# Output anchor link.
# @param string :url link URL
# @param string :name link name
# @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
# @access public
#
def addHtmlLink(url, name, fill=0)
#Put a hyperlink
SetTextColor(0, 0, 255);
SetStyle('u', true);
Write(@lasth, name, url, fill);
SetStyle('u', false);
SetTextColor(0);
end
#
# Returns an associative array (keys: R,G,B) from
# a hex html code (e.g. #3FE5AA).
# @param string :color hexadecimal html color [#rrggbb]
# @return array
# @access private
#
def convertColorHexToDec(color = "#000000")
tbl_color = {}
tbl_color['R'] = color[1,2].hex.to_i;
tbl_color['G'] = color[3,2].hex.to_i;
tbl_color['B'] = color[5,2].hex.to_i;
return tbl_color;
end
#
# Converts pixels to millimeters in 72 dpi.
# @param int :px pixels
# @return float millimeters
# @access private
#
def pixelsToMillimeters(px)
return px.to_f * 25.4 / 72;
end
#
# Reverse function for htmlentities.
# Convert entities in UTF-8.
#
# @param :text_to_convert Text to convert.
# @return string converted
#
def unhtmlentities(string)
if @@decoder.nil?
CGI.unescapeHTML(string)
else
@@decoder.decode(string)
end
end
end # END OF CLASS
#TODO 2007-05-25 (EJM) Level=0 -
#Handle special IE contype request
# if (!_SERVER['HTTP_USER_AGENT'].nil? and (_SERVER['HTTP_USER_AGENT']=='contype'))
# header('Content-Type: application/pdf');
# exit;
# }
|