/usr/lib/python3/dist-packages/reportlab/pdfbase/pdfdoc.py is in python3-reportlab 3.3.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #Copyright ReportLab Europe Ltd. 2000-2016
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfbase/pdfdoc.py
__version__='3.3.0'
__doc__="""
The module pdfdoc.py handles the 'outer structure' of PDF documents, ensuring that
all objects are properly cross-referenced and indexed to the nearest byte. The
'inner structure' - the page descriptions - are presumed to be generated before
each page is saved.
pdfgen.py calls this and provides a 'canvas' object to handle page marking operators.
piddlePDF calls pdfgen and offers a high-level interface.
The classes within this generally mirror structures in the PDF file
and are not part of any public interface. Instead, canvas and font
classes are made available elsewhere for users to manipulate.
"""
import types, binascii, codecs
from collections import OrderedDict
from reportlab.pdfbase import pdfutils
from reportlab import rl_config
from reportlab.lib.utils import import_zlib, open_for_read, makeFileName, isSeq, isBytes, isUnicode, _digester, isStr, bytestr, isPy3, annotateException
from reportlab.lib.rl_accel import escapePDF, fp_str, asciiBase85Encode, asciiBase85Decode
from reportlab.pdfbase import pdfmetrics
from hashlib import md5
from sys import platform
from sys import version_info
from sys import stderr
if platform[:4] == 'java' and version_info[:2] == (2, 1):
# workaround for list()-bug in Jython 2.1 (should be fixed in 2.2)
def list(sequence):
def f(x):
return x
return list(map(f, sequence))
class PDFError(Exception):
pass
# __InternalName__ is a special attribute that can only be set by the Document arbitrator
__InternalName__ = "__InternalName__"
# __RefOnly__ marks reference only elements that must be formatted on top level
__RefOnly__ = "__RefOnly__"
# __Comment__ provides a (one line) comment to inline with an object ref, if present
# if it is more than one line then percentize it...
__Comment__ = "__Comment__"
# name for standard font dictionary
BasicFonts = "BasicFonts"
# name for the pages object
Pages = "Pages"
PDF_VERSION_DEFAULT = (1, 3)
PDF_SUPPORT_VERSION = dict( #map keyword to min version that supports it
transparency = (1, 4),
)
if isPy3:
def pdfdocEnc(x):
return x.encode('extpdfdoc') if isinstance(x,str) else x
else:
def pdfdocEnc(x):
return x.encode('extpdfdoc') if isinstance(x,unicode) else x
def format(element, document, toplevel=0):
"""Indirection step for formatting.
Ensures that document parameters alter behaviour
of formatting for all elements.
"""
if isinstance(element,PDFObject):
if not toplevel and hasattr(element, __RefOnly__):
# the object cannot be a component at non top level.
# make a reference to it and return it's format
return document.Reference(element).format(document)
else:
f = element.format(document)
if not rl_config.invariant and rl_config.pdfComments and hasattr(element, __Comment__):
f = pdfdocEnc("%% %s\r\n" % element.__Comment__)+f
return f
elif type(element) in (float, int):
#use a controlled number formatting routine
#instead of str, so Jython/Python etc do not differ
return pdfdocEnc(fp_str(element))
elif isBytes(element):
return element
elif isUnicode(element):
return pdfdocEnc(element)
else:
return pdfdocEnc(str(element))
def xObjectName(externalname):
return "FormXob.%s" % externalname
# backwards compatibility
formName = xObjectName
# no encryption
class NoEncryption:
def encode(self, t):
"encode a string, stream, text"
return t
def prepare(self, document):
# get ready to do encryption
pass
def register(self, objnum, version):
# enter a new direct object
pass
def info(self):
# the representation of self in file if any (should be None or PDFDict)
return None
class PDFObject(object):
pass
class DummyDoc(PDFObject):
"used to bypass encryption when required"
encrypt = NoEncryption()
### the global document structure manager
class PDFDocument(PDFObject):
# set this to define filters
defaultStreamFilters = None
encrypt = NoEncryption() # default no encryption
def __init__(self,
dummyoutline=0,
compression=rl_config.pageCompression,
invariant=rl_config.invariant,
filename=None,
pdfVersion=PDF_VERSION_DEFAULT,
):
self._ID = None
self.objectcounter = 0
self.shadingCounter = 0
self.inObject = None
self.pageCounter = 1
# allow None value to be passed in to mean 'give system defaults'
if invariant is None:
self.invariant = rl_config.invariant
else:
self.invariant = invariant
self.setCompression(compression)
self._pdfVersion = pdfVersion
# signature for creating PDF ID
sig = self.signature = md5()
sig.update(b"a reportlab document")
if not self.invariant:
cat = _getTimeStamp()
else:
cat = 946684800.0
cat = ascii(cat)
sig.update(bytestr(cat)) # initialize with timestamp digest
# mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0)
self.idToObjectNumberAndVersion = {}
# mapping of internal identifier ("Page001") to PDF object (PDFPage instance)
self.idToObject = {}
# internal id to file location
self.idToOffset = {}
# number to id
self.numberToId = {}
cat = self.Catalog = self._catalog = PDFCatalog()
pages = self.Pages = PDFPages()
cat.Pages = pages
if dummyoutline:
outlines = PDFOutlines0()
else:
outlines = PDFOutlines()
self.Outlines = self.outline = outlines
cat.Outlines = outlines
self.info = PDFInfo()
self.info.invariant = self.invariant
#self.Reference(self.Catalog)
#self.Reference(self.Info)
self.fontMapping = {}
#make an empty font dictionary
DD = PDFDictionary({})
DD.__Comment__ = "The standard fonts dictionary"
self.Reference(DD, BasicFonts)
self.delayedFonts = []
def setCompression(self, onoff):
# XXX: maybe this should also set self.defaultStreamFilters?
self.compression = onoff
def ensureMinPdfVersion(self, *keys):
"Ensure that the pdf version is greater than or equal to that specified by the keys"
for k in keys:
self._pdfVersion = max(self._pdfVersion, PDF_SUPPORT_VERSION[k])
def updateSignature(self, thing):
"add information to the signature"
if self._ID: return # but not if its used already!
self.signature.update(bytestr(thing))
def ID(self):
"A unique fingerprint for the file (unless in invariant mode)"
if self._ID:
return self._ID
digest = self.signature.digest()
doc = DummyDoc()
IDs = PDFString(digest,enc='raw').format(doc)
self._ID = (b'\r\n % ReportLab generated PDF document -- digest (http://www.reportlab.com)\r\n ['
+IDs+b' '+IDs+b']\r\n')
return self._ID
def SaveToFile(self, filename, canvas):
if hasattr(getattr(filename, "write",None),'__call__'):
myfile = 0
f = filename
filename = makeFileName(getattr(filename,'name',''))
else :
myfile = 1
filename = makeFileName(filename)
f = open(filename, "wb")
data = self.GetPDFData(canvas)
if isUnicode(data):
data = data.encode('latin1')
f.write(data)
if myfile:
f.close()
import os
if os.name=='mac':
from reportlab.lib.utils import markfilename
markfilename(filename) # do platform specific file junk
if getattr(canvas,'_verbosity',None): print('saved %s' % (filename,))
def GetPDFData(self, canvas):
# realize delayed fonts
for fnt in self.delayedFonts:
fnt.addObjects(self)
# add info stuff to signature
self.info.invariant = self.invariant
self.info.digest(self.signature)
### later: maybe add more info to sig?
# prepare outline
self.Reference(self.Catalog)
self.Reference(self.info)
outline = self.outline
outline.prepare(self, canvas)
return self.format()
def inPage(self):
"""specify the current object as a page (enables reference binding and other page features)"""
if self.inObject is not None:
if self.inObject=="page": return
raise ValueError("can't go in page already in object %s" % self.inObject)
self.inObject = "page"
def inForm(self):
"""specify that we are in a form xobject (disable page features, etc)"""
# don't need this check anymore since going in a form pushes old context at canvas level.
#if self.inObject not in ["form", None]:
# raise ValueError("can't go in form already in object %s" % self.inObject)
self.inObject = "form"
# don't need to do anything else, I think...
def getInternalFontName(self, psfontname):
fm = self.fontMapping
if psfontname in fm:
return fm[psfontname]
else:
try:
# does pdfmetrics know about it? if so, add
fontObj = pdfmetrics.getFont(psfontname)
if fontObj._dynamicFont:
raise PDFError("getInternalFontName(%s) called for a dynamic font" % repr(psfontname))
fontObj.addObjects(self)
return fm[psfontname]
except KeyError:
raise PDFError("Font %s not known!" % repr(psfontname))
def thisPageName(self):
return "Page"+repr(self.pageCounter)
def thisPageRef(self):
return PDFObjectReference(self.thisPageName())
def addPage(self, page):
name = self.thisPageName()
self.Reference(page, name)
self.Pages.addPage(page)
self.pageCounter += 1
self.inObject = None
def addForm(self, name, form):
"""add a Form XObject."""
# XXX should check that name is a legal PDF name
if self.inObject != "form":
self.inForm()
self.Reference(form, xObjectName(name))
self.inObject = None
def annotationName(self, externalname):
return "Annot.%s"%externalname
def addAnnotation(self, name, annotation):
self.Reference(annotation, self.annotationName(name))
def refAnnotation(self, name):
internalname = self.annotationName(name)
return PDFObjectReference(internalname)
def addShading(self, shading):
name = "Sh%d" % self.shadingCounter
self.Reference(shading, name)
self.shadingCounter += 1
return name
def addColor(self,cmyk):
sname = cmyk.spotName
if not sname:
if cmyk.cyan==0 and cmyk.magenta==0 and cmyk.yellow==0:
sname = 'BLACK'
elif cmyk.black==0 and cmyk.magenta==0 and cmyk.yellow==0:
sname = 'CYAN'
elif cmyk.cyan==0 and cmyk.black==0 and cmyk.yellow==0:
sname = 'MAGENTA'
elif cmyk.cyan==0 and cmyk.magenta==0 and cmyk.black==0:
sname = 'YELLOW'
if not sname:
raise ValueError("CMYK colour %r used without a spotName" % cmyk)
else:
cmyk = cmyk.clone(spotName = sname)
name = PDFName(sname)[1:]
if name not in self.idToObject:
sep = PDFSeparationCMYKColor(cmyk).value() #PDFArray([/Separation /name /DeviceCMYK tint_tf])
self.Reference(sep,name)
return name,sname
def setTitle(self, title):
"embeds in PDF file"
if title is None:
self.info.title = '(anonymous)'
else:
self.info.title = title
def setAuthor(self, author):
"embedded in PDF file"
#allow resetting to clear it
if author is None:
self.info.author = '(anonymous)'
else:
self.info.author = author
def setSubject(self, subject):
"embeds in PDF file"
#allow resetting to clear it
if subject is None:
self.info.subject = '(unspecified)'
else:
self.info.subject = subject
def setCreator(self, creator):
"embeds in PDF file"
#allow resetting to clear it
if creator is None:
self.info.creator = '(unspecified)'
else:
self.info.creator = creator
def setKeywords(self, keywords):
"embeds a string containing keywords in PDF file"
#allow resetting to clear it but ensure it's a string
if keywords is None:
self.info.keywords = ''
else:
self.info.keywords = keywords
def setDateFormatter(self, dateFormatter):
self.info._dateFormatter = dateFormatter
def getAvailableFonts(self):
fontnames = list(self.fontMapping.keys())
# the standard 14 are also always available! (even if not initialized yet)
from reportlab.pdfbase import _fontdata
for name in _fontdata.standardFonts:
if name not in fontnames:
fontnames.append(name)
fontnames.sort()
return fontnames
def format(self):
# register the Catalog/INfo and then format the objects one by one until exhausted
# (possible infinite loop if there is a bug that continually makes new objects/refs...)
# Prepare encryption
self.encrypt.prepare(self)
cat = self.Catalog
info = self.info
self.Reference(self.Catalog)
self.Reference(self.info)
# register the encryption dictionary if present
encryptref = None
encryptinfo = self.encrypt.info()
if encryptinfo:
encryptref = self.Reference(encryptinfo)
# make std fonts (this could be made optional
counter = 0 # start at first object (object 1 after preincrement)
ids = [] # the collection of object ids in object number order
numbertoid = self.numberToId
idToNV = self.idToObjectNumberAndVersion
idToOb = self.idToObject
idToOf = self.idToOffset
### note that new entries may be "appended" DURING FORMATTING
done = None
# __accum__ allows objects to know where they are in the file etc etc
self.__accum__ = File = PDFFile(self._pdfVersion) # output collector
while done is None:
counter += 1 # do next object...
if counter in numbertoid:
id = numbertoid[counter]
#printidToOb
obj = idToOb[id]
IO = PDFIndirectObject(id, obj)
# register object number and version
#encrypt.register(id,
IOf = IO.format(self)
# add a comment to the PDF output
if not rl_config.invariant and rl_config.pdfComments:
try:
classname = obj.__class__.__name__
except:
classname = ascii(obj)
File.add("%% %s: class %s \r\n" % (ascii(id), classname[:50]))
offset = File.add(IOf)
idToOf[id] = offset
ids.append(id)
else:
done = 1
del self.__accum__
# sanity checks (must happen AFTER formatting)
lno = len(numbertoid)
if counter-1!=lno:
raise ValueError("counter %s doesn't match number to id dictionary %s" %(counter, lno))
# now add the xref
xref = PDFCrossReferenceTable()
xref.addsection(0, ids)
xreff = xref.format(self)
xrefoffset = File.add(xreff)
# now add the trailer
trailer = PDFTrailer(
startxref = xrefoffset,
Size = lno+1,
Root = self.Reference(cat),
Info = self.Reference(info),
Encrypt = encryptref,
ID = self.ID(),
)
trailerf = trailer.format(self)
File.add(trailerf)
for ds in getattr(self,'_digiSigs',[]):
ds.sign(File)
# return string format for pdf file
return File.format(self)
def hasForm(self, name):
"""test for existence of named form"""
internalname = xObjectName(name)
return internalname in self.idToObject
def getFormBBox(self, name, boxType="MediaBox"):
"""get the declared bounding box of the form as a list.
If you specify a different PDF box definition (e.g. the
ArtBox) and it has one, that's what you'll get."""
internalname = xObjectName(name)
if internalname in self.idToObject:
theform = self.idToObject[internalname]
if hasattr(theform,'_extra_pageCatcher_info'):
return theform._extra_pageCatcher_info[boxType]
if isinstance(theform, PDFFormXObject):
# internally defined form
return theform.BBoxList()
elif isinstance(theform, PDFStream):
# externally defined form
return list(theform.dictionary.dict[boxType].sequence)
else:
raise ValueError("I don't understand the form instance %s" % repr(name))
def getXObjectName(self, name):
"""Lets canvas find out what form is called internally.
Never mind whether it is defined yet or not."""
return xObjectName(name)
def xobjDict(self, formnames):
"""construct an xobject dict (for inclusion in a resource dict, usually)
from a list of form names (images not yet supported)"""
D = {}
for name in formnames:
internalname = xObjectName(name)
reference = PDFObjectReference(internalname)
D[internalname] = reference
#print "xobjDict D", D
return PDFDictionary(D)
def Reference(self, obj, name=None):
### note references may "grow" during the final formatting pass: don't use d.keys()!
# don't make references to other references, or non instances, unless they are named!
iob = isinstance(obj,PDFObject)
idToObject = self.idToObject
if name is None and (not iob or obj.__class__ is PDFObjectReference):
return obj
if hasattr(obj, __InternalName__):
# already registered
intname = obj.__InternalName__
if name is not None and name!=intname:
raise ValueError("attempt to reregister object %s with new name %s" % (
repr(intname), repr(name)))
if intname not in idToObject:
raise ValueError("object of type %s named as %s, but not registered" % (type(obj),ascii(intname)))
return PDFObjectReference(intname)
# otherwise register the new object
objectcounter = self.objectcounter = self.objectcounter+1
if name is None:
name = "R"+repr(objectcounter)
if name in idToObject:
other = idToObject[name]
if other!=obj:
raise ValueError("redefining named object: "+repr(name))
return PDFObjectReference(name)
if iob:
obj.__InternalName__ = name
#print "name", name, "counter", objectcounter
self.idToObjectNumberAndVersion[name] = (objectcounter, 0)
self.numberToId[objectcounter] = name
idToObject[name] = obj
return PDFObjectReference(name)
### chapter 4 Objects
PDFtrue = "true"
PDFfalse = "false"
PDFnull = "null"
class PDFText(PDFObject):
def __init__(self, t):
self.t = t
def format(self, document):
t = self.t
if isUnicode(t):
t = t.encode('utf-8')
result = binascii.hexlify(document.encrypt.encode(t))
return b"<" + result + b">"
def __str__(self):
dummydoc = DummyDoc()
return self.format(dummydoc)
def PDFnumber(n):
return n
import re
_re_cleanparens=re.compile('[^()]')
del re
def _isbalanced(s):
'''test whether a string is balanced in parens'''
s = _re_cleanparens.sub('',s)
n = 0
for c in s:
if c=='(': n+=1
else:
n -= 1
if n<0: return 0
return not n and 1 or 0
def _checkPdfdoc(utext):
'''return true if no Pdfdoc encoding errors'''
try:
utext.encode('pdfdoc')
return 1
except UnicodeEncodeError as e:
return 0
class PDFString(PDFObject):
def __init__(self, s, escape=1, enc='auto'):
'''s can be unicode/utf8 or a PDFString
if escape is true then the output will be passed through escape
if enc is raw then the string will be left alone
if enc is auto we'll try and automatically adapt to utf_16_be if the
effective string is not entirely in pdfdoc
'''
if isinstance(s,PDFString):
self.s = s.s
self.escape = s.escape
self.enc = s.enc
else:
self.s = s
self.escape = escape
self.enc = enc
def format(self, document):
s = self.s
enc = getattr(self,'enc','auto')
if (isBytes(s)):
if enc is 'auto':
try:
u = s.decode(s.startswith(codecs.BOM_UTF16_BE) and 'utf16' or 'utf8')
if _checkPdfdoc(u):
s = u.encode('pdfdoc')
else:
s = codecs.BOM_UTF16_BE+u.encode('utf_16_be')
except:
try:
s.decode('pdfdoc')
except:
stderr.write('Error in %s' % (repr(s),))
raise
elif isUnicode(s):
if enc is 'auto':
if _checkPdfdoc(s):
s = s.encode('pdfdoc')
else:
s = codecs.BOM_UTF16_BE+s.encode('utf_16_be')
else:
s = codecs.BOM_UTF16_BE+s.encode('utf_16_be')
else:
raise ValueError('PDFString argument must be str/unicode not %s' % type(s))
escape = getattr(self,'escape',1)
if not isinstance(document.encrypt,NoEncryption):
s = document.encrypt.encode(s)
escape = 1
if escape:
try:
es = "(%s)" % escapePDF(s)
except:
raise ValueError("cannot escape %s %s" % (s, repr(s)))
if escape&2:
es = es.replace('\\012','\n')
if escape&4 and _isbalanced(es):
es = es.replace('\\(','(').replace('\\)',')')
return pdfdocEnc(es)
else:
return b'(' + s + b')'
def __str__(self):
return "(%s)" % escapePDF(self.s)
def PDFName(data,lo=chr(0x21),hi=chr(0x7e)):
# might need to change this to class for encryption
# NOTE: RESULT MUST ALWAYS SUPPORT MEANINGFUL COMPARISONS (EQUALITY) AND HASH
# first convert the name
L = list(data)
for i,c in enumerate(L):
if c<lo or c>hi or c in "%()<>{}[]#":
L[i] = "#"+hex(ord(c))[2:] # forget the 0x thing...
return "/"+(''.join(L))
class PDFDictionary(PDFObject):
multiline = True
def __init__(self, dict=None):
"""dict should be namestring to value eg "a": 122 NOT pdfname to value NOT "/a":122"""
if dict is None:
self.dict = {}
else:
self.dict = dict.copy()
def __setitem__(self, name, value):
self.dict[name] = value
def __getitem__(self, a):
return self.dict[a]
def __contains__(self,a):
return a in self.dict
def Reference(self, name, document):
self.dict[name] = document.Reference(self.dict[name])
def format(self, document,IND=b'\r\n '):
dict = self.dict
try:
keys = list(dict.keys())
except:
print(ascii(dict))
raise
if not isinstance(dict,OrderedDict): keys.sort()
L = [(format(PDFName(k),document)+b" "+format(dict[k],document)) for k in keys]
if self.multiline and rl_config.pdfMultiLine:
L = IND.join(L)
else:
# break up every 6 elements anyway
t=L.insert
for i in reversed(range(6, len(L), 6)):
t(i,b'\r\n ')
L = b" ".join(L)
return b'<< '+L+b' >>'
def copy(self):
return PDFDictionary(self.dict)
def normalize(self):
#normalize the names to use RL standard ie Name not /Name
D = self.dict
K = [k for k in D.keys() if k.startswith('/')]
for k in K:
D[k[1:]] = D.pop(k)
class checkPDFNames:
def __init__(self,*names):
self.names = list(map(PDFName,names))
def __call__(self,value):
if not value.startswith('/'):
value=PDFName(value)
if value in self.names:
return value
def checkPDFBoolean(value):
if value in ('true','false'): return value
class CheckedPDFDictionary(PDFDictionary):
validate = {}
def __init__(self,dict=None,validate=None):
PDFDictionary.__init__(self,dict)
if validate: self.validate = validate
def __setitem__(self,name,value):
if name not in self.validate:
raise ValueError('invalid key, %r' % name)
cvalue = self.validate[name](value)
if cvalue is None:
raise ValueError('Bad value %r for key %r' % (value,name))
PDFDictionary.__setitem__(self,name,cvalue)
class ViewerPreferencesPDFDictionary(CheckedPDFDictionary):
validate=dict(
HideToolbar=checkPDFBoolean,
HideMenubar=checkPDFBoolean,
HideWindowUI=checkPDFBoolean,
FitWindow=checkPDFBoolean,
CenterWindow=checkPDFBoolean,
DisplayDocTitle=checkPDFBoolean, #contributed by mark Erbaugh
NonFullScreenPageMode=checkPDFNames(*'UseNone UseOutlines UseThumbs UseOC'.split()),
Direction=checkPDFNames(*'L2R R2L'.split()),
ViewArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
ViewClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
PrintArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
PrintClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
PrintScaling=checkPDFNames(*'None AppDefault'.split()),
)
# stream filters are objects to support round trip and
# possibly in the future also support parameters
class PDFStreamFilterZCompress:
pdfname = "FlateDecode"
def encode(self, text):
from reportlab.lib.utils import import_zlib
zlib = import_zlib()
if not zlib: raise ImportError("cannot z-compress zlib unavailable")
if isUnicode(text):
text = text.encode('utf8')
return zlib.compress(text)
def decode(self, encoded):
from reportlab.lib.utils import import_zlib
zlib = import_zlib()
if not zlib: raise ImportError("cannot z-decompress zlib unavailable")
return zlib.decompress(encoded)
# need only one of these, unless we implement parameters later
PDFZCompress = PDFStreamFilterZCompress()
class PDFStreamFilterBase85Encode:
pdfname = "ASCII85Decode"
def encode(self, text):
from reportlab.pdfbase.pdfutils import _wrap
text = asciiBase85Encode(text)
if rl_config.wrapA85:
text = _wrap(text)
return text
def decode(self, text):
return asciiBase85Decode(text)
# need only one of these too
PDFBase85Encode = PDFStreamFilterBase85Encode()
class PDFStream(PDFObject):
'''set dictionary elements explicitly stream.dictionary[name]=value'''
### compression stuff not implemented yet
__RefOnly__ = 1 # must be at top level
def __init__(self, dictionary=None, content=None, filters=None):
if dictionary is None:
dictionary = PDFDictionary()
self.dictionary = dictionary
self.content = content
self.filters = filters
def format(self, document):
dictionary = self.dictionary
# copy it for modification
dictionary = PDFDictionary(dictionary.dict.copy())
content = self.content
filters = self.filters
if self.content is None:
raise ValueError("stream content not set")
if filters is None:
filters = document.defaultStreamFilters
# only apply filters if they haven't been applied elsewhere
if filters is not None and "Filter" not in dictionary.dict:
# apply filters in reverse order listed
rf = list(filters)
rf.reverse()
fnames = []
for f in rf:
#print "*****************content:"; print repr(content[:200])
#print "*****************filter", f.pdfname
content = f.encode(content)
fnames.insert(0, PDFName(f.pdfname))
#print "*****************finally:"; print content[:200]
#print "****** FILTERS", fnames
#stop
dictionary["Filter"] = PDFArray(fnames)
# "stream encoding is done after all filters have been applied"
content = document.encrypt.encode(content)
fc = format(content, document)
dictionary["Length"] = len(content)
fd = format(dictionary, document)
return fd+b'\r\nstream\r\n'+fc+b'endstream\r\n'
def teststream(content=None):
#content = "" # test
if content is None:
content = teststreamcontent
content = content.strip()
content = content.replace("\n", '\n\r') + '\n\r'
S = PDFStream(content = content,
filters=rl_config.useA85 and [PDFBase85Encode,PDFZCompress] or [PDFZCompress])
# nothing else needed...
S.__Comment__ = "test stream"
return S
teststreamcontent = """
1 0 0 1 0 0 cm BT /F9 12 Tf 14.4 TL ET
1.00 0.00 1.00 rg
n 72.00 72.00 432.00 648.00 re B*
"""
class PDFArray(PDFObject):
multiline = True
def __init__(self, sequence):
self.sequence = list(sequence)
def References(self, document):
"""make all objects in sequence references"""
self.sequence = list(map(document.Reference, self.sequence))
def format(self, document, IND=b'\r\n '):
L = [format(e, document) for e in self.sequence]
if self.multiline and rl_config.pdfMultiLine:
L = IND.join(L)
else:
n=len(L)
if n>10:
# break up every 10 elements anyway
t=L.insert
for i in reversed(range(10, n, 10)):
t(i,b'\r\n ')
L = b' '.join(L)
else:
L = b' '.join(L)
return b'[ ' + L + b' ]'
class PDFArrayCompact(PDFArray):
multiline=False
class PDFIndirectObject(PDFObject):
__RefOnly__ = 1
def __init__(self, name, content):
self.name = name
self.content = content
def format(self, document):
name = self.name
n, v = document.idToObjectNumberAndVersion[name]
# set encryption parameters
document.encrypt.register(n, v)
fcontent = format(self.content, document, toplevel=1) # yes this is at top level
return (pdfdocEnc("%s %s obj\r\n"%(n,v))
+fcontent+ (b'' if fcontent.endswith(b'\r\n') else b'\r\n')
+b'endobj\r\n')
class PDFObjectReference(PDFObject):
def __init__(self, name):
self.name = name
def format(self, document):
try:
return pdfdocEnc("%s %s R" % document.idToObjectNumberAndVersion[self.name])
except:
raise KeyError("forward reference to %s not resolved upon final formatting" % repr(self.name))
class PDFFile(PDFObject):
### just accumulates strings: keeps track of current offset
def __init__(self,pdfVersion=PDF_VERSION_DEFAULT):
self.strings = []
self.write = self.strings.append
self.offset = 0
### chapter 5
# Following Ken Lunde's advice and the PDF spec, this includes
# some high-order bytes. I chose the characters for Tokyo
# in Shift-JIS encoding, as these cannot be mistaken for
# any other encoding, and we'll be able to tell if something
# has run our PDF files through a dodgy Unicode conversion.
self.add((pdfdocEnc("%%PDF-%s.%s" % pdfVersion) +
b'\r\n%\223\214\213\236 ReportLab Generated PDF document http://www.reportlab.com\r\n'
))
def closeOrReset(self):
pass
def add(self, s):
"""should be constructed as late as possible, return position where placed"""
s = pdfdocEnc(s)
result = self.offset
self.offset = result+len(s)
self.write(s)
return result
def format(self, document):
return b''.join(self.strings)
XREFFMT = '%0.10d %0.5d n'
class PDFCrossReferenceSubsection(PDFObject):
def __init__(self, firstentrynumber, idsequence):
self.firstentrynumber = firstentrynumber
self.idsequence = idsequence
def format(self, document):
"""id sequence should represent contiguous object nums else error. free numbers not supported (yet)"""
firstentrynumber = self.firstentrynumber
idsequence = self.idsequence
entries = list(idsequence)
nentries = len(idsequence)
# special case: object number 0 is always free
taken = {}
if firstentrynumber==0:
taken[0] = "standard free entry"
nentries = nentries+1
entries.insert(0, "0000000000 65535 f")
idToNV = document.idToObjectNumberAndVersion
idToOffset = document.idToOffset
lastentrynumber = firstentrynumber+nentries-1
for id in idsequence:
(num, version) = idToNV[id]
if num in taken:
raise ValueError("object number collision %s %s %s" % (num, repr(id), repr(taken[id])))
if num>lastentrynumber or num<firstentrynumber:
raise ValueError("object number %s not in range %s..%s" % (num, firstentrynumber, lastentrynumber))
# compute position in list
rnum = num-firstentrynumber
taken[num] = id
offset = idToOffset[id]
entries[num] = XREFFMT % (offset, version)
# now add the initial line
firstline = "%s %s" % (firstentrynumber, nentries)
entries.insert(0, firstline)
# make sure it ends with \r\n
entries.append("")
return pdfdocEnc('\r\n'.join(entries))
class PDFCrossReferenceTable(PDFObject):
def __init__(self):
self.sections = []
def addsection(self, firstentry, ids):
section = PDFCrossReferenceSubsection(firstentry, ids)
self.sections.append(section)
def format(self, document):
sections = self.sections
if not sections:
raise ValueError("no crossref sections")
L = [b"xref\r\n"]
for s in self.sections:
fs = format(s, document)
L.append(fs)
return pdfdocEnc(b''.join(L))
class PDFTrailer(PDFObject):
def __init__(self, startxref, Size=None, Prev=None, Root=None, Info=None, ID=None, Encrypt=None):
self.startxref = startxref
if Size is None or Root is None:
raise ValueError("Size and Root keys required")
dict = self.dict = PDFDictionary()
for (n,v) in [("Size", Size), ("Prev", Prev), ("Root", Root),
("Info", Info), ("ID", ID), ("Encrypt", Encrypt)]:
if v is not None:
dict[n] = v
def format(self, document):
fdict = format(self.dict, document)
return b''.join([
b'trailer\r\n',
fdict,
b'\r\nstartxref\r\n',
pdfdocEnc(str(self.startxref)),
b'\r\n%%EOF\r\n',
]
)
#### XXXX skipping incremental update,
#### encryption
#### chapter 6, doc structure
class PDFCatalog(PDFObject):
__Comment__ = "Document Root"
__RefOnly__ = 1
# to override, set as attributes
__Defaults__ = {"Type": PDFName("Catalog"),
"PageMode": PDFName("UseNone"),
"Lang": None,
}
__NoDefault__ = """
Dests Outlines Pages Threads AcroForm Names OpenAction PageMode URI
ViewerPreferences PageLabels PageLayout JavaScript StructTreeRoot SpiderInfo""".split()
__Refs__ = __NoDefault__ # make these all into references, if present
def format(self, document):
self.check_format(document)
defaults = self.__Defaults__
Refs = self.__Refs__
D = {}
for k,v in defaults.items():
v = getattr(self,k,v)
if v is not None:
D[k] = v
for k in self.__NoDefault__:
v = getattr(self,k,None)
if v is not None:
D[k] = v
# force objects to be references where required
for k in Refs:
if k in D:
#print"k is", k, "value", D[k]
D[k] = document.Reference(D[k])
dict = PDFDictionary(D)
return format(dict, document)
def showOutline(self):
self.setPageMode("UseOutlines")
def showFullScreen(self):
self.setPageMode("FullScreen")
def setPageLayout(self,layout):
if layout:
self.PageLayout = PDFName(layout)
def setPageMode(self,mode):
if mode:
self.PageMode = PDFName(mode)
def check_format(self, document):
"""for use in subclasses"""
pass
class PDFPages(PDFCatalog):
"""PAGES TREE WITH ONE INTERNAL NODE, FOR "BALANCING" CHANGE IMPLEMENTATION"""
__Comment__ = "page tree"
__RefOnly__ = 1
# note: could implement page attribute inheritance...
__Defaults__ = {"Type": PDFName("Pages"),
}
__NoDefault__ = "Kids Count Parent".split()
__Refs__ = ["Parent"]
def __init__(self):
self.pages = []
def __getitem__(self, item):
return self.pages[item]
def addPage(self, page):
self.pages.append(page)
def check_format(self, document):
# convert all pages to page references
pages = self.pages
kids = PDFArray(pages)
# make sure all pages are references
kids.References(document)
self.Kids = kids
self.Count = len(pages)
class PDFPage(PDFCatalog):
__Comment__ = "Page dictionary"
# all PDF attributes can be set explicitly
# if this flag is set, the "usual" behavior will be suppressed
Override_default_compilation = 0
__RefOnly__ = 1
__Defaults__ = {"Type": PDFName("Page"),
# "Parent": PDFObjectReference(Pages), # no! use document.Pages
}
__NoDefault__ = """Parent
MediaBox Resources Contents CropBox Rotate Thumb Annots B Dur Hid Trans AA
PieceInfo LastModified SeparationInfo ArtBox TrimBox BleedBox ID PZ
Trans""".split()
__Refs__ = """Contents Parent ID""".split()
pagewidth = 595
pageheight = 842
stream = None
hasImages = 0
compression = 0
XObjects = None
_colorsUsed = {}
_shadingsUsed = {}
Trans = None
# transitionstring?
# xobjects?
# annotations
def __init__(self):
# set all nodefaults to None
for name in self.__NoDefault__:
setattr(self, name, None)
def setCompression(self, onoff):
self.compression = onoff
def setStream(self, code):
if self.Override_default_compilation:
raise ValueError("overridden! must set stream explicitly")
if isSeq(code):
code = '\r\n'.join(code)+'\r\n'
self.stream = code
def setPageTransition(self, tranDict):
self.Trans = PDFDictionary(tranDict)
def check_format(self, document):
# set up parameters unless usual behaviour is suppressed
if self.Override_default_compilation:
return
self.MediaBox = self.MediaBox or PDFArray(self.Rotate in (90,270) and [0,0,self.pageheight,self.pagewidth] or [0, 0, self.pagewidth, self.pageheight])
if not self.Annots:
self.Annots = None
else:
#print self.Annots
#raise ValueError("annotations not reimplemented yet")
if not isinstance(self.Annots,PDFObject):
self.Annots = PDFArray(self.Annots)
if not self.Contents:
stream = self.stream
if not stream:
self.Contents = teststream()
else:
S = PDFStream()
if self.compression:
S.filters = rl_config.useA85 and [PDFBase85Encode, PDFZCompress] or [PDFZCompress]
S.content = stream
S.__Comment__ = "page stream"
self.Contents = S
if not self.Resources:
resources = PDFResourceDictionary()
# fonts!
resources.basicFonts()
if self.hasImages:
resources.allProcs()
else:
resources.basicProcs()
if self.XObjects:
#print "XObjects", self.XObjects.dict
resources.XObject = self.XObjects
if self.ExtGState:
resources.ExtGState = self.ExtGState
resources.setShading(self._shadingUsed)
resources.setColorSpace(self._colorsUsed)
self.Resources = resources
if not self.Parent:
pages = document.Pages
self.Parent = document.Reference(pages)
#this code contributed by Christian Jacobs <cljacobsen@gmail.com>
class DuplicatePageLabelPage(Exception):
pass
class PDFPageLabels(PDFCatalog):
__comment__ = None
__RefOnly__ = 0
__Defaults__ = {}
__NoDefault__ = ["Nums"]
__Refs__ = []
def __init__(self):
self.labels = []
def addPageLabel(self, page, label):
""" Adds a new PDFPageLabel to this catalog.
The 'page' argument, an integer, is the page number in the PDF document
with which the 'label' should be associated. Page numbering in the PDF
starts at zero! Thus, to change the label on the first page, '0' should be
provided as an argument, and to change the 6th page, '5' should be provided
as the argument.
The 'label' argument should be a PDFPageLabel instance, which describes the
format of the labels starting on page 'page' in the PDF and continuing
until the next encounter of a PDFPageLabel.
The order in which labels are added is not important.
"""
self.labels.append((page, label))
def format(self, document):
try:
self.labels.sort()
except DuplicatePageLabelPage:
tmp = sorted([x[0] for x in self.labels])
annotateException('\n\n!!!!! Duplicate PageLabel seen for pages %r' % list(set([x for x in tmp if tmp.count(x)>1])))
labels = []
for page, label in self.labels:
labels.append(page)
labels.append(label)
self.Nums = PDFArray(labels) #PDFArray makes a copy with list()
return PDFCatalog.format(self, document)
class PDFPageLabel(PDFCatalog):
__Comment__ = None
__RefOnly__ = 0
__Defaults__ = {}
__NoDefault__ = "Type S P St".split()
__convertible__ = 'ARABIC ROMAN_UPPER ROMAN_LOWER LETTERS_UPPER LETTERS_LOWER'
ARABIC = 'D'
ROMAN_UPPER = 'R'
ROMAN_LOWER = 'r'
LETTERS_UPPER = 'A'
LETTERS_LOWER = 'a'
def __init__(self, style=None, start=None, prefix=None):
"""
A PDFPageLabel changes the style of page numbering as displayed in a PDF
viewer. PDF page labels have nothing to do with 'physical' page numbers
printed on a canvas, but instead influence the 'logical' page numbers
displayed by PDF viewers. However, when using roman numerals (i, ii,
iii...) or page prefixes for appendecies (A.1, A.2...) on the physical
pages PDF page labels are necessary to change the logical page numbers
displayed by the PDF viewer to match up with the physical numbers. A
PDFPageLabel changes the properties of numbering at the page on which it
appears (see the class 'PDFPageLabels' for specifying where a PDFPageLabel
is associated) and all subsequent pages, until a new PDFPageLabel is
encountered.
The arguments to this initialiser determine the properties of all
subsequent page labels. 'style' determines the numberings style, arabic,
roman, letters; 'start' specifies the starting number; and 'prefix' any
prefix to be applied to the page numbers. All these arguments can be left
out or set to None.
* style:
- None: No numbering, can be used to display the prefix only.
- PDFPageLabel.ARABIC: Use arabic numbers: 1, 2, 3, 4...
- PDFPageLabel.ROMAN_UPPER: Use upper case roman numerals: I, II, III...
- PDFPageLabel.ROMAN_LOWER: Use lower case roman numerals: i, ii, iii...
- PDFPageLabel.LETTERS_UPPER: Use upper case letters: A, B, C, D...
- PDFPageLabel.LETTERS_LOWER: Use lower case letters: a, b, c, d...
* start:
- An integer specifying the starting number for this PDFPageLabel. This
can be used when numbering style changes to reset the page number back
to one, ie from roman to arabic, or from arabic to appendecies. Can be
any positive integer or None. I'm not sure what the effect of
specifying None is, probably that page numbering continues with the
current sequence, I'd have to check the spec to clarify though.
* prefix:
- A string which is prefixed to the page numbers. Can be used to display
appendecies in the format: A.1, A.2, ..., B.1, B.2, ... where a
PDFPageLabel is used to set the properties for the first page of each
appendix to restart the page numbering at one and set the prefix to the
appropriate letter for current appendix. The prefix can also be used to
display text only, if the 'style' is set to None. This can be used to
display strings such as 'Front', 'Back', or 'Cover' for the covers on
books.
"""
if style:
if style.upper() in self.__convertible__: style = getattr(self,style.upper())
self.S = PDFName(style)
if start: self.St = PDFnumber(start)
if prefix: self.P = PDFString(prefix)
def __lt__(self,oth):
if rl_config.errorOnDuplicatePageLabelPage:
raise DuplicatePageLabelPage()
return False
#ends code contributed by Christian Jacobs <cljacobsen@gmail.com>
def testpage(document):
P = PDFPage()
P.Contents = teststream()
pages = document.Pages
P.Parent = document.Reference(pages)
P.MediaBox = PDFArray([0, 0, 595, 841])
resources = PDFResourceDictionary()
resources.allProcs() # enable all procsets
resources.basicFonts()
P.Resources = resources
pages.addPage(P)
#### DUMMY OUTLINES IMPLEMENTATION FOR testing
DUMMYOUTLINE = """
<<
/Count
0
/Type
/Outlines
>>"""
class PDFOutlines0(PDFObject):
__Comment__ = "TEST OUTLINE!"
text = DUMMYOUTLINE.replace("\n", '\r\n')
__RefOnly__ = 1
def format(self, document):
return pdfdocEnc(self.text)
class OutlineEntryObject(PDFObject):
"an entry in an outline"
Title = Dest = Parent = Prev = Next = First = Last = Count = None
def format(self, document):
D = {}
D["Title"] = PDFString(self.Title)
D["Parent"] = self.Parent
D["Dest"] = self.Dest
for n in ("Prev", "Next", "First", "Last", "Count"):
v = getattr(self, n)
if v is not None:
D[n] = v
PD = PDFDictionary(D)
return PD.format(document)
class PDFOutlines(PDFObject):
"""
takes a recursive list of outline destinations like::
out = PDFOutline1()
out.setNames(canvas, # requires canvas for name resolution
"chapter1dest",
("chapter2dest",
["chapter2section1dest",
"chapter2section2dest",
"chapter2conclusiondest"]
), # end of chapter2 description
"chapter3dest",
("chapter4dest", ["c4s1", "c4s2"])
)
Higher layers may build this structure incrementally. KISS at base level.
"""
# first attempt, many possible features missing.
#no init for now
mydestinations = ready = None
counter = 0
currentlevel = -1 # ie, no levels yet
def __init__(self):
self.destinationnamestotitles = {}
self.destinationstotitles = {}
self.levelstack = []
self.buildtree = []
self.closedict = {} # dictionary of "closed" destinations in the outline
def addOutlineEntry(self, destinationname, level=0, title=None, closed=None):
"""destinationname of None means "close the tree" """
if destinationname is None and level!=0:
raise ValueError("close tree must have level of 0")
if not isinstance(level,int): raise ValueError("level must be integer, got %s" % type(level))
if level<0: raise ValueError("negative levels not allowed")
if title is None: title = destinationname
currentlevel = self.currentlevel
stack = self.levelstack
tree = self.buildtree
# adjust currentlevel and stack to match level
if level>currentlevel:
if level>currentlevel+1:
raise ValueError("can't jump from outline level %s to level %s, need intermediates (destinationname=%r, title=%r)" %(currentlevel, level, destinationname, title))
level = currentlevel = currentlevel+1
stack.append([])
while level<currentlevel:
# pop off levels to match
current = stack[-1]
del stack[-1]
previous = stack[-1]
lastinprevious = previous[-1]
if isinstance(lastinprevious,tuple):
(name, sectionlist) = lastinprevious
raise ValueError("cannot reset existing sections: " + repr(lastinprevious))
else:
name = lastinprevious
sectionlist = current
previous[-1] = (name, sectionlist)
#sectionlist.append(current)
currentlevel = currentlevel-1
if destinationname is None: return
stack[-1].append(destinationname)
self.destinationnamestotitles[destinationname] = title
if closed: self.closedict[destinationname] = 1
self.currentlevel = level
def setDestinations(self, destinationtree):
self.mydestinations = destinationtree
def format(self, document):
D = {}
D["Type"] = PDFName("Outlines")
c = self.count
D["Count"] = c
if c!=0:
D["First"] = self.first
D["Last"] = self.last
PD = PDFDictionary(D)
return PD.format(document)
def setNames(self, canvas, *nametree):
desttree = self.translateNames(canvas, nametree)
self.setDestinations(desttree)
def setNameList(self, canvas, nametree):
"Explicit list so I don't need to do in the caller"
desttree = self.translateNames(canvas, nametree)
self.setDestinations(desttree)
def translateNames(self, canvas, object):
"recursively translate tree of names into tree of destinations"
destinationnamestotitles = self.destinationnamestotitles
destinationstotitles = self.destinationstotitles
closedict = self.closedict
if isStr(object):
if not isUnicode(object): object = object.decode('utf8')
destination = canvas._bookmarkReference(object)
title = object
if object in destinationnamestotitles:
title = destinationnamestotitles[object]
else:
destinationnamestotitles[title] = title
destinationstotitles[destination] = title
if object in closedict:
closedict[destination] = 1 # mark destination closed
return {object: canvas._bookmarkReference(object)} # name-->ref
if isSeq(object):
L = []
for o in object:
L.append(self.translateNames(canvas, o))
if isinstance(object,tuple):
return tuple(L)
return L
# bug contributed by Benjamin Dumke <reportlab@benjamin-dumke.de>
raise TypeError("in outline, destination name must be string: got a %s"%type(object))
def prepare(self, document, canvas):
"""prepare all data structures required for save operation (create related objects)"""
if self.mydestinations is None:
if self.levelstack:
self.addOutlineEntry(None) # close the tree
destnames = self.levelstack[0]
#from pprint import pprint; pprint(destnames); stop
self.mydestinations = self.translateNames(canvas, destnames)
else:
self.first = self.last = None
self.count = 0
self.ready = 1
return
#self.first = document.objectReference("Outline.First")
#self.last = document.objectReference("Outline.Last")
# XXXX this needs to be generalized for closed entries!
self.count = count(self.mydestinations, self.closedict)
(self.first, self.last) = self.maketree(document, self.mydestinations, toplevel=1)
self.ready = 1
def maketree(self, document, destinationtree, Parent=None, toplevel=0):
if toplevel:
levelname = "Outline"
Parent = document.Reference(document.Outlines)
else:
self.count = self.count+1
levelname = "Outline.%s" % self.count
if Parent is None:
raise ValueError("non-top level outline elt parent must be specified")
if not isSeq(destinationtree):
raise ValueError("destinationtree must be list or tuple, got %s")
nelts = len(destinationtree)
lastindex = nelts-1
lastelt = firstref = lastref = None
destinationnamestotitles = self.destinationnamestotitles
closedict = self.closedict
for index in range(nelts):
eltobj = OutlineEntryObject()
eltobj.Parent = Parent
eltname = "%s.%s" % (levelname, index)
eltref = document.Reference(eltobj, eltname)
#document.add(eltname, eltobj)
if lastelt is not None:
lastelt.Next = eltref
eltobj.Prev = lastref
if firstref is None:
firstref = eltref
lastref = eltref
lastelt = eltobj # advance eltobj
lastref = eltref
elt = destinationtree[index]
if isinstance(elt,dict):
# simple leaf {name: dest}
leafdict = elt
elif isinstance(elt,tuple):
# leaf with subsections: ({name: ref}, subsections) XXXX should clean up (see count(...))
try:
(leafdict, subsections) = elt
except:
raise ValueError("destination tree elt tuple should have two elts, got %s" % len(elt))
eltobj.Count = count(subsections, closedict)
(eltobj.First, eltobj.Last) = self.maketree(document, subsections, eltref)
else:
raise ValueError("destination tree elt should be dict or tuple, got %s" % type(elt))
try:
[(Title, Dest)] = list(leafdict.items())
except:
raise ValueError("bad outline leaf dictionary, should have one entry "+bytestr(elt))
eltobj.Title = destinationnamestotitles[Title]
eltobj.Dest = Dest
if isinstance(elt,tuple) and Dest in closedict:
# closed subsection, count should be negative
eltobj.Count = -eltobj.Count
return (firstref, lastref)
def count(tree, closedict=None):
"""utility for outline: recursively count leaves in a tuple/list tree"""
from operator import add
if isinstance(tree,tuple):
# leaf with subsections XXXX should clean up this structural usage
(leafdict, subsections) = tree
[(Title, Dest)] = list(leafdict.items())
if closedict and Dest in closedict:
return 1 # closed tree element
if isSeq(tree):
#return reduce(add, map(count, tree))
counts = []
for e in tree:
counts.append(count(e, closedict))
return sum(counts) #used to be: return reduce(add, counts)
return 1
class PDFInfo(PDFObject):
"""PDF documents can have basic information embedded, viewable from
File | Document Info in Acrobat Reader. If this is wrong, you get
Postscript errors while printing, even though it does not print."""
producer = "ReportLab PDF Library - www.reportlab.com"
creator = "ReportLab PDF Library - www.reportlab.com"
title = "untitled"
author = "anonymous"
subject = "unspecified"
keywords = ""
_dateFormatter = None
def __init__(self):
self.invariant = rl_config.invariant
self.trapped = 'False' #could be 'True' or 'Unknown'
def digest(self, md5object):
# add self information to signature
for x in (self.title, self.author, self.subject, self.keywords):
md5object.update(bytestr(x))
def format(self, document):
D = {}
D["Title"] = PDFString(self.title)
D["Author"] = PDFString(self.author)
D['ModDate'] = D["CreationDate"] = PDFDate(invariant=self.invariant,dateFormatter=self._dateFormatter)
D["Producer"] = PDFString(self.producer)
D["Creator"] = PDFString(self.creator)
D["Subject"] = PDFString(self.subject)
D["Keywords"] = PDFString(self.keywords)
D["Trapped"] = PDFName(self.trapped)
PD = PDFDictionary(D)
return PD.format(document)
def copy(self):
"shallow copy - useful in pagecatchering"
thing = self.__klass__()
for k, v in self.__dict__.items():
setattr(thing, k, v)
return thing
# skipping thumbnails, etc
class Annotation(PDFObject):
"""superclass for all annotations."""
defaults = [("Type", PDFName("Annot"),)]
required = ("Type", "Rect", "Contents", "Subtype")
permitted = required+(
"Border", "C", "T", "M", "F", "H", "BS", "AA", "AS", "Popup", "P", "AP")
def cvtdict(self, d, escape=1):
"""transform dict args from python form to pdf string rep as needed"""
Rect = d["Rect"]
if not isStr(Rect):
d["Rect"] = PDFArray(Rect)
d["Contents"] = PDFString(d["Contents"],escape)
return d
def AnnotationDict(self, **kw):
if 'escape' in kw:
escape = kw['escape']
del kw['escape']
else:
escape = 1
d = {}
for (name,val) in self.defaults:
d[name] = val
d.update(kw)
for name in self.required:
if name not in d:
raise ValueError("keyword argument %s missing" % name)
d = self.cvtdict(d,escape=escape)
permitted = self.permitted
for name in d.keys():
if name not in permitted:
raise ValueError("bad annotation dictionary name %s" % name)
return PDFDictionary(d)
def Dict(self):
raise ValueError("DictString undefined for virtual superclass Annotation, must overload")
# but usually
#return self.AnnotationDict(self, Rect=(a,b,c,d)) or whatever
def format(self, document):
D = self.Dict()
return D.format(document)
class TextAnnotation(Annotation):
permitted = Annotation.permitted + (
"Open", "Name")
def __init__(self, Rect, Contents, **kw):
self.Rect = Rect
self.Contents = Contents
self.otherkw = kw
def Dict(self):
d = {}
d.update(self.otherkw)
d["Rect"] = self.Rect
d["Contents"] = self.Contents
d["Subtype"] = "/Text"
return self.AnnotationDict(**d)
class FreeTextAnnotation(Annotation):
permitted = Annotation.permitted + ("DA",)
def __init__(self, Rect, Contents, DA, **kw):
self.Rect = Rect
self.Contents = Contents
self.DA = DA
self.otherkw = kw
def Dict(self):
d = {}
d.update(self.otherkw)
d["Rect"] = self.Rect
d["Contents"] = self.Contents
d["DA"] = self.DA
d["Subtype"] = "/FreeText"
return self.AnnotationDict(**d)
class LinkAnnotation(Annotation):
permitted = Annotation.permitted + (
"Dest", "A", "PA")
def __init__(self, Rect, Contents, Destination, Border="[0 0 1]", **kw):
self.Border = Border
self.Rect = Rect
self.Contents = Contents
self.Destination = Destination
self.otherkw = kw
def dummyDictString(self): # old, testing
return """
<< /Type /Annot /Subtype /Link /Rect [71 717 190 734] /Border [16 16 1]
/Dest [23 0 R /Fit] >>
"""
def Dict(self):
d = {}
d.update(self.otherkw)
d["Border"] = self.Border
d["Rect"] = self.Rect
d["Contents"] = self.Contents
d["Subtype"] = "/Link"
d["Dest"] = self.Destination
return self.AnnotationDict(**d)
class HighlightAnnotation(Annotation):
"""
HighlightAnnotation is an annotation that highlights the selected area.
Rect is the mouseover area that will show the contents.
QuadPoints is a list of points to highlight, you can have many groups of
four QuadPoints to allow highlighting many lines.
"""
permitted = Annotation.permitted + ("QuadPoints", )
def __init__(self, Rect, Contents, QuadPoints, Color=[0.83, 0.89, 0.95], **kw):
self.Rect = Rect
self.Contents = Contents
self.otherkw = kw
self.QuadPoints = QuadPoints
self.Color = Color
def cvtdict(self, d, escape=1):
"""transform dict args from python form to pdf string rep as needed"""
Rect = d["Rect"]
Quad = d["QuadPoints"]
Color = d["C"]
if not isinstance(Rect, str):
d["Rect"] = PDFArray(Rect).format(d, IND=b" ")
if not isinstance(Quad, str):
d["QuadPoints"] = PDFArray(Quad).format(d, IND=b" ")
if not isinstance(Color, str):
d["C"] = PDFArray(Color).format(d, IND=b" ")
d["Contents"] = PDFString(d["Contents"], escape)
return d
def Dict(self):
d = {}
d.update(self.otherkw)
d["Rect"] = self.Rect
d["Contents"] = self.Contents
d["Subtype"] = "/Highlight"
d["QuadPoints"] = self.QuadPoints
d["C"] = self.Color
return self.AnnotationDict(**d)
def rect_to_quad(Rect):
"""
Utility method to convert a Rect to a QuadPoint
"""
return [Rect[0], Rect[1], Rect[2], Rect[1],
Rect[0], Rect[3], Rect[2], Rect[3]]
# skipping names tree
# skipping actions
# skipping names trees
# skipping to chapter 7
class PDFRectangle(PDFObject):
def __init__(self, llx, lly, urx, ury):
self.llx, self.lly, self.ulx, self.ury = llx, lly, urx, ury
def format(self, document):
A = PDFArray([self.llx, self.lly, self.ulx, self.ury])
return format(A, document)
_NOWT=None
def _getTimeStamp():
global _NOWT
if not _NOWT:
import time
_NOWT = time.time()
return _NOWT
class PDFDate(PDFObject):
# gmt offset now suppported properly
def __init__(self, invariant=rl_config.invariant, dateFormatter=None):
if invariant:
now = (2000,1,1,0,0,0,0)
self.dhh = 0
self.dmm = 0
else:
import time
now = tuple(time.localtime(_getTimeStamp())[:6])
from time import timezone
self.dhh = int(timezone / (3600.0))
self.dmm = (timezone % 3600) % 60
self.date = now[:6]
self.dateFormatter = dateFormatter
def format(self, doc):
dfmt = self.dateFormatter or (
lambda yyyy,mm,dd,hh,m,s:
"D:%04d%02d%02d%02d%02d%02d%+03d'%02d'"
% (yyyy,mm,dd,hh,m,s,self.dhh,self.dmm))
return format(PDFString(dfmt(*self.date)), doc)
class Destination(PDFObject):
"""
not a PDFObject! This is a placeholder that can delegates
to a pdf object only after it has been defined by the methods
below.
EG a Destination can refer to Appendix A before it has been
defined, but only if Appendix A is explicitly noted as a destination
and resolved before the document is generated...
For example the following sequence causes resolution before doc generation.
d = Destination()
d.fit() # or other format defining method call
d.setPage(p)
(at present setPageRef is called on generation of the page).
"""
representation = format = page = None
def __init__(self,name):
self.name = name
self.fmt = self.page = None
def format(self, document):
f = self.fmt
if f is None: raise ValueError("format not resolved, probably missing URL scheme or undefined destination target for '%s'" % self.name)
p = self.page
if p is None: raise ValueError("Page not bound, probably missing URL scheme or undefined destination target for '%s'" % self.name)
f.page = p
return f.format(document)
def xyz(self, left, top, zoom): # see pdfspec mar 11 99 pp184+
self.fmt = PDFDestinationXYZ(None, left, top, zoom)
def fit(self):
self.fmt = PDFDestinationFit(None)
def fitb(self):
self.fmt = PDFDestinationFitB(None)
def fith(self, top):
self.fmt = PDFDestinationFitH(None,top)
def fitv(self, left):
self.fmt = PDFDestinationFitV(None, left)
def fitbh(self, top):
self.fmt = PDFDestinationFitBH(None, top)
def fitbv(self, left):
self.fmt = PDFDestinationFitBV(None, left)
def fitr(self, left, bottom, right, top):
self.fmt = PDFDestinationFitR(None, left, bottom, right, top)
def setPage(self, page):
self.page = page
#self.fmt.page = page # may not yet be defined!
class PDFDestinationXYZ(PDFObject):
typename = "XYZ"
def __init__(self, page, left, top, zoom):
self.page = page
self.top = top
self.zoom = zoom
self.left = left
def format(self, document):
pageref = document.Reference(self.page)
A = PDFArray( [ pageref, PDFName(self.typename), self.left, self.top, self.zoom ] )
return format(A, document)
class PDFDestinationFit(PDFObject):
typename = "Fit"
def __init__(self, page):
self.page = page
def format(self, document):
pageref = document.Reference(self.page)
A = PDFArray( [ pageref, PDFName(self.typename) ] )
return format(A, document)
class PDFDestinationFitB(PDFDestinationFit):
typename = "FitB"
class PDFDestinationFitH(PDFObject):
typename = "FitH"
def __init__(self, page, top):
self.page = page; self.top=top
def format(self, document):
pageref = document.Reference(self.page)
A = PDFArray( [ pageref, PDFName(self.typename), self.top ] )
return format(A, document)
class PDFDestinationFitBH(PDFDestinationFitH):
typename = "FitBH"
class PDFDestinationFitV(PDFObject):
typename = "FitV"
def __init__(self, page, left):
self.page = page; self.left=left
def format(self, document):
pageref = document.Reference(self.page)
A = PDFArray( [ pageref, PDFName(self.typename), self.left ] )
return format(A, document)
class PDFDestinationFitBV(PDFDestinationFitV):
typename = "FitBV"
class PDFDestinationFitR(PDFObject):
typename = "FitR"
def __init__(self, page, left, bottom, right, top):
self.page = page; self.left=left; self.bottom=bottom; self.right=right; self.top=top
def format(self, document):
pageref = document.Reference(self.page)
A = PDFArray( [ pageref, PDFName(self.typename), self.left, self.bottom, self.right, self.top] )
return format(A, document)
# named destinations need nothing
# skipping filespecs
class PDFResourceDictionary(PDFObject):
"""each element *could* be reset to a reference if desired"""
def __init__(self):
self.ColorSpace = {}
self.XObject = {}
self.ExtGState = {}
self.Font = {}
self.Pattern = {}
self.ProcSet = []
self.Properties = {}
self.Shading = {}
# ?by default define the basicprocs
self.basicProcs()
stdprocs = [PDFName(s) for s in "PDF Text ImageB ImageC ImageI".split()]
dict_attributes = ("ColorSpace", "XObject", "ExtGState", "Font", "Pattern", "Properties", "Shading")
def allProcs(self):
# define all standard procsets
self.ProcSet = self.stdprocs
def basicProcs(self):
self.ProcSet = self.stdprocs[:2] # just PDF and Text
def basicFonts(self):
self.Font = PDFObjectReference(BasicFonts)
def setColorSpace(self,colorsUsed):
for c,s in colorsUsed.items():
self.ColorSpace[s] = PDFObjectReference(c)
def setShading(self,shadingUsed):
for c,s in shadingUsed.items():
self.Shading[s] = PDFObjectReference(c)
def format(self, document):
D = {}
for dname in self.dict_attributes:
v = getattr(self, dname)
if isinstance(v,dict):
if v:
dv = PDFDictionary(v)
D[dname] = dv
else:
D[dname] = v
v = self.ProcSet
dname = "ProcSet"
if isSeq(v):
if v:
dv = PDFArray(v)
D[dname] = dv
else:
D[dname] = v
DD = PDFDictionary(D)
return format(DD, document)
##############################################################################
#
# Font objects - the PDFDocument.addFont() method knows which of these
# to construct when given a user-facing Font object
#
##############################################################################
class PDFType1Font(PDFObject):
"""no init: set attributes explicitly"""
__RefOnly__ = 1
# note! /Name appears to be an undocumented attribute....
name_attributes = "Type Subtype BaseFont Name".split()
Type = "Font"
Subtype = "Type1"
# these attributes are assumed to already be of the right type
local_attributes = "FirstChar LastChar Widths Encoding ToUnicode FontDescriptor".split()
def format(self, document):
D = {}
for name in self.name_attributes:
if hasattr(self, name):
value = getattr(self, name)
D[name] = PDFName(value)
for name in self.local_attributes:
if hasattr(self, name):
value = getattr(self, name)
D[name] = value
#print D
PD = PDFDictionary(D)
return PD.format(document)
## These attribute listings will be useful in future, even if we
## put them elsewhere
class PDFTrueTypeFont(PDFType1Font):
Subtype = "TrueType"
#local_attributes = "FirstChar LastChar Widths Encoding ToUnicode FontDescriptor".split() #same
##class PDFMMType1Font(PDFType1Font):
## Subtype = "MMType1"
##
##class PDFType3Font(PDFType1Font):
## Subtype = "Type3"
## local_attributes = "FirstChar LastChar Widths CharProcs FontBBox FontMatrix Resources Encoding".split()
##
##class PDFType0Font(PDFType1Font):
## Subtype = "Type0"
## local_attributes = "DescendantFonts Encoding".split(
##
##class PDFCIDFontType0(PDFType1Font):
## Subtype = "CIDFontType0"
## local_attributes = "CIDSystemInfo FontDescriptor DW W DW2 W2 Registry Ordering Supplement".split()
##
##class PDFCIDFontType0(PDFType1Font):
## Subtype = "CIDFontType2"
## local_attributes = "BaseFont CIDToGIDMap CIDSystemInfo FontDescriptor DW W DW2 W2".split()
##
##class PDFEncoding(PDFType1Font):
## Type = "Encoding"
## name_attributes = "Type BaseEncoding".split()
## # these attributes are assumed to already be of the right type
## local_attributes = ["Differences"]
##
# UGLY ALERT - this needs turning into something O-O, it was hacked
# across from the pdfmetrics.Encoding class to avoid circularity
# skipping CMaps
class PDFFormXObject(PDFObject):
# like page requires .info set by some higher level (doc)
# XXXX any resource used in a form must be propagated up to the page that (recursively) uses
# the form!! (not implemented yet).
XObjects = Annots = BBox = Matrix = Contents = stream = Resources = None
hasImages = 1 # probably should change
compression = 0
def __init__(self, lowerx, lowery, upperx, uppery):
#not done
self.lowerx = lowerx; self.lowery=lowery; self.upperx=upperx; self.uppery=uppery
def setStreamList(self, data):
if isSeq(data):
data = '\r\n'.join(data)
self.stream = pdfdocEnc(data)
def BBoxList(self):
"get the declared bounding box for the form as a list"
if self.BBox:
return list(self.BBox.sequence)
else:
return [self.lowerx, self.lowery, self.upperx, self.uppery]
def format(self, document):
self.BBox = self.BBox or PDFArray([self.lowerx, self.lowery, self.upperx, self.uppery])
self.Matrix = self.Matrix or PDFArray([1, 0, 0, 1, 0, 0])
if not self.Annots:
self.Annots = None
else:
#these must be transferred to the page when the form is used
raise ValueError("annotations don't work in PDFFormXObjects yet")
if not self.Contents:
stream = self.stream
if not stream:
self.Contents = teststream()
else:
S = PDFStream()
S.content = stream
# need to add filter stuff (?)
S.__Comment__ = "xobject form stream"
self.Contents = S
if not self.Resources:
resources = PDFResourceDictionary()
# fonts!
resources.basicFonts()
if self.hasImages:
resources.allProcs()
else:
resources.basicProcs()
if self.XObjects:
#print "XObjects", self.XObjects.dict
resources.XObject = self.XObjects
self.Resources=resources
if self.compression:
self.Contents.filters = rl_config.useA85 and [PDFBase85Encode, PDFZCompress] or [PDFZCompress]
sdict = self.Contents.dictionary
sdict["Type"] = PDFName("XObject")
sdict["Subtype"] = PDFName("Form")
sdict["FormType"] = 1
sdict["BBox"] = self.BBox
sdict["Matrix"] = self.Matrix
sdict["Resources"] = self.Resources
return self.Contents.format(document)
class PDFPostScriptXObject(PDFObject):
"For embedding PD (e.g. tray commands) in PDF"
def __init__(self, content=None):
self.content = content
def format(self, document):
S = PDFStream()
S.content = self.content
S.__Comment__ = "xobject postscript stream"
sdict = S.dictionary
sdict["Type"] = PDFName("XObject")
sdict["Subtype"] = PDFName("PS")
return S.format(document)
_mode2CS={'RGB':'DeviceRGB', 'L':'DeviceGray', 'CMYK':'DeviceCMYK'}
class PDFImageXObject(PDFObject):
# first attempts at a hard-coded one
# in the file, Image XObjects are stream objects. We already
# have a PDFStream object with 3 attributes: dictionary, content
# and filters. So the job of this thing is to construct the
# right PDFStream instance and ask it to format itself.
def __init__(self, name, source=None, mask=None):
self.name = name
self.width = 24
self.height = 23
self.bitsPerComponent = 1
self.colorSpace = 'DeviceGray'
self._filters = rl_config.useA85 and ('ASCII85Decode',) or ()
self.streamContent = """
003B00 002700 002480 0E4940 114920 14B220 3CB650
75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC
B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800
1E1800 1FF800>
"""
self.mask = mask
if source is None:
pass # use the canned one.
elif hasattr(source,'jpeg_fh'):
self.loadImageFromSRC(source) #it is already a PIL Image
else:
# it is a filename
import os
ext = os.path.splitext(source)[1].lower()
src = open_for_read(source)
try:
if not(ext in ('.jpg', '.jpeg') and self.loadImageFromJPEG(src)):
if rl_config.useA85:
self.loadImageFromA85(src)
else:
self.loadImageFromRaw(src)
finally:
src.close()
def loadImageFromA85(self,source):
IMG=[]
imagedata = pdfutils.makeA85Image(source,IMG=IMG,detectJpeg=True)
if not imagedata:
return self.loadImageFromSRC(IMG[0])
imagedata = [s.strip() for s in imagedata]
words = imagedata[1].split()
self.width, self.height = (int(words[1]),int(words[3]))
self.colorSpace = {'/RGB':'DeviceRGB', '/G':'DeviceGray', '/CMYK':'DeviceCMYK'}[words[7]]
self.bitsPerComponent = 8
self._filters = 'ASCII85Decode','FlateDecode' #'A85','Fl'
if IMG: self._checkTransparency(IMG[0])
elif self.mask=='auto': self.mask = None
self.streamContent = ''.join(imagedata[3:-1])
def loadImageFromJPEG(self,imageFile):
try:
try:
info = pdfutils.readJPEGInfo(imageFile)
finally:
imageFile.seek(0) #reset file pointer
except:
return False
self.width, self.height = info[0], info[1]
self.bitsPerComponent = 8
if info[2] == 1:
self.colorSpace = 'DeviceGray'
elif info[2] == 3:
self.colorSpace = 'DeviceRGB'
else: #maybe should generate an error, is this right for CMYK?
self.colorSpace = 'DeviceCMYK'
self._dotrans = 1
self.streamContent = imageFile.read()
if rl_config.useA85:
self.streamContent = asciiBase85Encode(self.streamContent)
self._filters = 'ASCII85Decode','DCTDecode' #'A85','DCT'
else:
self._filters = 'DCTDecode', #'DCT'
self.mask = None
return True
def loadImageFromRaw(self,source):
IMG=[]
imagedata = pdfutils.makeRawImage(source,IMG=IMG,detectJpeg=True)
if not imagedata:
return self.loadImageFromSRC(IMG[0])
words = imagedata[1].split()
self.width = int(words[1])
self.height = int(words[3])
self.colorSpace = {'/RGB':'DeviceRGB', '/G':'DeviceGray', '/CMYK':'DeviceCMYK'}[words[7]]
self.bitsPerComponent = 8
self._filters = 'FlateDecode', #'Fl'
if IMG: self._checkTransparency(IMG[0])
elif self.mask=='auto': self.mask = None
self.streamContent = ''.join(imagedata[3:-1])
def _checkTransparency(self,im):
if self.mask=='auto':
if im._dataA:
self.mask = None
self._smask = PDFImageXObject(_digester(im._dataA.getRGBData()),im._dataA,mask=None)
self._smask._decode = [0,1]
else:
tc = im.getTransparent()
if tc:
self.mask = (tc[0], tc[0], tc[1], tc[1], tc[2], tc[2])
else:
self.mask = None
elif hasattr(self.mask,'rgb'):
_ = self.mask.rgb()
self.mask = _[0],_[0],_[1],_[1],_[2],_[2]
def loadImageFromSRC(self, im):
"Extracts the stream, width and height"
fp = im.jpeg_fh()
if fp:
self.loadImageFromJPEG(fp)
else:
zlib = import_zlib()
if not zlib: return
self.width, self.height = im.getSize()
raw = im.getRGBData()
#assert len(raw) == self.width*self.height, "Wrong amount of data for image expected %sx%s=%s got %s" % (self.width,self.height,self.width*self.height,len(raw))
self.streamContent = zlib.compress(raw)
if rl_config.useA85:
self.streamContent = asciiBase85Encode(self.streamContent)
self._filters = 'ASCII85Decode','FlateDecode' #'A85','Fl'
else:
self._filters = 'FlateDecode', #'Fl'
self.colorSpace= _mode2CS[im.mode]
self.bitsPerComponent = 8
self._checkTransparency(im)
def format(self, document):
S = PDFStream(content = self.streamContent)
dict = S.dictionary
dict["Type"] = PDFName("XObject")
dict["Subtype"] = PDFName("Image")
dict["Width"] = self.width
dict["Height"] = self.height
dict["BitsPerComponent"] = self.bitsPerComponent
dict["ColorSpace"] = PDFName(self.colorSpace)
if self.colorSpace=='DeviceCMYK' and getattr(self,'_dotrans',0):
dict["Decode"] = PDFArray([1,0,1,0,1,0,1,0])
elif getattr(self,'_decode',None):
dict["Decode"] = PDFArray(self._decode)
dict["Filter"] = PDFArray(map(PDFName,self._filters))
dict["Length"] = len(self.streamContent)
if self.mask: dict["Mask"] = PDFArray(self.mask)
if getattr(self,'smask',None): dict["SMask"] = self.smask
return S.format(document)
class PDFSeparationCMYKColor:
def __init__(self, cmyk):
from reportlab.lib.colors import CMYKColor
if not isinstance(cmyk,CMYKColor):
raise ValueError('%s needs a CMYKColor argument' % self.__class__.__name__)
elif not cmyk.spotName:
raise ValueError('%s needs a CMYKColor argument with a spotName' % self.__class__.__name__)
self.cmyk = cmyk
def _makeFuncPS(self):
'''create the postscript code for the tint transfer function
effectively this is tint*c, tint*y, ... tint*k'''
R = [].append
for i,v in enumerate(self.cmyk.cmyk()):
v=float(v)
if i==3:
if v==0.0:
R('pop')
R('0.0')
else:
R(str(v))
R('mul')
else:
if v==0:
R('0.0')
else:
R('dup')
R(str(v))
R('mul')
R('exch')
return '{%s}' % (' '.join(R.__self__))
def value(self):
return PDFArrayCompact((
PDFName('Separation'),
PDFName(self.cmyk.spotName),
PDFName('DeviceCMYK'),
PDFStream(
dictionary=PDFDictionary(dict(
FunctionType=4,
Domain=PDFArrayCompact((0,1)),
Range=PDFArrayCompact((0,1,0,1,0,1,0,1))
)),
content=self._makeFuncPS(),
filters=None,#[PDFBase85Encode, PDFZCompress],
)
))
class PDFFunction(PDFObject):
"""superclass for all function types."""
defaults = []
required = ("FunctionType", "Domain")
permitted = required+("Range",)
def FunctionDict(self, **kw):
d = {}
for (name,val) in self.defaults:
d[name] = val
d.update(kw)
for name in self.required:
if name not in d:
raise ValueError("keyword argument %s missing" % name)
permitted = self.permitted
for name in d.keys():
if name not in permitted:
raise ValueError("bad annotation dictionary name %s" % name)
return PDFDictionary(d)
def Dict(self, document):
raise ValueError("Dict undefined for virtual superclass PDFShading, must overload")
# but usually
#return self.FunctionDict(self, ...)
def format(self, document):
D = self.Dict(document)
return D.format(document)
class PDFExponentialFunction(PDFFunction):
defaults = PDFFunction.defaults + [("Domain", PDFArrayCompact((0.0, 1.0)))]
required = PDFFunction.required + ("N",)
permitted = PDFFunction.permitted + ("C0", "C1", "N")
def __init__(self, C0, C1, N, **kw):
self.C0 = C0
self.C1 = C1
self.N = N
self.otherkw = kw
def Dict(self, document):
d = {}
d.update(self.otherkw)
d["FunctionType"] = 2
d["C0"] = PDFArrayCompact(self.C0)
d["C1"] = PDFArrayCompact(self.C1)
d["N"] = self.N
return self.FunctionDict(**d)
class PDFStitchingFunction(PDFFunction):
required = PDFFunction.required + ("Functions", "Bounds", "Encode")
permitted = PDFFunction.permitted + ("Functions", "Bounds", "Encode")
def __init__(self, Functions, Bounds, Encode, **kw):
self.Functions = Functions
self.Bounds = Bounds
self.Encode = Encode
self.otherkw = kw
def Dict(self, document):
d = {}
d.update(self.otherkw)
d["FunctionType"] = 3
d["Functions"] = PDFArray([document.Reference(x) for x in self.Functions])
d["Bounds"] = PDFArray(self.Bounds)
d["Encode"] = PDFArray(self.Encode)
return self.FunctionDict(**d)
class PDFShading(PDFObject):
"""superclass for all shading types."""
required = ("ShadingType", "ColorSpace")
permitted = required+("Background", "BBox", "AntiAlias")
def ShadingDict(self, **kw):
d = {}
d.update(kw)
for name in self.required:
if name not in d:
raise ValueError("keyword argument %s missing" % name)
permitted = self.permitted
for name in d.keys():
if name not in permitted:
raise ValueError("bad annotation dictionary name %s" % name)
return PDFDictionary(d)
def Dict(self, document):
raise ValueError("Dict undefined for virtual superclass PDFShading, must overload")
# but usually
#return self.ShadingDict(self, ...)
def format(self, document):
D = self.Dict(document)
return D.format(document)
class PDFFunctionShading(PDFShading):
required = PDFShading.required + ("Function",)
permitted = PDFShading.permitted + ("Domain", "Matrix", "Function")
def __init__(self, Function, ColorSpace, **kw):
self.Function = Function
self.ColorSpace = ColorSpace
self.otherkw = kw
def Dict(self, document):
d = {}
d.update(self.otherkw)
d["ShadingType"] = 1
d["ColorSpace"] = PDFName(self.ColorSpace)
d["Function"] = document.Reference(self.Function)
return self.ShadingDict(**d)
class PDFAxialShading(PDFShading):
required = PDFShading.required + ("Coords", "Function")
permitted = PDFShading.permitted + (
"Coords", "Domain", "Function", "Extend")
def __init__(self, x0, y0, x1, y1, Function, ColorSpace, **kw):
self.Coords = (x0, y0, x1, y1)
self.Function = Function
self.ColorSpace = ColorSpace
self.otherkw = kw
def Dict(self, document):
d = {}
d.update(self.otherkw)
d["ShadingType"] = 2
d["ColorSpace"] = PDFName(self.ColorSpace)
d["Coords"] = PDFArrayCompact(self.Coords)
d["Function"] = document.Reference(self.Function)
return self.ShadingDict(**d)
class PDFRadialShading(PDFShading):
required = PDFShading.required + ("Coords", "Function")
permitted = PDFShading.permitted + (
"Coords", "Domain", "Function", "Extend")
def __init__(self, x0, y0, r0, x1, y1, r1, Function, ColorSpace, **kw):
self.Coords = (x0, y0, r0, x1, y1, r1)
self.Function = Function
self.ColorSpace = ColorSpace
self.otherkw = kw
def Dict(self, document):
d = {}
d.update(self.otherkw)
d["ShadingType"] = 3
d["ColorSpace"] = PDFName(self.ColorSpace)
d["Coords"] = PDFArrayCompact(self.Coords)
d["Function"] = document.Reference(self.Function)
return self.ShadingDict(**d)
if __name__=="__main__":
print("There is no script interpretation for pdfdoc.")
|