Initial commit

This commit is contained in:
Alex committed 2026-11-02 22:54:14 +08:00
commit 57fc3525eb
7311 files changed
+1291398

No files matched your search

@@ -0,0 +1,161 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__="""
Module to analyze Python source code; for syntax coloring tools.
Interface::
tags = fontify(pytext, searchfrom, searchto)
- The 'pytext' argument is a string containing Python source code.
- The (optional) arguments 'searchfrom' and 'searchto' may contain a slice in pytext.
- The returned value is a list of tuples, formatted like this::
[('keyword', 0, 6, None), ('keyword', 11, 17, None), ('comment', 23, 53, None), etc. ]
- The tuple contents are always like this::
(tag, startindex, endindex, sublist)
- tag is one of 'keyword', 'string', 'comment' or 'identifier'
- sublist is not used, hence always None.
"""
# Based on FontText.py by Mitchell S. Chapman,
# which was modified by Zachary Roadhouse,
# then un-Tk'd by Just van Rossum.
# Many thanks for regular expression debugging & authoring are due to:
# Tim (the-incredib-ly y'rs) Peters and Cristian Tismer
# So, who owns the copyright? ;-) How about this:
# Copyright 1996-2001:
# Mitchell S. Chapman,
# Zachary Roadhouse,
# Tim Peters,
# Just van Rossum
__version__ = "0.4"
import re
# First a little helper, since I don't like to repeat things. (Tismer speaking)
def replace(src, sep, rep):
return rep.join(src.split(sep))
# This list of keywords is taken from ref/node13.html of the
# Python 1.3 HTML documentation. ("access" is intentionally omitted.)
keywordsList = [
"as", "assert", "exec",
"del", "from", "lambda", "return",
"and", "elif", "global", "not", "try",
"break", "else", "if", "or", "while",
"class", "except", "import", "pass",
"continue", "finally", "in", "print",
"def", "for", "is", "raise", "yield",
"with"]
# Build up a regular expression which will match anything
# interesting, including multi-line triple-quoted strings.
commentPat = r"#[^\n]*"
pat = r"q[^\\q\n]*(\\[\000-\377][^\\q\n]*)*q"
quotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"')
# Way to go, Tim!
pat = r"""
qqq
[^\\q]*
(
( \\[\000-\377]
| q
( \\[\000-\377]
| [^\q]
| q
( \\[\000-\377]
| [^\\q]
)
)
)
[^\\q]*
)*
qqq
"""
pat = ''.join(pat.split()) # get rid of whitespace
tripleQuotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"')
# Build up a regular expression which matches all and only
# Python keywords. This will let us skip the uninteresting
# identifier references.
# nonKeyPat identifies characters which may legally precede
# a keyword pattern.
nonKeyPat = r"(^|[^a-zA-Z0-9_.\"'])"
keyPat = nonKeyPat + "(" + "|".join(keywordsList) + ")" + nonKeyPat
matchPat = commentPat + "|" + keyPat + "|" + tripleQuotePat + "|" + quotePat
matchRE = re.compile(matchPat)
idKeyPat = "[ \t]*[A-Za-z_][A-Za-z_0-9.]*" # Ident w. leading whitespace.
idRE = re.compile(idKeyPat)
def fontify(pytext, searchfrom = 0, searchto = None):
if searchto is None:
searchto = len(pytext)
# Cache a few attributes for quicker reference.
search = matchRE.search
idSearch = idRE.search
tags = []
tags_append = tags.append
commentTag = 'comment'
stringTag = 'string'
keywordTag = 'keyword'
identifierTag = 'identifier'
start = 0
end = searchfrom
while 1:
m = search(pytext, end)
if m is None:
break # EXIT LOOP
start = m.start()
if start >= searchto:
break # EXIT LOOP
match = m.group(0)
end = start + len(match)
c = match[0]
if c not in "#'\"":
# Must have matched a keyword.
if start != searchfrom:
# there's still a redundant char before and after it, strip!
match = match[1:-1]
start = start + 1
else:
# this is the first keyword in the text.
# Only a space at the end.
match = match[:-1]
end = end - 1
tags_append((keywordTag, start, end, None))
# If this was a defining keyword, look ahead to the
# following identifier.
if match in ["def", "class"]:
m = idSearch(pytext, end)
if m is not None:
start = m.start()
if start == end:
match = m.group(0)
end = start + len(match)
tags_append((identifierTag, start, end, None))
elif c == "#":
tags_append((commentTag, start, end, None))
else:
tags_append((stringTag, start, end, None))
return tags
def test(path):
f = open(path)
text = f.read()
f.close()
tags = fontify(text)
for tag, start, end, sublist in tags:
print(tag, repr(text[start:end]))
@@ -0,0 +1,7 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/__init__.py
__version__='3.3.0'
import os
RL_DEBUG = 'RL_DEBUG' in os.environ
@@ -0,0 +1,36 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/abag.py
__version__='3.3.0'
__doc__='''Data structure to hold a collection of attributes, used by styles.'''
class ABag:
"""
'Attribute Bag' - a trivial BAG class for holding attributes.
This predates modern Python. Doing this again, we'd use a subclass
of dict.
You may initialize with keyword arguments.
a = ABag(k0=v0,....,kx=vx,....) ==> getattr(a,'kx')==vx
c = a.clone(ak0=av0,.....) copy with optional additional attributes.
"""
def __init__(self,**attr):
self.__dict__.update(attr)
def clone(self,**attr):
n = self.__class__(**self.__dict__)
if attr: n.__dict__.update(attr)
return n
def __repr__(self):
D = self.__dict__
K = list(D.keys())
K.sort()
return '%s(%s)' % (self.__class__.__name__,', '.join(['%s=%r' % (k,D[k]) for k in K]))
if __name__=="__main__":
AB = ABag(a=1, c="hello")
CD = AB.clone()
print(AB)
print(CD)
@@ -0,0 +1,214 @@
#copyright ReportLab Europe Limited. 2000-2016
#see license.txt for license details
'''
Arciv Stream ciphering
'''
__all__='''ArcIV encode decode'''.split()
__version__="1.0"
from reportlab.lib.utils import isUnicode
class ArcIV:
'''
performs 'ArcIV' Stream Encryption of S using key
Based on what is widely thought to be RSA's ArcIV algorithm.
It produces output streams that are identical.
NB there is no separate decoder arciv(arciv(s,key),key) == s
'''
def __init__(self,key):
self._key = key
self.reset()
def reset(self):
'''restore the cipher to it's start state'''
#Initialize private key, k With the values of the key mod 256.
#and sbox With numbers 0 - 255. Then compute sbox
key = self._key
if isUnicode(key): key = key.encode('utf8')
sbox = list(range(256))
k = list(range(256))
lk = len(key)
for i in sbox:
k[i] = key[i % lk] % 256
#Re-order sbox using the private key, k.
#Iterating each element of sbox re-calculate the counter j
#Then interchange the elements sbox[a] & sbox[b]
j = 0
for i in range(256):
j = (j+sbox[i]+k[i]) % 256
sbox[i], sbox[j] = sbox[j], sbox[i]
self._sbox, self._i, self._j = sbox, 0, 0
def _encode(self, B):
'''
return the list of encoded bytes of B, B might be a string or a
list of integers between 0 <= i <= 255
'''
sbox, i, j = self._sbox, self._i, self._j
C = list(B.encode('utf8')) if isinstance(B,str) else (list(B) if isinstance(B,bytes) else B[:])
n = len(C)
p = 0
while p<n:
#update the variables i, j.
self._i = i = (i + 1) % 256
self._j = j = (j + sbox[i]) % 256
#swap sbox[i] and sbox[j]
sbox[i], sbox[j] = sbox[j], sbox[i]
#overwrite the plaintext with the ciphered byte
C[p] = C[p] ^ sbox[(sbox[i] + sbox[j]) % 256]
p += 1
return C
def encode(self,S):
'ArcIV encode string S'
return bytes(self._encode(S))
_TESTS=[{
'key': b"\x01\x23\x45\x67\x89\xab\xcd\xef",
'input': b"\x01\x23\x45\x67\x89\xab\xcd\xef",
'output': b"\x75\xb7\x87\x80\x99\xe0\xc5\x96",
},
{
'key': b"\x01\x23\x45\x67\x89\xab\xcd\xef",
'input': b"\x00\x00\x00\x00\x00\x00\x00\x00",
'output': b"\x74\x94\xc2\xe7\x10\x4b\x08\x79",
},
{
'key': b"\x00\x00\x00\x00\x00\x00\x00\x00",
'input': b"\x00\x00\x00\x00\x00\x00\x00\x00",
'output': b"\xde\x18\x89\x41\xa3\x37\x5d\x3a",
},
{
'key': b"\xef\x01\x23\x45",
'input': b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
'output': b"\xd6\xa1\x41\xa7\xec\x3c\x38\xdf\xbd\x61",
},
{
'key': b"\x01\x23\x45\x67\x89\xab\xcd\xef",
'input': b"\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\
\x01",
'output': b"\x75\x95\xc3\xe6\x11\x4a\x09\x78\x0c\x4a\xd4\
\x52\x33\x8e\x1f\xfd\x9a\x1b\xe9\x49\x8f\
\x81\x3d\x76\x53\x34\x49\xb6\x77\x8d\xca\
\xd8\xc7\x8a\x8d\x2b\xa9\xac\x66\x08\x5d\
\x0e\x53\xd5\x9c\x26\xc2\xd1\xc4\x90\xc1\
\xeb\xbe\x0c\xe6\x6d\x1b\x6b\x1b\x13\xb6\
\xb9\x19\xb8\x47\xc2\x5a\x91\x44\x7a\x95\
\xe7\x5e\x4e\xf1\x67\x79\xcd\xe8\xbf\x0a\
\x95\x85\x0e\x32\xaf\x96\x89\x44\x4f\xd3\
\x77\x10\x8f\x98\xfd\xcb\xd4\xe7\x26\x56\
\x75\x00\x99\x0b\xcc\x7e\x0c\xa3\xc4\xaa\
\xa3\x04\xa3\x87\xd2\x0f\x3b\x8f\xbb\xcd\
\x42\xa1\xbd\x31\x1d\x7a\x43\x03\xdd\xa5\
\xab\x07\x88\x96\xae\x80\xc1\x8b\x0a\xf6\
\x6d\xff\x31\x96\x16\xeb\x78\x4e\x49\x5a\
\xd2\xce\x90\xd7\xf7\x72\xa8\x17\x47\xb6\
\x5f\x62\x09\x3b\x1e\x0d\xb9\xe5\xba\x53\
\x2f\xaf\xec\x47\x50\x83\x23\xe6\x71\x32\
\x7d\xf9\x44\x44\x32\xcb\x73\x67\xce\xc8\
\x2f\x5d\x44\xc0\xd0\x0b\x67\xd6\x50\xa0\
\x75\xcd\x4b\x70\xde\xdd\x77\xeb\x9b\x10\
\x23\x1b\x6b\x5b\x74\x13\x47\x39\x6d\x62\
\x89\x74\x21\xd4\x3d\xf9\xb4\x2e\x44\x6e\
\x35\x8e\x9c\x11\xa9\xb2\x18\x4e\xcb\xef\
\x0c\xd8\xe7\xa8\x77\xef\x96\x8f\x13\x90\
\xec\x9b\x3d\x35\xa5\x58\x5c\xb0\x09\x29\
\x0e\x2f\xcd\xe7\xb5\xec\x66\xd9\x08\x4b\
\xe4\x40\x55\xa6\x19\xd9\xdd\x7f\xc3\x16\
\x6f\x94\x87\xf7\xcb\x27\x29\x12\x42\x64\
\x45\x99\x85\x14\xc1\x5d\x53\xa1\x8c\x86\
\x4c\xe3\xa2\xb7\x55\x57\x93\x98\x81\x26\
\x52\x0e\xac\xf2\xe3\x06\x6e\x23\x0c\x91\
\xbe\xe4\xdd\x53\x04\xf5\xfd\x04\x05\xb3\
\x5b\xd9\x9c\x73\x13\x5d\x3d\x9b\xc3\x35\
\xee\x04\x9e\xf6\x9b\x38\x67\xbf\x2d\x7b\
\xd1\xea\xa5\x95\xd8\xbf\xc0\x06\x6f\xf8\
\xd3\x15\x09\xeb\x0c\x6c\xaa\x00\x6c\x80\
\x7a\x62\x3e\xf8\x4c\x3d\x33\xc1\x95\xd2\
\x3e\xe3\x20\xc4\x0d\xe0\x55\x81\x57\xc8\
\x22\xd4\xb8\xc5\x69\xd8\x49\xae\xd5\x9d\
\x4e\x0f\xd7\xf3\x79\x58\x6b\x4b\x7f\xf6\
\x84\xed\x6a\x18\x9f\x74\x86\xd4\x9b\x9c\
\x4b\xad\x9b\xa2\x4b\x96\xab\xf9\x24\x37\
\x2c\x8a\x8f\xff\xb1\x0d\x55\x35\x49\x00\
\xa7\x7a\x3d\xb5\xf2\x05\xe1\xb9\x9f\xcd\
\x86\x60\x86\x3a\x15\x9a\xd4\xab\xe4\x0f\
\xa4\x89\x34\x16\x3d\xdd\xe5\x42\xa6\x58\
\x55\x40\xfd\x68\x3c\xbf\xd8\xc0\x0f\x12\
\x12\x9a\x28\x4d\xea\xcc\x4c\xde\xfe\x58\
\xbe\x71\x37\x54\x1c\x04\x71\x26\xc8\xd4\
\x9e\x27\x55\xab\x18\x1a\xb7\xe9\x40\xb0\
\xc0",
},
]
def encode(text, key):
"One-line shortcut for making an encoder object"
return ArcIV(key).encode(text)
def decode(text, key):
"One-line shortcut for decoding"
# yes, encode and decode are symmetric - see docstring
return ArcIV(key).encode(text)
if __name__=='__main__':
i = 0
for t in _TESTS:
o = ArcIV(t['key']).encode(t['input'])
o = ArcIV(t['key']).encode(t['output'])
i += 1
@@ -0,0 +1,189 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/attrmap.py
__version__='3.3.0'
__doc__='''Framework for objects whose assignments are checked. Used by graphics.
We developed reportlab/graphics prior to Python 2 and metaclasses. For the
graphics, we wanted to be able to declare the attributes of a class, check
them on assignment, and convert from string arguments. Examples of
attrmap-based objects can be found in reportlab/graphics/shapes. It lets
us defined structures like the one below, which are seen more modern form in
Django models and other frameworks.
We'll probably replace this one day soon, hopefully with no impact on client
code.
class Rect(SolidShape):
"""Rectangle, possibly with rounded corners."""
_attrMap = AttrMap(BASE=SolidShape,
x = AttrMapValue(isNumber),
y = AttrMapValue(isNumber),
width = AttrMapValue(isNumber),
height = AttrMapValue(isNumber),
rx = AttrMapValue(isNumber),
ry = AttrMapValue(isNumber),
)
'''
from reportlab.lib.validators import isAnything, DerivedValue
from reportlab.lib.utils import isSeq
from reportlab import rl_config
class CallableValue:
'''a class to allow callable initial values'''
def __init__(self,func,*args,**kw):
#assert iscallable(func)
self.func = func
self.args = args
self.kw = kw
def __call__(self):
return self.func(*self.args,**self.kw)
class AttrMapValue:
'''Simple multi-value holder for attribute maps'''
def __init__(self,validate=None,desc=None,initial=None, advancedUsage=0, **kw):
self.validate = validate or isAnything
self.desc = desc
self._initial = initial
self._advancedUsage = advancedUsage
for k,v in kw.items():
setattr(self,k,v)
def __getattr__(self,name):
#hack to allow callable initial values
if name=='initial':
if isinstance(self._initial,CallableValue): return self._initial()
return self._initial
elif name=='hidden':
return 0
raise AttributeError(name)
def __repr__(self):
return 'AttrMapValue(%s)' % ', '.join(['%s=%r' % i for i in self.__dict__.items()])
class AttrMap(dict):
def __init__(self,BASE=None,UNWANTED=[],**kw):
data = {}
if BASE:
if isinstance(BASE,AttrMap):
data = BASE
else:
if not isSeq(BASE): BASE = (BASE,)
for B in BASE:
am = getattr(B,'_attrMap',self)
if am is not self:
if am: data.update(am)
else:
raise ValueError('BASE=%s has wrong kind of value' % ascii(B))
dict.__init__(self,data)
self.remove(UNWANTED)
self.update(kw)
def remove(self,unwanted):
for k in unwanted:
try:
del self[k]
except KeyError:
pass
def clone(self,UNWANTED=[],**kw):
c = AttrMap(BASE=self,UNWANTED=UNWANTED)
c.update(kw)
return c
def validateSetattr(obj,name,value):
'''validate setattr(obj,name,value)'''
if rl_config.shapeChecking:
aMap = obj._attrMap
if aMap and name[0]!= '_':
#we always allow the inherited values; they cannot
#be checked until draw time.
if isinstance(value, DerivedValue):
#let it through
pass
elif name in aMap:
validate = aMap[name].validate
try:
r = validate(value)
except Exception as e:
raise e.__class__(f"{obj.__class__.__name__}.{name} {validate}({value!r})") from e
else:
if not r:
raise AttributeError(f"Illegal assignment of {value!r} to {name} in class {obj.__class__.__name__}")
else:
prop = getattr(obj.__class__,name,None)
if isinstance(prop,property):
fset = getattr(prop,'fset',None)
if fset:
fset(obj,value)
return
else:
raise AttributeError(f"{obj.__class__.__name__}.{name} has no setter")
else:
raise AttributeError("Illegal attribute '%s' in class %s" % (name, obj.__class__.__name__))
prop = getattr(obj.__class__,name,None)
if isinstance(prop,property):
fset = getattr(prop,'fset',None)
if fset:
fset(obj,value)
else:
raise AttributeError(f"{obj.__class__.__name__}.{name} has no setter")
elif name=='__dict__':
obj.__dict__.clear()
obj.__dict__.update(value)
else:
obj.__dict__[name] = value
def _privateAttrMap(obj,ret=0):
'''clone obj._attrMap if required'''
A = obj._attrMap
oA = getattr(obj.__class__,'_attrMap',None)
if ret:
if oA is A:
return A.clone(), oA
else:
return A, None
else:
if oA is A:
obj._attrMap = A.clone()
def _findObjectAndAttr(src, P):
'''Locate the object src.P for P a string, return parent and name of attribute
'''
P = P.split('.')
if len(P) == 0:
return None, None
else:
for p in P[0:-1]:
src = getattr(src, p)
return src, P[-1]
def hook__setattr__(obj):
if not hasattr(obj,'__attrproxy__'):
C = obj.__class__
import new
obj.__class__=new.classobj(C.__name__,(C,)+C.__bases__,
{'__attrproxy__':[],
'__setattr__':lambda self,k,v,osa=getattr(obj,'__setattr__',None),hook=hook: hook(self,k,v,osa)})
def addProxyAttribute(src,name,validate=None,desc=None,initial=None,dst=None):
'''
Add a proxy attribute 'name' to src with targets dst
'''
#sanity
assert hasattr(src,'_attrMap'), 'src object has no _attrMap'
A, oA = _privateAttrMap(src,1)
if not isSeq(dst): dst = dst,
D = []
DV = []
for d in dst:
if isSeq(d):
d, e = d[0], d[1:]
obj, attr = _findObjectAndAttr(src,d)
if obj:
dA = getattr(obj,'_attrMap',None)
@@ -0,0 +1,84 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.4.34'
__doc__='''Utility functions to position and resize boxes within boxes'''
def rectCorner(x, y, width, height, anchor='sw', dims=False):
'''given rectangle controlled by x,y width and height return
the corner corresponding to the anchor'''
if anchor not in ('nw','w','sw'):
if anchor in ('n','c','s'):
x += width/2.
else:
x += width
if anchor not in ('sw','s','se'):
if anchor in ('w','c','e'):
y += height/2.
else:
y += height
return (x,y,width,height) if dims else (x,y)
def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight,anchorAtXY=False):
"""This function helps position an image within a box.
It first normalizes for two cases:
- if the width is None, it assumes imWidth
- ditto for height
- if width or height is negative, it adjusts x or y and makes them positive
Given
(a) the enclosing box (defined by x,y,width,height where x,y is the \
lower left corner) which you wish to position the image in, and
(b) the image size (imWidth, imHeight), and
(c) the 'anchor point' as a point of the compass - n,s,e,w,ne,se etc \
and c for centre,
this should return the position at which the image should be drawn,
as well as a scale factor indicating what scaling has happened.
It returns the parameters which would be used to draw the image
without any adjustments:
x,y, width, height, scale
used in canvas.drawImage and drawInlineImage
"""
scale = 1.0
if width is None:
width = imWidth
if height is None:
height = imHeight
if width<0:
width = -width
x -= width
if height<0:
height = -height
y -= height
if preserve:
imWidth = abs(imWidth)
imHeight = abs(imHeight)
scale = min(width/float(imWidth),height/float(imHeight))
owidth = width
oheight = height
width = scale*imWidth-1e-8
height = scale*imHeight-1e-8
if not anchorAtXY:
# if anchor not in ('nw','w','sw'):
# dx = owidth-width
# if anchor in ('n','c','s'):
# x += dx/2.
# else:
# x += dx
# if anchor not in ('sw','s','se'):
# dy = oheight-height
# if anchor in ('w','c','e'):
# y += dy/2.
# else:
# y += dy
x, y = rectCorner(x,y,owidth-width,oheight-height,anchor)
if anchorAtXY:
if anchor not in ('sw','s','se'):
y -= height/2. if anchor in ('e','c','w') else height
if anchor not in ('nw','w','sw'):
x -= width/2. if anchor in ('n','c','s') else width
return x,y, width, height, scale
@@ -0,0 +1,363 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/codecharts.py
#$Header $
__version__='3.3.0'
__doc__="""Routines to print code page (character set) drawings. Predates unicode.
To be sure we can accurately represent characters in various encodings
and fonts, we need some routines to display all those characters.
These are defined herein. The idea is to include flowable, drawable
and graphic objects for single and multi-byte fonts. """
import codecs
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Flowable
from reportlab.pdfbase import pdfmetrics, cidfonts
from reportlab.graphics.shapes import Group, String, Rect
from reportlab.graphics.widgetbase import Widget
from reportlab.lib import colors
from reportlab.lib.utils import int2Byte
adobe2codec = {
'WinAnsiEncoding':'winansi',
'MacRomanEncoding':'macroman',
'MacExpert':'macexpert',
'PDFDoc':'pdfdoc',
}
class CodeChartBase(Flowable):
"""Basic bits of drawing furniture used by
single and multi-byte versions: ability to put letters
into boxes."""
def calcLayout(self):
"Work out x and y positions for drawing"
rows = self.codePoints * 1.0 / self.charsPerRow
if rows == int(rows):
self.rows = int(rows)
else:
self.rows = int(rows) + 1
# size allows for a gray column of labels
self.width = self.boxSize * (1+self.charsPerRow)
self.height = self.boxSize * (1+self.rows)
#handy lists
self.ylist = []
for row in range(self.rows + 2):
self.ylist.append(row * self.boxSize)
self.xlist = []
for col in range(self.charsPerRow + 2):
self.xlist.append(col * self.boxSize)
def formatByte(self, byt):
if self.hex:
return '%02X' % byt
else:
return '%d' % byt
def drawChars(self, charList):
"""Fills boxes in order. None means skip a box.
Empty boxes at end get filled with gray"""
extraNeeded = (self.rows * self.charsPerRow - len(charList))
for i in range(extraNeeded):
charList.append(None)
#charList.extend([None] * extraNeeded)
row = 0
col = 0
self.canv.setFont(self.fontName, self.boxSize * 0.75)
for ch in charList: # may be 2 bytes or 1
if ch is None:
self.canv.setFillGray(0.9)
self.canv.rect((1+col) * self.boxSize, (self.rows - row - 1) * self.boxSize,
self.boxSize, self.boxSize, stroke=0, fill=1)
self.canv.setFillGray(0.0)
else:
try:
self.canv.drawCentredString(
(col+1.5) * self.boxSize,
(self.rows - row - 0.875) * self.boxSize,
ch,
)
except:
self.canv.setFillGray(0.9)
self.canv.rect((1+col) * self.boxSize, (self.rows - row - 1) * self.boxSize,
self.boxSize, self.boxSize, stroke=0, fill=1)
self.canv.drawCentredString(
(col+1.5) * self.boxSize,
(self.rows - row - 0.875) * self.boxSize,
'?',
)
self.canv.setFillGray(0.0)
col = col + 1
if col == self.charsPerRow:
row = row + 1
col = 0
def drawLabels(self, topLeft = ''):
"""Writes little labels in the top row and first column"""
self.canv.setFillGray(0.8)
self.canv.rect(0, self.ylist[-2], self.width, self.boxSize, fill=1, stroke=0)
self.canv.rect(0, 0, self.boxSize, self.ylist[-2], fill=1, stroke=0)
self.canv.setFillGray(0.0)
#label each row and column
self.canv.setFont('Helvetica-Oblique',0.375 * self.boxSize)
byt = 0
for row in range(self.rows):
if self.rowLabels:
label = self.rowLabels[row]
else: # format start bytes as hex or decimal
label = self.formatByte(row * self.charsPerRow)
self.canv.drawCentredString(0.5 * self.boxSize,
(self.rows - row - 0.75) * self.boxSize,
label
)
for col in range(self.charsPerRow):
self.canv.drawCentredString((col + 1.5) * self.boxSize,
(self.rows + 0.25) * self.boxSize,
self.formatByte(col)
)
if topLeft:
self.canv.setFont('Helvetica-BoldOblique',0.5 * self.boxSize)
self.canv.drawCentredString(0.5 * self.boxSize,
(self.rows + 0.25) * self.boxSize,
topLeft
)
class SingleByteEncodingChart(CodeChartBase):
def __init__(self, faceName='Helvetica', encodingName='WinAnsiEncoding',
charsPerRow=16, boxSize=14, hex=1):
self.codePoints = 256
self.faceName = faceName
self.encodingName = encodingName
self.fontName = self.faceName + '-' + self.encodingName
self.charsPerRow = charsPerRow
self.boxSize = boxSize
self.hex = hex
self.rowLabels = None
pdfmetrics.registerFont(pdfmetrics.Font(self.fontName,
self.faceName,
self.encodingName)
)
self.calcLayout()
def draw(self):
self.drawLabels()
charList = [None] * 32 + list(map(int2Byte, list(range(32, 256))))
#we need to convert these to Unicode, since ReportLab
#2.0 can only draw in Unicode.
encName = self.encodingName
#apply some common translations
encName = adobe2codec.get(encName, encName)
decoder = codecs.lookup(encName)[1]
def decodeFunc(txt):
if txt is None:
return None
else:
return decoder(txt, errors='replace')[0]
charList = [decodeFunc(ch) for ch in charList]
self.drawChars(charList)
self.canv.grid(self.xlist, self.ylist)
class KutenRowCodeChart(CodeChartBase):
"""Formats one 'row' of the 94x94 space used in many Asian encodings.aliases
These deliberately resemble the code charts in Ken Lunde's "Understanding
CJKV Information Processing", to enable manual checking. Due to the large
numbers of characters, we don't try to make one graphic with 10,000 characters,
but rather output a sequence of these."""
#would be cleaner if both shared one base class whose job
#was to draw the boxes, but never mind...
def __init__(self, row, faceName, encodingName):
self.row = row
self.codePoints = 94
self.boxSize = 18
self.charsPerRow = 20
self.rows = 5
self.rowLabels = ['00','20','40','60','80']
self.hex = 0
self.faceName = faceName
self.encodingName = encodingName
try:
# the dependent files might not be available
font = cidfonts.CIDFont(self.faceName, self.encodingName)
pdfmetrics.registerFont(font)
except:
# fall back to English and at least show we can draw the boxes
self.faceName = 'Helvetica'
self.encodingName = 'WinAnsiEncoding'
self.fontName = self.faceName + '-' + self.encodingName
self.calcLayout()
def makeRow(self, row):
"""Works out the character values for this kuten row"""
cells = []
if self.encodingName.find('EUC') > -1:
# it is an EUC family encoding.
for col in range(1, 95):
ch = int2Byte(row + 160) + int2Byte(col+160)
cells.append(ch)
## elif self.encodingName.find('GB') > -1:
## # it is an EUC family encoding.
## for col in range(1, 95):
## ch = int2Byte(row + 160) + int2Byte(col+160)
else:
cells.append([None] * 94)
return cells
def draw(self):
self.drawLabels(topLeft= 'R%d' % self.row)
# work out which characters we need for the row
#assert self.encodingName.find('EUC') > -1, 'Only handles EUC encoding today, you gave me %s!' % self.encodingName
# pad out by 1 to match Ken Lunde's tables
charList = [None] + self.makeRow(self.row)
self.drawChars(charList)
self.canv.grid(self.xlist, self.ylist)
class Big5CodeChart(CodeChartBase):
"""Formats one 'row' of the 94x160 space used in Big 5
These deliberately resemble the code charts in Ken Lunde's "Understanding
CJKV Information Processing", to enable manual checking."""
def __init__(self, row, faceName, encodingName):
self.row = row
self.codePoints = 160
self.boxSize = 18
self.charsPerRow = 16
self.rows = 10
self.hex = 1
self.faceName = faceName
self.encodingName = encodingName
self.rowLabels = ['4','5','6','7','A','B','C','D','E','F']
try:
# the dependent files might not be available
font = cidfonts.CIDFont(self.faceName, self.encodingName)
pdfmetrics.registerFont(font)
except:
# fall back to English and at least show we can draw the boxes
self.faceName = 'Helvetica'
self.encodingName = 'WinAnsiEncoding'
self.fontName = self.faceName + '-' + self.encodingName
self.calcLayout()
def makeRow(self, row):
"""Works out the character values for this Big5 row.
Rows start at 0xA1"""
cells = []
if self.encodingName.find('B5') > -1:
# big 5, different row size
for y in [4,5,6,7,10,11,12,13,14,15]:
for x in range(16):
col = y*16+x
ch = int2Byte(row) + int2Byte(col)
cells.append(ch)
else:
cells.append([None] * 160)
return cells
def draw(self):
self.drawLabels(topLeft='%02X' % self.row)
charList = self.makeRow(self.row)
self.drawChars(charList)
self.canv.grid(self.xlist, self.ylist)
def hBoxText(msg, canvas, x, y, fontName):
"""Helper for stringwidth tests on Asian fonts.
Registers font if needed. Then draws the string,
and a box around it derived from the stringWidth function"""
canvas.saveState()
try:
font = pdfmetrics.getFont(fontName)
except KeyError:
font = cidfonts.UnicodeCIDFont(fontName)
pdfmetrics.registerFont(font)
canvas.setFillGray(0.8)
canvas.rect(x,y,pdfmetrics.stringWidth(msg, fontName, 16),16,stroke=0,fill=1)
canvas.setFillGray(0)
canvas.setFont(fontName, 16,16)
canvas.drawString(x,y,msg)
canvas.restoreState()
class CodeWidget(Widget):
"""Block showing all the characters"""
def __init__(self):
self.x = 0
self.y = 0
self.width = 160
self.height = 160
def draw(self):
dx = self.width / 16.0
dy = self.height / 16.0
g = Group()
g.add(Rect(self.x, self.y, self.width, self.height,
fillColor=None, strokeColor=colors.black))
for x in range(16):
for y in range(16):
charValue = y * 16 + x
if charValue > 32:
s = String(self.x + x * dx,
self.y + (self.height - y*dy), int2Byte(charValue))
g.add(s)
return g
def test():
c = Canvas('codecharts.pdf')
c.setFont('Helvetica-Bold', 24)
c.drawString(72, 750, 'Testing code page charts')
cc1 = SingleByteEncodingChart()
cc1.drawOn(c, 72, 500)
cc2 = SingleByteEncodingChart(charsPerRow=32)
cc2.drawOn(c, 72, 300)
cc3 = SingleByteEncodingChart(charsPerRow=25, hex=0)
cc3.drawOn(c, 72, 100)
## c.showPage()
##
## c.setFont('Helvetica-Bold', 24)
## c.drawString(72, 750, 'Multi-byte Kuten code chart examples')
## KutenRowCodeChart(1, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 600)
## KutenRowCodeChart(16, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 450)
## KutenRowCodeChart(84, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 300)
##
## c.showPage()
## c.setFont('Helvetica-Bold', 24)
## c.drawString(72, 750, 'Big5 Code Chart Examples')
## #Big5CodeChart(0xA1, 'MSungStd-Light-Acro','ETenms-B5-H').drawOn(c, 72, 500)
c.save()
print('saved codecharts.pdf')
if __name__=='__main__':
test()
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,481 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__="""Generate ReportLab logo in a variety of sizes and formats.
This module includes some reusable routines for ReportLab's
'Corporate Image' - the logo, standard page backdrops and
so on - you are advised to do the same for your own company!"""
from reportlab.lib.units import inch,cm
from reportlab.lib.validators import *
from reportlab.lib.attrmap import *
from reportlab.lib.formatters import DecimalFormatter
from reportlab.graphics.shapes import definePath, Group, Drawing, Rect, PolyLine, String
from reportlab.graphics.widgetbase import Widget
from reportlab.lib.colors import Color, black, white, ReportLabBlue
from reportlab.pdfbase.pdfmetrics import stringWidth
class RL_CorpLogo(Widget):
'''Dinu's fat letter logo as hacked into decent paths by Robin'''
_attrMap = AttrMap(
x = AttrMapValue(isNumber,'Logo x-coord'),
y = AttrMapValue(isNumber,'Logo y-coord'),
angle = AttrMapValue(isNumber,'Logo rotation'),
strokeColor = AttrMapValue(isColorOrNone, 'Logo lettering stroke color'),
fillColor = AttrMapValue(isColorOrNone, 'Logo lettering fill color'),
strokeWidth = AttrMapValue(isNumber,'Logo lettering stroke width'),
background = AttrMapValue(isColorOrNone,desc="Logo background color"),
border = AttrMapValue(isColorOrNone,desc="Logo border color"),
borderWidth = AttrMapValue(isNumber,desc="Logo border width (1)"),
shadow = AttrMapValue(isNumberOrNone,desc="None or fraction of background for shadowing" ),
width = AttrMapValue(isNumber, desc="width in points of the logo (default 129)"),
height = AttrMapValue(isNumber, desc="height in points of the logo (default 86)"),
skewX = AttrMapValue(isNumber, desc="x-skew of the logo (default 10)"),
skewY = AttrMapValue(isNumber, desc="y-skew of the logo (default 0)"),
showPage = AttrMapValue(EitherOr((isBoolean,SequenceOf(isBoolean,lo=2,hi=2))), desc="If true or (true(top),true(bottom)) show the page lines"),
xFlip = AttrMapValue(isBoolean, desc="If true do x reversal"),
yFlip = AttrMapValue(isBoolean, desc="If true do y reversal"),
oColors = AttrMapValue(NoneOr(EitherOr((isColor,SequenceOf(isColorOrNone,lo=2,hi=2)))),desc="None or fill/stroke colors for the o in ReportLab"),
pageColors = AttrMapValue(NoneOr(EitherOr((isColor,SequenceOf(isColorOrNone,lo=2,hi=2)))),desc="None or fill/stroke colors for the page outline"),
prec = AttrMapValue(NoneOr(isInt),desc="None or precision negative means strip excess"),
)
def __init__(self):
self.fillColor = white
self.strokeColor = None
self.strokeWidth = 0.1
self.background = ReportLabBlue
self.border = None
self.borderWidth = 1
self.shadow = 0.5
self.height = 86
self.width = 130
self.x = self.y = self.angle = self.skewY = self._dx = 0
self.skewX = 10
self._dy = 35.5
self.showPage = 1
self.oColors = None #ie use the default
self.pageColors = None #ie use the default
self.prec = None
def demo(self):
D = Drawing(self.width, self.height)
D.add(self)
return D
def _paintLogo(self, g, dx=0, dy=0, strokeColor=None, strokeWidth=0.1, fillColor=white, _ocolors=None, _pagecolors=None):
OP = [('moveTo' ,62.10648,6.51392 ), ('curveTo' ,62.10648,4.44205 ,61.47118,2.79288 ,60.2003,1.56631 ), ('curveTo' ,58.92971,0.33978 ,57.22626,-0.27348 ,55.08965,-0.27348 ), ('curveTo' ,52.99018,-0.27348 ,51.31914,0.35221 ,50.07595,1.60362 ), ('curveTo' ,48.8419,2.8633 ,48.22517,4.55394 ,48.22517,6.67551 ), ('curveTo' ,48.22517,8.79709 ,48.85575,10.50016 ,50.1175,11.78472 ), ('curveTo' ,51.36982,13.07755 ,53.03172,13.72396 ,55.1035,13.72396 ), ('curveTo' ,57.28608,13.72396 ,58.99866,13.08168 ,60.24185,11.79712 ), ('curveTo' ,61.48503,10.51259 ,62.10648,8.75154 ,62.10648,6.51392 ), 'closePath', ('moveTo' ,56.73358,6.67551 ), ('curveTo' ,56.73358,7.17276 ,56.69675,7.62236 ,56.62308,8.02428 ), ('curveTo' ,56.54942,8.42623 ,56.44334,8.77016 ,56.30544,9.05607 ), ('curveTo' ,56.16724,9.34198 ,56.00134,9.56369 ,55.80804,9.72113 ), ('curveTo' ,55.61474,9.8786 ,55.39817,9.95733 ,55.1589,9.95733 ), ('curveTo' ,54.68921,9.95733 ,54.31174,9.65898 ,54.02621,9.06229 ), ('curveTo' ,53.74068,8.54018 ,53.59807,7.75702 ,53.59807,6.71282 ), ('curveTo' ,53.59807,5.68515 ,53.74068,4.90202 ,54.02621,4.36332 ), ('curveTo' ,54.31174,3.76663 ,54.69392,3.46828 ,55.17275,3.46828 ), ('curveTo' ,55.62388,3.46828 ,55.99692,3.7625 ,56.29159,4.35088 ), ('curveTo' ,56.58625,5.0056 ,56.73358,5.78047 ,56.73358,6.67551 ), 'closePath']
P = [
('moveTo' ,15.7246,0 ), ('lineTo' ,9.49521,0 ), ('lineTo' ,6.64988,6.83711 ), ('curveTo' ,6.62224,6.95315 ,6.57391,7.10646 ,6.50485,7.29708 ), ('curveTo' ,6.43578,7.48767 ,6.35059,7.71559 ,6.24931,7.98079 ), ('lineTo' ,6.29074,6.71282 ), ('lineTo' ,6.29074,0 ), ('lineTo' ,0.55862,0 ), ('lineTo' ,0.55862,19.19365 ), ('lineTo' ,6.45649,19.19365 ), ('curveTo' ,9.05324,19.19365 ,10.99617,18.73371 ,12.28532,17.8138 ), ('curveTo' ,13.92439,16.63697 ,14.7439,14.96293 ,14.7439,12.79161 ), ('curveTo' ,14.7439,10.47114 ,13.64354,8.86755 ,11.44276,7.98079 ), 'closePath', ('moveTo' ,6.31838,10.30542 ), ('lineTo' ,6.70513,10.30542 ), ('curveTo' ,7.36812,10.30542 ,7.92062,10.53331 ,8.36261,10.98912 ), ('curveTo' ,8.80461,11.44491 ,9.0256,12.02504 ,9.0256,12.72947 ), ('curveTo' ,9.0256,14.16321 ,8.19227,14.88004 ,6.52556,14.88004 ), ('lineTo' ,6.31838,14.88004 ), 'closePath',
('moveTo' ,25.06173,4.54978 ), ('lineTo' ,30.47611,4.45033 ), ('curveTo' ,30.08951,2.88402 ,29.33668,1.70513 ,28.21787,0.91369 ), ('curveTo' ,27.09906,0.12223 ,25.63726,-0.27348 ,23.83245,-0.27348 ), ('curveTo' ,21.69611,-0.27348 ,20.02024,0.32322 ,18.80475,1.5166 ), ('curveTo' ,17.59846,2.72658 ,16.99531,4.37988 ,16.99531,6.47662 ), ('curveTo' ,16.99531,8.6065 ,17.64451,10.34269 ,18.94286,11.68527 ), ('curveTo' ,20.24124,13.03612 ,21.91711,13.71152 ,23.97056,13.71152 ), ('curveTo' ,26.01482,13.71152 ,27.64466,13.06096 ,28.86015,11.75985 ), ('curveTo' ,30.07566,10.45042 ,30.68326,8.71423 ,30.68326,6.5512 ), ('lineTo' ,30.65586,5.66859 ), ('lineTo' ,22.53407,5.66859 ), ('curveTo' ,22.59855,4.29287 ,23.03132,3.60503 ,23.83245,3.60503 ), ('curveTo' ,24.45861,3.60503 ,24.86837,3.91994 ,25.06173,4.54978 ), 'closePath', ('moveTo' ,25.18604,8.35371 ), ('curveTo' ,25.18604,8.60235 ,25.15384,8.83024 ,25.08937,9.03742 ), ('curveTo' ,25.02489,9.24463 ,24.93514,9.42278 ,24.82001,9.57197 ), ('curveTo' ,24.70492,9.72113 ,24.56911,9.83923 ,24.41255,9.92624 ), ('curveTo' ,24.25603,10.01326 ,24.08568,10.05678 ,23.90152,10.05678 ), ('curveTo' ,23.51474,10.05678 ,23.20169,9.89725 ,22.96225,9.57819 ), ('curveTo' ,22.72283,9.25913 ,22.60314,8.85096 ,22.60314,8.35371 ), 'closePath',
('moveTo' ,38.36308,-5.99181 ), ('lineTo' ,32.82428,-5.99181 ), ('lineTo' ,32.82428,13.43804 ), ('lineTo' ,38.36308,13.43804 ), ('lineTo' ,38.23873,11.53608 ), ('curveTo' ,38.46886,11.93387 ,38.70371,12.27159 ,38.94327,12.54922 ), ('curveTo' ,39.18254,12.82685 ,39.44037,13.05268 ,39.71676,13.22671 ), ('curveTo' ,39.99286,13.40074 ,40.28988,13.52712 ,40.60753,13.60585 ), ('curveTo' ,40.92518,13.68459 ,41.27759,13.72396 ,41.66419,13.72396 ), ('curveTo' ,43.10068,13.72396 ,44.2702,13.07755 ,45.17246,11.78472 ), ('curveTo' ,46.06588,10.50844 ,46.51229,8.81368 ,46.51229,6.70038 ), ('curveTo' ,46.51229,4.55394 ,46.08415,2.85502 ,45.22785,1.60362 ), ('curveTo' ,44.38983,0.35221 ,43.23416,-0.27348 ,41.76084,-0.27348 ), ('curveTo' ,40.41659,-0.27348 ,39.24235,0.42679 ,38.23873,1.82739 ), ('curveTo' ,38.2847,1.40472 ,38.31239,1.04007 ,38.32153,0.73345 ), ('curveTo' ,38.34923,0.41851 ,38.36308,0.04146 ,38.36308,-0.3978 ), 'closePath', ('moveTo' ,40.7802,6.84954 ), ('curveTo' ,40.7802,7.72802 ,40.66734,8.40964 ,40.44193,8.89448 ), ('curveTo' ,40.21621,9.37929 ,39.89621,9.62168 ,39.48191,9.62168 ), ('curveTo' ,38.62533,9.62168 ,38.19718,8.68108 ,38.19718,6.79983 ), ('curveTo' ,38.19718,4.87712 ,38.61177,3.91581 ,39.44037,3.91581 ), ('curveTo' ,39.85466,3.91581 ,40.18174,4.1727 ,40.42101,4.68654 ), ('curveTo' ,40.66057,5.20037 ,40.7802,5.92135 ,40.7802,6.84954 ), 'closePath',
('moveTo' ,69.78629,0 ), ('lineTo' ,64.2475,0 ), ('lineTo' ,64.2475,13.43804 ), ('lineTo' ,69.78629,13.43804 ), ('lineTo' ,69.49605,10.81507 ), ('curveTo' ,70.33407,12.77921 ,71.71988,13.76126 ,73.65346,13.76126 ), ('lineTo' ,73.65346,8.16725 ), ('curveTo' ,73.04586,8.4656 ,72.5302,8.61478 ,72.10647,8.61478 ), ('curveTo' ,71.36068,8.61478 ,70.78756,8.37236 ,70.38711,7.88755 ), ('curveTo' ,69.98637,7.40274 ,69.78629,6.69623 ,69.78629,5.76804 ), 'closePath',
('moveTo' ,81.55427,0 ), ('lineTo' ,76.00163,0 ), ('lineTo' ,76.00163,9.42278 ), ('lineTo' ,74.42725,9.42278 ), ('lineTo' ,74.42725,13.43804 ), ('lineTo' ,76.00163,13.43804 ), ('lineTo' ,76.00163,17.39113 ), ('lineTo' ,81.55427,17.39113 ), ('lineTo' ,81.55427,13.43804 ), ('lineTo' ,83.39121,13.43804 ), ('lineTo' ,83.39121,9.42278 ), ('lineTo' ,81.55427,9.42278 ), 'closePath',
('moveTo' ,95.17333,0 ), ('lineTo' ,85.09024,0 ), ('lineTo' ,85.09024,19.19365 ), ('lineTo' ,90.85002,19.19365 ), ('lineTo' ,90.85002,4.61196 ), ('lineTo' ,95.17333,4.61196 ), 'closePath',
('moveTo' ,110.00787,0 ), ('lineTo' ,104.45523,0 ), ('curveTo' ,104.5012,0.44754 ,104.53803,0.87433 ,104.56573,1.2804 ), ('curveTo' ,104.59313,1.68651 ,104.62083,2.01385 ,104.64853,2.26246 ), ('curveTo' ,103.69087,0.57182 ,102.40644,-0.27348 ,100.79492,-0.27348 ), ('curveTo' ,99.39527,-0.27348 ,98.28557,0.35637 ,97.46611,1.61605 ), ('curveTo' ,96.65578,2.86746 ,96.25062,4.59952 ,96.25062,6.81227 ), ('curveTo' ,96.25062,8.95041 ,96.66963,10.63276 ,97.50765,11.8593 ), ('curveTo' ,98.34538,13.10242 ,99.4872,13.72396 ,100.93312,13.72396 ), ('curveTo' ,102.41557,13.72396 ,103.61249,12.92008 ,104.52418,11.31231 ), ('curveTo' ,104.50591,11.47806 ,104.49206,11.62309 ,104.48293,11.74741 ), ('curveTo' ,104.4735,11.87173 ,104.46437,11.9753 ,104.45523,12.05819 ), ('lineTo' ,104.39983,12.84135 ), ('lineTo' ,104.35858,13.43804 ), ('lineTo' ,110.00787,13.43804 ), 'closePath', ('moveTo' ,104.39983,6.88685 ), ('curveTo' ,104.39983,7.38409 ,104.37921,7.80676 ,104.33766,8.15481 ), ('curveTo' ,104.29641,8.5029 ,104.22952,8.78672 ,104.13758,9.00636 ), ('curveTo' ,104.04535,9.22598 ,103.92572,9.38341 ,103.77839,9.47874 ), ('curveTo' ,103.63106,9.57403 ,103.45161,9.62168 ,103.23974,9.62168 ), ('curveTo' ,102.30036,9.62168 ,101.83096,8.49875 ,101.83096,6.25285 ), ('curveTo' ,101.83096,4.64508 ,102.24967,3.8412 ,103.0877,3.8412 ), ('curveTo' ,103.96255,3.8412 ,104.39983,4.85641 ,104.39983,6.88685 ), 'closePath',
('moveTo' ,118.22604,0 ), ('lineTo' ,112.5629,0 ), ('lineTo' ,112.5629,20.99616 ), ('lineTo' ,118.10169,20.99616 ), ('lineTo' ,118.10169,13.63694 ), ('curveTo' ,118.10169,13.01538 ,118.07399,12.30268 ,118.01889,11.49877 ), ('curveTo' ,118.52542,12.31096 ,119.03636,12.88693 ,119.55202,13.22671 ), ('curveTo' ,120.08625,13.55821 ,120.75838,13.72396 ,121.5687,13.72396 ), ('curveTo' ,123.07885,13.72396 ,124.24837,13.09827 ,125.07697,11.84686 ), ('curveTo' ,125.90586,10.60373 ,126.32015,8.85099 ,126.32015,6.5885 ), ('curveTo' ,126.32015,4.42546 ,125.89201,2.74314 ,125.03571,1.54147 ), ('curveTo' ,124.18826,0.3315 ,123.01432,-0.27348 ,121.51331,-0.27348 ), ('curveTo' ,120.78608,-0.27348 ,120.16905,-0.12432 ,119.66252,0.17403 ), ('curveTo' ,119.41383,0.3315 ,119.15835,0.54283 ,118.8961,0.80803 ), ('curveTo' ,118.63356,1.07322 ,118.36866,1.40472 ,118.10169,1.80252 ), ('curveTo' ,118.11112,1.64505 ,118.12025,1.51039 ,118.12939,1.3985 ), ('curveTo' ,118.13852,1.28662 ,118.14766,1.19339 ,118.15709,1.11881 ), 'closePath', ('moveTo' ,120.58806,6.70038 ), ('curveTo' ,120.58806,8.62306 ,120.11837,9.5844 ,119.17898,9.5844 ), ('curveTo' ,118.35039,9.5844 ,117.93609,8.67693 ,117.93609,6.86198 ), ('curveTo' ,117.93609,4.96417 ,118.36424,4.01526 ,119.22053,4.01526 ), ('curveTo' ,120.13222,4.01526 ,120.58806,4.91027 ,120.58806,6.70038 ), 'closePath',
]
showPage = self.showPage
PP = []
if showPage:
if not isSeq(showPage):
showPage = (showPage,showPage)
if showPage[0]: #top
PP.extend([('moveTo' ,32.70766,14.52164 ), ('lineTo' ,32.70766,47.81862 ), ('lineTo' ,80.14849,47.81862 ), ('lineTo' ,90.46172,37.21073 ), ('lineTo' ,90.46172,20.12025 ), ('lineTo' ,85.15777,20.12025 ), ('lineTo' ,85.15777,30.72814 ), ('lineTo' ,73.66589,30.72814 ), ('lineTo' ,73.66589,42.22002 ), ('lineTo' ,38.30626,42.22002 ), ('lineTo' ,38.30626,14.52164 ), 'closePath', ('moveTo' ,79.2645,36.32674 ), ('lineTo' ,85.15777,36.32674 ), ('lineTo' ,79.2645,42.22002 ), 'closePath'])
if showPage[1]: #bottom
PP.extend([('moveTo',38.30626,-7.28346),('lineTo',38.30626,-25.55261),('lineTo',85.15777,-25.55261),('lineTo',85.15777,-1.39019),('lineTo',90.46172,-1.39019),('lineTo',90.46172,-31.15121),('lineTo',32.70766,-31.15121),('lineTo',32.70766,-7.28346), 'closePath'])
if _ocolors:
OP = self.applyPrec(OP,self.prec)
g.add(definePath(OP,strokeColor=_ocolors[0],strokeWidth=strokeWidth,fillColor=_ocolors[1], dx=dx, dy=dy))
else:
P += OP
if self.showPage and _pagecolors:
PP = self.applyPrec(PP,self.prec)
g.add(definePath(PP,strokeColor=_pagecolors[0],strokeWidth=strokeWidth,fillColor=_pagecolors[1], dx=dx, dy=dy))
else:
P += PP
P = self.applyPrec(P,self.prec)
g.add(definePath(P,strokeColor=strokeColor,strokeWidth=strokeWidth,fillColor=fillColor, dx=dx, dy=dy))
@staticmethod
def applyPrec(P,prec):
if prec is None: return P
R = [].append
f = DecimalFormatter(places=prec)
for p in P:
if isSeq(p):
n = [].append
for e in p:
if isinstance(e,float):
e = float(f(e))
n(e)
p = n.__self__
R(p)
return R.__self__
def draw(self):
fillColor = self.fillColor
strokeColor = self.strokeColor
g = Group()
bg = self.background
bd = self.border
bdw = self.borderWidth
shadow = self.shadow
x, y = self.x, self.y
if bg:
if shadow is not None and 0<=shadow<1:
shadow = Color(bg.red*shadow,bg.green*shadow,bg.blue*shadow)
self._paintLogo(g,dy=-2.5, dx=2,fillColor=shadow)
self._paintLogo(g,fillColor=fillColor,strokeColor=strokeColor,
_ocolors=self.oColors or None,_pagecolors=self.pageColors or None)
g.skew(kx=self.skewX, ky=self.skewY)
g.shift(self._dx,self._dy)
G = Group()
G.add(g)
_w, _h = 130, 86
w, h = self.width, self.height
if bg or (bd and bdw):
G.insert(0,Rect(0,0,_w,_h,fillColor=bg,strokeColor=bd,strokeWidth=bdw))
if w!=_w or h!=_h: G.scale(w/float(_w),h/float(_h))
angle = self.angle
if self.angle:
w, h = w/2., h/2.
G.shift(-w,-h)
G.rotate(angle)
G.shift(w,h)
xFlip = getattr(self,'xFlip',0) and -1 or 0
yFlip = getattr(self,'yFlip',0) and -1 or 0
if xFlip or yFlip:
sx = xFlip or 1
sy = yFlip or 1
G.shift(sx*x+w*xFlip,sy*y+yFlip*h)
G = Group(G,transform=(sx,0,0,sy,0,0))
else:
G.shift(x,y)
return G
class RL_CorpLogoReversed(RL_CorpLogo):
def __init__(self):
RL_CorpLogo.__init__(self)
self.background = white
self.fillColor = ReportLabBlue
class RL_CorpLogoThin(Widget):
"""The ReportLab Logo.
New version created by John Precedo on 7-8 August 2001.
Based on bitmapped imaged from E-Id.
Improved by Robin Becker."""
_attrMap = AttrMap(
x = AttrMapValue(isNumber),
y = AttrMapValue(isNumber),
height = AttrMapValue(isNumberOrNone),
width = AttrMapValue(isNumberOrNone),
fillColor = AttrMapValue(isColorOrNone),
strokeColor = AttrMapValue( isColorOrNone)
)
_h = 90.5
_w = 136.5
_text='R e p o r t L a b'
_fontName = 'Helvetica-Bold'
_fontSize = 16
def __init__(self):
self.fillColor = ReportLabBlue
self.strokeColor = white
self.x = 0
self.y = 0
self.height = self._h
self.width = self._w
def demo(self):
D = Drawing(self.width, self.height)
D.add(self)
return D
def _getText(self, x=0, y=0, color=None):
return String(x,y, self._text, fontName=self._fontName, fontSize=self._fontSize, fillColor=color)
def _sw(self,f=None,l=None):
text = self._text
if f is None: f = 0
if l is None: l = len(text)
return stringWidth(text[f:l],self._fontName,self._fontSize)
def _addPage(self, g, strokeWidth=3, color=None, dx=0, dy=0):
x1, x2 = 31.85+dx, 80.97+dx
fL = 10 # fold length
y1, y2 = dy-34, dy+50.5
L = [[x1,dy-4,x1,y1, x2, y1, x2, dy-1],
[x1,dy+11,x1,y2,x2-fL,y2,x2,y2-fL,x2,dy+14],
[x2-10,y2,x2-10,y2-fL,x2,y2-fL]]
for l in L:
g.add(PolyLine(l, strokeWidth=strokeWidth, strokeColor=color, strokeLineJoin=0))
def draw(self):
sx = 0.5
fillColor = self.fillColor
strokeColor = self.strokeColor
shadow = Color(fillColor.red*sx,fillColor.green*sx,fillColor.blue*sx)
g = Group()
g2= Group()
g.add(Rect(fillColor=fillColor, strokeColor=fillColor, x=0, y=0, width=self._w, height=self._h))
sx = (self._w-2)/self._sw()
g2.scale(sx,1)
self._addPage(g2,strokeWidth=3,dx=2,dy=-2.5,color=shadow)
self._addPage(g2,strokeWidth=3,color=strokeColor)
g2.scale(1/sx,1)
g2.add(self._getText(x=1,y=0,color=shadow))
g2.add(self._getText(x=0,y=1,color=strokeColor))
g2.scale(sx,1)
g2.skew(kx=10, ky=0)
g2.shift(0,38)
g.add(g2)
g.scale(self.width/self._w,self.height/self._h)
g.shift(self.x,self.y)
return g
class ReportLabLogo:
"""vector reportlab logo centered in a 250x by 150y rectangle"""
def __init__(self, atx=0, aty=0, width=2.5*inch, height=1.5*inch, powered_by=0):
self.origin = (atx, aty)
self.dimensions = (width, height)
self.powered_by = powered_by
def draw(self, canvas):
from reportlab.graphics import renderPDF
canvas.saveState()
(atx,aty) = self.origin
(width, height) = self.dimensions
logo = RL_CorpLogo()
logo.width, logo.height = width, height
renderPDF.draw(logo.demo(),canvas,atx,aty,0)
canvas.restoreState()
class RL_BusinessCard(Widget):
"""Widget that creates a single business card.
Uses RL_CorpLogo for the logo.
For a black border around your card, set self.border to 1.
To change the details on the card, over-ride the following properties:
self.name, self.position, self.telephone, self.mobile, self.fax, self.email, self.web
The office locations are set in self.rh_blurb_top ("London office" etc), and
self.rh_blurb_bottom ("New York office" etc).
"""
# for items where it 'isString' the string can be an empty one...
_attrMap = AttrMap(
fillColor = AttrMapValue(isColorOrNone),
strokeColor = AttrMapValue(isColorOrNone),
altStrokeColor = AttrMapValue(isColorOrNone),
x = AttrMapValue(isNumber),
y = AttrMapValue(isNumber),
height = AttrMapValue(isNumber),
width = AttrMapValue(isNumber),
borderWidth = AttrMapValue(isNumber),
bleed=AttrMapValue(isNumberOrNone),
cropMarks=AttrMapValue(isBoolean),
border=AttrMapValue(isBoolean),
name=AttrMapValue(isString),
position=AttrMapValue(isString),
telephone=AttrMapValue(isString),
mobile=AttrMapValue(isString),
fax=AttrMapValue(isString),
email=AttrMapValue(isString),
web=AttrMapValue(isString),
rh_blurb_top=AttrMapValue(isListOfStringsOrNone),
rh_blurb_bottom=AttrMapValue(isListOfStringsOrNone)
)
_h = 5.35*cm
_w = 8.5*cm
_fontName = 'Helvetica-Bold'
_strapline = "strategic reporting solutions for e-business"
def __init__(self):
self.fillColor = ReportLabBlue
self.strokeColor = black
self.altStrokeColor = white
self.x = 0
self.y = 0
self.height = self._h
self.width = self._w
self.borderWidth = self.width/6.15
self.bleed=0.2*cm
self.cropMarks=1
self.border=0
#Over-ride these with your own info
self.name="Joe Cool"
self.position="Freelance Demonstrator"
self.telephone="020 8545 7271"
self.mobile="-"
self.fax="020 8544 1311"
self.email="info@reportlab.com"
self.web="www.reportlab.com"
self.rh_blurb_top = ["London office:",
"ReportLab Europe Ltd",
"Media House",
"3 Palmerston Road",
"Wimbledon",
"London SW19 1PG",
"United Kingdom"]
def demo(self):
D = Drawing(self.width, self.height)
D.add(self)
return D
def draw(self):
fillColor = self.fillColor
strokeColor = self.strokeColor
g = Group()
g.add(Rect(x = 0, y = 0,
fillColor = self.fillColor,
strokeColor = self.fillColor,
width = self.borderWidth,
height = self.height))
g.add(Rect(x = 0, y = self.height-self.borderWidth,
fillColor = self.fillColor,
strokeColor = self.fillColor,
width = self.width,
height = self.borderWidth))
g2 = Group()
rl=RL_CorpLogo()
rl.height = 1.25*cm
rl.width = 1.9*cm
rl.draw()
g2.add(rl)
g.add(g2)
g2.shift(x=(self.width-(rl.width+(self.width/42))),
y=(self.height - (rl.height+(self.height/42))))
g.add(String(x = self.borderWidth/5.0,
y = ((self.height - (rl.height+(self.height/42)))+((38/90.5)*rl.height)),
fontSize = 6,
fillColor = self.altStrokeColor,
fontName = "Helvetica-BoldOblique",
textAnchor = 'start',
text = self._strapline))
leftText=["Tel:", "Mobile:", "Fax:", "Email:", "Web:"]
leftDetails=[self.telephone,self.mobile,self.fax,self.email,self.web]
leftText.reverse()
leftDetails.reverse()
for f in range(len(leftText),0,-1):
g.add(String(x = self.borderWidth+(self.borderWidth/5.0),
y = (self.borderWidth/5.0)+((f-1)*(5*1.2)),
fontSize = 5,
fillColor = self.strokeColor,
fontName = "Helvetica",
textAnchor = 'start',
text = leftText[f-1]))
g.add(String(x = self.borderWidth+(self.borderWidth/5.0)+self.borderWidth,
y = (self.borderWidth/5.0)+((f-1)*(5*1.2)),
fontSize = 5,
fillColor = self.strokeColor,
fontName = "Helvetica",
textAnchor = 'start',
text = leftDetails[f-1]))
ty = (self.height-self.borderWidth-(self.borderWidth/5.0)+2)
# g.add(Line(self.borderWidth, ty, self.borderWidth+(self.borderWidth/5.0), ty))
# g.add(Line(self.borderWidth+(self.borderWidth/5.0), ty, self.borderWidth+(self.borderWidth/5.0),
# ty+(self.borderWidth/5.0)))
# g.add(Line(self.borderWidth, ty-10,
# self.borderWidth+(self.borderWidth/5.0), ty-10))
rightText=self.rh_blurb_top
for f in range(1,(len(rightText)+1)):
g.add(String(x = self.width-(self.borderWidth/5.0),
y = ty-((f)*(5*1.2)),
fontSize = 5,
fillColor = self.strokeColor,
fontName = "Helvetica",
textAnchor = 'end',
text = rightText[f-1]))
g.add(String(x = self.borderWidth+(self.borderWidth/5.0),
y = ty-10,
fontSize = 10,
fillColor = self.strokeColor,
fontName = "Helvetica",
textAnchor = 'start',
text = self.name))
ty1 = ty-10*1.2
g.add(String(x = self.borderWidth+(self.borderWidth/5.0),
y = ty1-8,
fontSize = 8,
fillColor = self.strokeColor,
fontName = "Helvetica",
textAnchor = 'start',
text = self.position))
if self.border:
g.add(Rect(x = 0, y = 0,
fillColor=None,
strokeColor = black,
width = self.width,
height = self.height))
g.shift(self.x,self.y)
return g
def test(formats=['pdf','eps','jpg','gif','svg']):
"""This function produces a pdf with examples. """
#white on blue
rl = RL_CorpLogo()
rl.width = 129
rl.height = 86
D = Drawing(rl.width,rl.height)
D.add(rl)
D.__dict__['verbose'] = 1
D.save(fnRoot='corplogo_whiteonblue',formats=formats)
#blue on white
rl = RL_CorpLogoReversed()
rl.width = 129
rl.height = 86
D = Drawing(rl.width,rl.height)
D.add(rl)
D.__dict__['verbose'] = 1
D.save(fnRoot='corplogo_blueonwhite',formats=formats)
#gray on white
rl = RL_CorpLogoReversed()
rl.fillColor = Color(0.2, 0.2, 0.2)
rl.width = 129
rl.height = 86
D = Drawing(rl.width,rl.height)
D.add(rl)
D.__dict__['verbose'] = 1
D.save(fnRoot='corplogo_grayonwhite',formats=formats)
rl = RL_BusinessCard()
rl.x=25
rl.y=25
rl.border=1
D = Drawing(rl.width+50,rl.height+50)
D.add(rl)
D.__dict__['verbose'] = 1
D.save(fnRoot='RL_BusinessCard',formats=formats)
if __name__=='__main__':
test()
@@ -0,0 +1,11 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/enums.py
__version__='3.3.0'
__doc__="""
Container for constants. Hardly used!
"""
TA_LEFT = 0
TA_CENTER = 1
TA_RIGHT = 2
TA_JUSTIFY = 4
@@ -0,0 +1,91 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__='''Apparently not used anywhere, purpose unknown!'''
try:
from tokenize import tokenprog
except ImportError:
from tokenize import Token
import re
tokenprog = re.compile(Token)
del Token, re
import sys
def _matchorfail(text, pos):
match = tokenprog.match(text, pos)
if match is None: raise ValueError(text, pos)
return match, match.end()
'''
Extended dictionary formatting
We allow expressions in the parentheses instead of
just a simple variable.
'''
def dictformat(_format, L={}, G={}):
format = _format
S = {}
chunks = []
pos = 0
n = 0
while 1:
pc = format.find("%", pos)
if pc < 0: break
nextchar = format[pc+1]
if nextchar == "(":
chunks.append(format[pos:pc])
pos, level = pc+2, 1
while level:
match, pos = _matchorfail(format, pos)
tstart, tend = match.regs[3]
token = format[tstart:tend]
if token == "(": level = level+1
elif token == ")": level = level-1
vname = '__superformat_%d' % n
n += 1
S[vname] = eval(format[pc+2:pos-1],G,L)
chunks.append('%%(%s)' % vname)
else:
nc = pc+1+(nextchar=="%")
chunks.append(format[pos:nc])
pos = nc
if pos < len(format): chunks.append(format[pos:])
return (''.join(chunks)) % S
def magicformat(format):
"""Evaluate and substitute the appropriate parts of the string."""
frame = sys._getframe(1)
return dictformat(format,frame.f_locals, frame.f_globals)
if __name__=='__main__':
from reportlab.lib.formatters import DecimalFormatter
_DF={}
def df(n,dp=2,ds='.',ts=','):
try:
_df = _DF[dp,ds]
except KeyError:
_df = _DF[dp,ds] = DecimalFormatter(places=dp,decimalSep=ds,thousandSep=ts)
return _df(n)
from reportlab.lib.extformat import magicformat
Z={'abc': ('ab','c')}
x = 300000.23
percent=79.2
class dingo:
a=3
print((magicformat('''
$%%(df(x,dp=3))s --> $%(df(x,dp=3))s
$%%(df(x,dp=2,ds=',',ts='.'))s --> $%(df(x,dp=2,ds=',',ts='.'))s
%%(percent).2f%%%% --> %(percent).2f%%
%%(dingo.a)s --> %(dingo.a)s
%%(Z['abc'][0])s --> %(Z['abc'][0])s
''')))
def func0(aa=1):
def func1(bb=2):
print((magicformat('bb=%(bb)s Z=%(Z)r')))
func1('BB')
func0('AA')
@@ -0,0 +1,360 @@
#Copyright ReportLab Europe Ltd. 2000-2019
#see license.txt for license details
__version__='3.4.22'
#modification of users/robin/ttflist.py.
__doc__="""This provides some general-purpose tools for finding fonts.
The FontFinder object can search for font files. It aims to build
a catalogue of fonts which our framework can work with. It may be useful
if you are building GUIs or design-time interfaces and want to present users
with a choice of fonts.
There are 3 steps to using it
1. create FontFinder and set options and directories
2. search
3. query
>>> import fontfinder
>>> ff = fontfinder.FontFinder()
>>> ff.addDirectories([dir1, dir2, dir3])
>>> ff.search()
>>> ff.getFamilyNames() #or whichever queries you want...
Because the disk search takes some time to find and parse hundreds of fonts,
it can use a cache to store a file with all fonts found. The cache file name
For each font found, it creates a structure with
- the short font name
- the long font name
- the principal file (.pfb for type 1 fonts), and the metrics file if appropriate
- the time modified (unix time stamp)
- a type code ('ttf')
- the family name
- bold and italic attributes
One common use is to display families in a dialog for end users;
then select regular, bold and italic variants of the font. To get
the initial list, use getFamilyNames; these will be in alpha order.
>>> ff.getFamilyNames()
['Bitstream Vera Sans', 'Century Schoolbook L', 'Dingbats', 'LettErrorRobot',
'MS Gothic', 'MS Mincho', 'Nimbus Mono L', 'Nimbus Roman No9 L',
'Nimbus Sans L', 'Vera', 'Standard Symbols L',
'URW Bookman L', 'URW Chancery L', 'URW Gothic L', 'URW Palladio L']
One can then obtain a specific font as follows
>>> f = ff.getFont('Bitstream Vera Sans', bold=False, italic=True)
>>> f.fullName
'Bitstream Vera Sans'
>>> f.fileName
'C:\\code\\reportlab\\fonts\\Vera.ttf'
>>>
It can also produce an XML report of fonts found by family, for the benefit
of non-Python applications.
Future plans might include using this to auto-register fonts; and making it
update itself smartly on repeated instantiation.
"""
import sys, os, pickle
from hashlib import md5
from xml.sax.saxutils import quoteattr
from time import process_time as clock
from reportlab.lib.utils import asBytes, asNative as _asNative
def asNative(s):
try:
return _asNative(s)
except:
return _asNative(s,enc='latin-1')
EXTENSIONS = ['.ttf','.ttc','.otf','.pfb','.pfa']
# PDF font flags (see PDF Reference Guide table 5.19)
FF_FIXED = 1 << 1-1
FF_SERIF = 1 << 2-1
FF_SYMBOLIC = 1 << 3-1
FF_SCRIPT = 1 << 4-1
FF_NONSYMBOLIC = 1 << 6-1
FF_ITALIC = 1 << 7-1
FF_ALLCAP = 1 << 17-1
FF_SMALLCAP = 1 << 18-1
FF_FORCEBOLD = 1 << 19-1
class FontDescriptor:
"""This is a short descriptive record about a font.
typeCode should be a file extension e.g. ['ttf','ttc','otf','pfb','pfa']
"""
def __init__(self):
self.name = None
self.fullName = None
self.familyName = None
self.styleName = None
self.isBold = False #true if it's somehow bold
self.isItalic = False #true if it's italic or oblique or somehow slanty
self.isFixedPitch = False
self.isSymbolic = False #false for Dingbats, Symbols etc.
self.typeCode = None #normally the extension minus the dot
self.fileName = None #full path to where we found it.
self.metricsFileName = None #defined only for type='type1pc', or 'type1mac'
self.timeModified = 0
def __repr__(self):
return "FontDescriptor(%s)" % self.name
def getTag(self):
"Return an XML tag representation"
attrs = []
for k, v in self.__dict__.items():
if k not in ['timeModified']:
if v:
attrs.append('%s=%s' % (k, quoteattr(str(v))))
return '<font ' + ' '.join(attrs) + '/>'
from reportlab.lib.utils import rl_isdir, rl_isfile, rl_listdir, rl_getmtime
class FontFinder:
def __init__(self, dirs=[], useCache=True, validate=False, recur=False, fsEncoding=None, verbose=0):
self.useCache = useCache
self.validate = validate
if fsEncoding is None:
fsEncoding = sys.getfilesystemencoding()
self._fsEncoding = fsEncoding or 'utf8'
self._dirs = set()
self._recur = recur
self.addDirectories(dirs)
self._fonts = []
self._skippedFiles = [] #list of filenames we did not handle
self._badFiles = [] #list of filenames we rejected
self._fontsByName = {}
self._fontsByFamily = {}
self._fontsByFamilyBoldItalic = {} #indexed by bold, italic
self.verbose = verbose
def addDirectory(self, dirName, recur=None):
#aesthetics - if there are 2 copies of a font, should the first or last
#be picked up? might need reversing
if rl_isdir(dirName):
self._dirs.add(dirName)
if recur if recur is not None else self._recur:
for r,D,F in os.walk(dirName):
for d in D:
self._dirs.add(os.path.join(r,d))
def addDirectories(self, dirNames,recur=None):
for dirName in dirNames:
self.addDirectory(dirName,recur=recur)
def getFamilyNames(self):
"Returns a list of the distinct font families found"
if not self._fontsByFamily:
fonts = self._fonts
for font in fonts:
fam = font.familyName
if fam is None: continue
if fam in self._fontsByFamily:
self._fontsByFamily[fam].append(font)
else:
self._fontsByFamily[fam] = [font]
fsEncoding = self._fsEncoding
names = list(asBytes(_,enc=fsEncoding) for _ in self._fontsByFamily.keys())
names.sort()
return names
def getFontsInFamily(self, familyName):
"Return list of all font objects with this family name"
return self._fontsByFamily.get(familyName,[])
def getFamilyXmlReport(self):
"""Reports on all families found as XML.
"""
lines = []
lines.append('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>')
lines.append("<font_families>")
for dirName in self._dirs:
lines.append(" <directory name=%s/>" % quoteattr(asNative(dirName)))
for familyName in self.getFamilyNames():
if familyName: #skip null case
lines.append(' <family name=%s>' % quoteattr(asNative(familyName)))
for font in self.getFontsInFamily(familyName):
lines.append(' ' + font.getTag())
lines.append(' </family>')
lines.append("</font_families>")
return '\n'.join(lines)
def getFontsWithAttributes(self, **kwds):
"""This is a general lightweight search."""
selected = []
for font in self._fonts:
OK = True
for k, v in kwds.items():
if getattr(font, k, None) != v:
OK = False
if OK:
selected.append(font)
return selected
def getFont(self, familyName, bold=False, italic=False):
"""Try to find a font matching the spec"""
for font in self._fonts:
if font.familyName == familyName:
if font.isBold == bold:
if font.isItalic == italic:
return font
raise KeyError("Cannot find font %s with bold=%s, italic=%s" % (familyName, bold, italic))
def _getCacheFileName(self):
"""Base this on the directories...same set of directories
should give same cache"""
fsEncoding = self._fsEncoding
hash = md5(b''.join(asBytes(_,enc=fsEncoding) for _ in sorted(self._dirs)),usedforsecurity=False).hexdigest()
from reportlab.lib.utils import get_rl_tempfile
fn = get_rl_tempfile('fonts_%s.dat' % hash)
return fn
def save(self, fileName):
f = open(fileName, 'wb')
pickle.dump(self, f)
f.close()
def load(self, fileName):
f = open(fileName, 'rb')
finder2 = pickle.load(f)
f.close()
self.__dict__.update(finder2.__dict__)
def search(self):
if self.verbose:
started = clock()
if not self._dirs:
raise ValueError("Font search path is empty! Please specify search directories using addDirectory or addDirectories")
if self.useCache:
cfn = self._getCacheFileName()
if rl_isfile(cfn):
try:
self.load(cfn)
if self.verbose>=3:
print("loaded cached file with %d fonts (%s)" % (len(self._fonts), cfn))
return
except:
pass #pickle load failed. Ho hum, maybe it's an old pickle. Better rebuild it.
for dirName in self._dirs:
try:
fileNames = rl_listdir(dirName)
except:
continue
for fileName in fileNames:
root, ext = os.path.splitext(fileName)
if ext.lower() in EXTENSIONS:
#it's a font
f = FontDescriptor()
f.fileName = fileName = os.path.normpath(os.path.join(dirName, fileName))
try:
f.timeModified = rl_getmtime(fileName)
except:
self._skippedFiles.append(fileName)
continue
ext = ext.lower()
if ext[0] == '.':
ext = ext[1:]
f.typeCode = ext #strip the dot
#what to do depends on type. We only accept .pfb if we
#have .afm to go with it, and don't handle .otf now.
if ext in ('otf', 'pfa'):
self._skippedFiles.append(fileName)
elif ext in ('ttf','ttc'):
#parsing should check it for us
from reportlab.pdfbase.ttfonts import TTFontFile, TTFError
try:
font = TTFontFile(fileName,validate=self.validate)
except TTFError:
self._badFiles.append(fileName)
continue
f.name = font.name
f.fullName = font.fullName
f.styleName = font.styleName
f.familyName = font.familyName
f.isBold = (FF_FORCEBOLD == FF_FORCEBOLD & font.flags)
f.isItalic = (FF_ITALIC == FF_ITALIC & font.flags)
elif ext == 'pfb':
# type 1; we need an AFM file or have to skip.
if rl_isfile(os.path.join(dirName, root + '.afm')):
f.metricsFileName = os.path.normpath(os.path.join(dirName, root + '.afm'))
elif rl_isfile(os.path.join(dirName, root + '.AFM')):
f.metricsFileName = os.path.normpath(os.path.join(dirName, root + '.AFM'))
else:
self._skippedFiles.append(fileName)
continue
from reportlab.pdfbase.pdfmetrics import parseAFMFile
(info, glyphs) = parseAFMFile(f.metricsFileName)
f.name = info['FontName']
f.fullName = info.get('FullName', f.name)
f.familyName = info.get('FamilyName', None)
f.isItalic = (float(info.get('ItalicAngle', 0)) > 0.0)
#if the weight has the word bold, deem it bold
f.isBold = ('bold' in info.get('Weight','').lower())
self._fonts.append(f)
if self.useCache:
self.save(cfn)
if self.verbose:
finished = clock()
print("found %d fonts; skipped %d; bad %d. Took %0.2f seconds" % (
len(self._fonts), len(self._skippedFiles), len(self._badFiles),
finished - started
))
def test():
#windows-centric test maybe
from reportlab import rl_config
ff = FontFinder(verbose=rl_config.verbose)
ff.useCache = True
ff.validate = True
import reportlab
ff.addDirectory('C:\\windows\\fonts')
rlFontDir = os.path.join(os.path.dirname(reportlab.__file__), 'fonts')
ff.addDirectory(rlFontDir)
ff.search()
print('cache file name...')
print(ff._getCacheFileName())
print('families...')
for familyName in ff.getFamilyNames():
print('\t%s' % familyName)
print()
outw = sys.stdout.write
outw('fonts called Vera:')
for font in ff.getFontsInFamily('Bitstream Vera Sans'):
outw(' %s' % font.name)
print()
outw('Bold fonts\n\t')
for font in ff.getFontsWithAttributes(isBold=True, isItalic=False):
outw(font.fullName+' ')
print()
print('family report')
print(ff.getFamilyXmlReport())
if __name__=='__main__':
test()
@@ -0,0 +1,96 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/fonts.py
__version__='3.3.0'
__doc__='''Utilities to associate bold and italic versions of fonts into families
Bold, italic and plain fonts are usually implemented in separate disk files;
but non-trivial apps want <b>this</b> to do the right thing. We therefore
need to keep 'mappings' between the font family name and the right group
of up to 4 implementation fonts to use.
Most font-handling code lives in pdfbase, and this probably should too.
'''
###############################################################################
# A place to put useful font stuff
###############################################################################
#
# Font Mappings
# The brute force approach to finding the correct postscript font name;
# much safer than the rule-based ones we tried.
# preprocessor to reduce font face names to the shortest list
# possible. Add any aliases you wish; it keeps looking up
# until it finds no more translations to do. Any input
# will be lowercased before checking.
_family_alias = {
'serif':'times',
'sansserif':'helvetica',
'monospaced':'courier',
'arial':'helvetica'
}
#maps a piddle font to a postscript one.
_tt2ps_map = {
#face, bold, italic -> ps name
('times', 0, 0) :'Times-Roman',
('times', 1, 0) :'Times-Bold',
('times', 0, 1) :'Times-Italic',
('times', 1, 1) :'Times-BoldItalic',
('courier', 0, 0) :'Courier',
('courier', 1, 0) :'Courier-Bold',
('courier', 0, 1) :'Courier-Oblique',
('courier', 1, 1) :'Courier-BoldOblique',
('helvetica', 0, 0) :'Helvetica',
('helvetica', 1, 0) :'Helvetica-Bold',
('helvetica', 0, 1) :'Helvetica-Oblique',
('helvetica', 1, 1) :'Helvetica-BoldOblique',
# there is only one Symbol font
('symbol', 0, 0) :'Symbol',
('symbol', 1, 0) :'Symbol',
('symbol', 0, 1) :'Symbol',
('symbol', 1, 1) :'Symbol',
# ditto for dingbats
('zapfdingbats', 0, 0) :'ZapfDingbats',
('zapfdingbats', 1, 0) :'ZapfDingbats',
('zapfdingbats', 0, 1) :'ZapfDingbats',
('zapfdingbats', 1, 1) :'ZapfDingbats',
}
_ps2tt_map={}
for k in sorted(_tt2ps_map.keys()):
v = _tt2ps_map[k].lower()
if v not in _ps2tt_map:
_ps2tt_map[v] = k
v = k[0].lower()
if v not in _ps2tt_map:
_ps2tt_map[v] = k
def ps2tt(psfn):
'ps fontname to family name, bold, italic'
psfn = psfn.lower()
if psfn in _ps2tt_map:
return _ps2tt_map[psfn]
raise ValueError("Can't map determine family/bold/italic for %s" % psfn)
def tt2ps(fn,b,i):
'family name + bold & italic to ps font name'
K = (fn.lower(),b,i)
if K in _tt2ps_map:
return _tt2ps_map[K]
else:
fn, b1, i1 = ps2tt(K[0])
K = fn, b1|b, i1|i
if K in _tt2ps_map:
return _tt2ps_map[K]
raise ValueError("Can't find concrete font for family=%s, bold=%d, italic=%d" % (fn, b, i))
def addMapping(face, bold, italic, psname):
'allow a custom font to be put in the mapping'
k = face.lower(), bold, italic
_tt2ps_map[k] = psname
_ps2tt_map[psname.lower()] = k
@@ -0,0 +1,109 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/formatters.py
__all__=('Formatter','DecimalFormatter')
__version__='3.3.0'
__doc__="""
These help format numbers and dates in a user friendly way.
Used by the graphics framework.
"""
import re
class Formatter:
"Base formatter - simply applies python format strings"
def __init__(self, pattern):
self.pattern = pattern
def format(self, obj):
return self.pattern % obj
def __repr__(self):
return "%s('%s')" % (self.__class__.__name__, self.pattern)
def __call__(self, x):
return self.format(x)
_ld_re=re.compile(r'^\d*\.')
_tz_re=re.compile('0+$')
class DecimalFormatter(Formatter):
"""lets you specify how to build a decimal.
A future NumberFormatter class will take Microsoft-style patterns
instead - "$#,##0.00" is WAY easier than this."""
def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None):
if places=='auto':
self.calcPlaces = self._calcPlaces
else:
self.places = places
self.dot = decimalSep
self.comma = thousandSep
self.prefix = prefix
self.suffix = suffix
def _calcPlaces(self,V):
'''called with the full set of values to be formatted so we can calculate places'''
self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V])
def format(self, num):
# positivize the numbers
sign=num<0
if sign:
num = -num
places, sep = self.places, self.dot
strip = places<=0
if places and strip: places = -places
strInt = ('%.' + str(places) + 'f') % num
if places:
strInt, strFrac = strInt.split('.')
strFrac = sep + strFrac
if strip:
while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1]
else:
strFrac = ''
if self.comma is not None:
strNew = ''
while strInt:
left, right = strInt[0:-3], strInt[-3:]
if left == '':
#strNew = self.comma + right + strNew
strNew = right + strNew
else:
strNew = self.comma + right + strNew
strInt = left
strInt = strNew
strBody = strInt + strFrac
if sign: strBody = '-' + strBody
if self.prefix:
strBody = self.prefix + strBody
if self.suffix:
strBody = strBody + self.suffix
return strBody
def __repr__(self):
return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % (
self.__class__.__name__,
self.places,
repr(self.dot),
repr(self.comma),
repr(self.prefix),
repr(self.suffix)
)
if __name__=='__main__':
def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None):
f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix)
r = f(n)
print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD'))
t(1000.9,'1,000.9',1,thousandSep=',')
t(1000.95,'1,001.0',1,thousandSep=',')
t(1000.95,'1,001',-1,thousandSep=',')
t(1000.9,'1,001',0,thousandSep=',')
t(1000.9,'1000.9',1)
t(1000.95,'1001.0',1)
t(1000.95,'1001',-1)
t(1000.9,'1001',0)
t(1000.1,'1000.1',1)
t(1000.55,'1000.6',1)
t(1000.449,'1000.4',-1)
t(1000.45,'1000',0)
@@ -0,0 +1,33 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__='''Utility functions for geometrical operations.'''
def normalizeTRBL(p):
'''
Useful for interpreting short descriptions of paddings, borders, margin, etc.
Expects a single value or a tuple of length 1 to 4.
Returns a tuple representing (clockwise) the value(s) applied to the 4 sides of a rectangle:
If a single value is given, that value is applied to all four sides.
If two or three values are given, the missing values are taken from the opposite side(s).
If four values are given they are returned unchanged.
>>> normalizeTRBL(1)
(1, 1, 1, 1)
>>> normalizeTRBL((1, 1.2))
(1, 1.2, 1, 1.2)
>>> normalizeTRBL((1, 1.2, 0))
(1, 1.2, 0, 1.2)
>>> normalizeTRBL((1, 1.2, 0, 8))
(1, 1.2, 0, 8)
'''
if not isinstance(p, (tuple, list)):
return (p,)*4
else:
l = len(p)
if l==1: return (p[0],)*4
if l < 1 or l > 4:
raise ValueError('normalizeTRBL needs between 1 and 4 values but got %d.' % l)
return tuple(p) + tuple([ p[i-2] for i in range(l, 4) ])
@@ -0,0 +1,61 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/logger.py
__version__='3.3.0'
__doc__="Logging and warning framework, predating Python's logging package"
from sys import stderr
class Logger:
'''
An extended file type thing initially equivalent to sys.stderr
You can add/remove file type things; it has a write method
'''
def __init__(self):
self._fps = [stderr]
self._fns = {}
def add(self,fp):
'''add the file/string fp to the destinations'''
if isinstance(fp,str):
if fp in self._fns: return
fp = open(fn,'wb')
self._fns[fn] = fp
self._fps.append(fp)
def remove(self,fp):
'''remove the file/string fp from the destinations'''
if isinstance(fp,str):
if fp not in self._fns: return
fn = fp
fp = self._fns[fn]
del self.fns[fn]
if fp in self._fps:
del self._fps[self._fps.index(fp)]
def write(self,text):
'''write text to all the destinations'''
if text[-1]!='\n': text=text+'\n'
for fp in self._fps: fp.write(text)
def __call__(self,text):
self.write(text)
logger=Logger()
class WarnOnce:
def __init__(self,kind='Warn'):
self.uttered = {}
self.pfx = '%s: '%kind
self.enabled = 1
def once(self,warning):
if warning not in self.uttered:
if self.enabled: logger.write(self.pfx + warning)
self.uttered[warning] = 1
def __call__(self,warning):
self.once(warning)
warnOnce=WarnOnce()
infoOnce=WarnOnce('Info')
@@ -0,0 +1,656 @@
#!/usr/bin/env python
# normalDate.py - version 1.0 - 20000717
#hacked by Robin Becker 10/Apr/2001
#major changes include
# using Types instead of type(0) etc
# BusinessDate class
# __radd__, __rsub__ methods
# formatMS stuff
# derived from an original version created
# by Jeff Bauer of Rubicon Research and used
# with his kind permission
__version__='3.3.18'
__doc__="Jeff Bauer's lightweight date class, extended by us. Predates Python's datetime module."
_bigBangScalar = -4345732 # based on (-9999, 1, 1) BC/BCE minimum
_bigCrunchScalar = 2958463 # based on (9999,12,31) AD/CE maximum
_daysInMonthNormal = [31,28,31,30,31,30,31,31,30,31,30,31]
_daysInMonthLeapYear = [31,29,31,30,31,30,31,31,30,31,30,31]
_dayOfWeekName = '''Monday Tuesday Wednesday Thursday Friday Saturday Sunday'''
_dayOfWeekNameLower = _dayOfWeekName.lower().split()
_dayOfWeekName = _dayOfWeekName.split()
_monthName = '''January February March April May June
July August September October November December'''
_monthNameLower = _monthName.lower().split()
_monthName = _monthName.split()
import re, time, datetime
from .utils import isStr
if hasattr(time,'struct_time'):
_DateSeqTypes = (list,tuple,time.struct_time)
else:
_DateSeqTypes = (list,tuple)
_fmtPat = re.compile('\\{(m{1,5}|yyyy|yy|d{1,4})\\}',re.MULTILINE|re.IGNORECASE)
_iso_re = re.compile(r'(\d\d\d\d|\d\d)-(\d\d)-(\d\d)')
def getStdMonthNames():
return _monthNameLower
def getStdShortMonthNames():
return [x[:3] for x in getStdMonthNames()]
def getStdDayNames():
return _dayOfWeekNameLower
def getStdShortDayNames():
return [x[:3] for x in getStdDayNames()]
def isLeapYear(year):
"""determine if specified year is leap year, returns Python boolean"""
if year < 1600:
if year % 4:
return 0
else:
return 1
elif year % 4 != 0:
return 0
elif year % 100 != 0:
return 1
elif year % 400 != 0:
return 0
else:
return 1
class NormalDateException(Exception):
"""Exception class for NormalDate"""
pass
class NormalDate:
"""
NormalDate is a specialized class to handle dates without
all the excess baggage (time zones, daylight savings, leap
seconds, etc.) of other date structures. The minimalist
strategy greatly simplifies its implementation and use.
Internally, NormalDate is stored as an integer with values
in a discontinuous range of -99990101 to 99991231. The
integer value is used principally for storage and to simplify
the user interface. Internal calculations are performed by
a scalar based on Jan 1, 1900.
Valid NormalDate ranges include (-9999,1,1) B.C.E. through
(9999,12,31) C.E./A.D.
1.0
No changes, except the version number. After 3 years of use by
various parties I think we can consider it stable.
0.8
Added Prof. Stephen Walton's suggestion for a range method
- module author resisted the temptation to use lambda <0.5 wink>
0.7
Added Dan Winkler's suggestions for __add__, __sub__ methods
0.6
Modifications suggested by Kevin Digweed to fix:
- dayOfWeek, dayOfWeekAbbrev, clone methods
- Permit NormalDate to be a better behaved superclass
0.5
Minor tweaking
0.4
- Added methods __cmp__, __hash__
- Added Epoch variable, scoped to the module
- Added setDay, setMonth, setYear methods
0.3
Minor touch-ups
0.2
- Fixed bug for certain B.C.E leap years
- Added Jim Fulton's suggestions for short alias class name =ND
and __getstate__, __setstate__ methods
Special thanks: Roedy Green
"""
def __init__(self, normalDate=None):
"""
Accept 1 of 4 values to initialize a NormalDate:
1. None - creates a NormalDate for the current day
2. integer in yyyymmdd format
3. string in yyyymmdd format
4. tuple in (yyyy, mm, dd) - localtime/gmtime can also be used
5. string iso date format see _iso_re above
6. datetime.datetime or datetime.date
"""
if normalDate is None:
self.setNormalDate(time.localtime(time.time()))
else:
self.setNormalDate(normalDate)
def add(self, days):
"""add days to date; use negative integers to subtract"""
if not isinstance(days,int):
raise NormalDateException( \
'add method parameter must be integer type')
self.normalize(self.scalar() + days)
def __add__(self, days):
"""add integer to normalDate and return a new, calculated value"""
if not isinstance(days,int):
raise NormalDateException( \
'__add__ parameter must be integer type')
cloned = self.clone()
cloned.add(days)
return cloned
def __radd__(self,days):
'''for completeness'''
return self.__add__(days)
def clone(self):
"""return a cloned instance of this normalDate"""
return self.__class__(self.normalDate)
def __lt__(self,other):
if not hasattr(other,'normalDate'):
return False
return self.normalDate < other.normalDate
def __le__(self,other):
if not hasattr(other,'normalDate'):
return False
return self.normalDate <= other.normalDate
def __eq__(self,other):
if not hasattr(other,'normalDate'):
return False
return self.normalDate == other.normalDate
def __ne__(self,other):
if not hasattr(other,'normalDate'):
return True
return self.normalDate != other.normalDate
def __ge__(self,other):
if not hasattr(other,'normalDate'):
return True
return self.normalDate >= other.normalDate
def __gt__(self,other):
if not hasattr(other,'normalDate'):
return True
return self.normalDate > other.normalDate
def day(self):
"""return the day as integer 1-31"""
return int(repr(self.normalDate)[-2:])
def dayOfWeek(self):
"""return integer representing day of week, Mon=0, Tue=1, etc."""
return dayOfWeek(*self.toTuple())
@property
def __day_of_week_name__(self):
return getattr(self,'_dayOfWeekName',_dayOfWeekName)
def dayOfWeekAbbrev(self):
"""return day of week abbreviation for current date: Mon, Tue, etc."""
return self.__day_of_week_name__[self.dayOfWeek()][:3]
def dayOfWeekName(self):
"""return day of week name for current date: Monday, Tuesday, etc."""
return self.__day_of_week_name__[self.dayOfWeek()]
def dayOfYear(self):
"""day of year"""
if self.isLeapYear():
daysByMonth = _daysInMonthLeapYear
else:
daysByMonth = _daysInMonthNormal
priorMonthDays = 0
for m in range(self.month() - 1):
priorMonthDays = priorMonthDays + daysByMonth[m]
return self.day() + priorMonthDays
def daysBetweenDates(self, normalDate):
"""
return value may be negative, since calculation is
self.scalar() - arg
"""
if isinstance(normalDate,NormalDate):
return self.scalar() - normalDate.scalar()
else:
return self.scalar() - NormalDate(normalDate).scalar()
def equals(self, target):
if isinstance(target,NormalDate):
if target is None:
return self.normalDate is None
else:
return self.normalDate == target.normalDate
else:
return 0
def endOfMonth(self):
"""returns (cloned) last day of month"""
return self.__class__(self.__repr__()[-8:-2]+str(self.lastDayOfMonth()))
def firstDayOfMonth(self):
"""returns (cloned) first day of month"""
return self.__class__(self.__repr__()[-8:-2]+"01")
def formatUS(self):
"""return date as string in common US format: MM/DD/YY"""
d = self.__repr__()
return "%s/%s/%s" % (d[-4:-2], d[-2:], d[-6:-4])
def formatUSCentury(self):
"""return date as string in 4-digit year US format: MM/DD/YYYY"""
d = self.__repr__()
return "%s/%s/%s" % (d[-4:-2], d[-2:], d[-8:-4])
def _fmtM(self):
return str(self.month())
def _fmtMM(self):
return '%02d' % self.month()
def _fmtMMM(self):
return self.monthAbbrev()
def _fmtMMMM(self):
return self.monthName()
def _fmtMMMMM(self):
return self.monthName()[0]
def _fmtD(self):
return str(self.day())
def _fmtDD(self):
return '%02d' % self.day()
def _fmtDDD(self):
return self.dayOfWeekAbbrev()
def _fmtDDDD(self):
return self.dayOfWeekName()
def _fmtYY(self):
return '%02d' % (self.year()%100)
def _fmtYYYY(self):
return str(self.year())
def formatMS(self,fmt):
'''format like MS date using the notation
{YY} --> 2 digit year
{YYYY} --> 4 digit year
{M} --> month as digit
{MM} --> 2 digit month
{MMM} --> abbreviated month name
{MMMM} --> monthname
{MMMMM} --> first character of monthname
{D} --> day of month as digit
{DD} --> 2 digit day of month
{DDD} --> abrreviated weekday name
{DDDD} --> weekday name
'''
r = fmt[:]
f = 0
while 1:
m = _fmtPat.search(r,f)
if m:
y = getattr(self,'_fmt'+(m.group()[1:-1].upper()))()
i, j = m.span()
r = (r[0:i] + y) + r[j:]
f = i + len(y)
else:
return r
def __getstate__(self):
"""minimize persistent storage requirements"""
return self.normalDate
def __hash__(self):
return hash(self.normalDate)
def __int__(self):
return self.normalDate
def isLeapYear(self):
"""
determine if specified year is leap year, returning true (1) or
false (0)
"""
return isLeapYear(self.year())
def _isValidNormalDate(self, normalDate):
"""checks for date validity in [-]yyyymmdd format"""
if not isinstance(normalDate,int):
return 0
if len(repr(normalDate)) > 9:
return 0
if normalDate < 0:
dateStr = "%09d" % normalDate
else:
dateStr = "%08d" % normalDate
if len(dateStr) < 8:
return 0
elif len(dateStr) == 9:
if (dateStr[0] != '-' and dateStr[0] != '+'):
return 0
year = int(dateStr[:-4])
if year < -9999 or year > 9999 or year == 0:
return 0 # note: zero (0) is not a valid year
month = int(dateStr[-4:-2])
if month < 1 or month > 12:
return 0
if isLeapYear(year):
maxDay = _daysInMonthLeapYear[month - 1]
else:
maxDay = _daysInMonthNormal[month - 1]
day = int(dateStr[-2:])
if day < 1 or day > maxDay:
return 0
if year == 1582 and month == 10 and day > 4 and day < 15:
return 0 # special case of 10 days dropped: Oct 5-14, 1582
return 1
def lastDayOfMonth(self):
"""returns last day of the month as integer 28-31"""
if self.isLeapYear():
return _daysInMonthLeapYear[self.month() - 1]
else:
return _daysInMonthNormal[self.month() - 1]
def localeFormat(self):
"""override this method to use your preferred locale format"""
return self.formatUS()
def month(self):
"""returns month as integer 1-12"""
return int(repr(self.normalDate)[-4:-2])
@property
def __month_name__(self):
return getattr(self,'_monthName',_monthName)
def monthAbbrev(self):
"""returns month as a 3-character abbreviation, i.e. Jan, Feb, etc."""
return self.__month_name__[self.month() - 1][:3]
def monthName(self):
"""returns month name, i.e. January, February, etc."""
return self.__month_name__[self.month() - 1]
def normalize(self, scalar):
"""convert scalar to normalDate"""
if scalar < _bigBangScalar:
msg = "normalize(%d): scalar below minimum" % \
_bigBangScalar
raise NormalDateException(msg)
if scalar > _bigCrunchScalar:
msg = "normalize(%d): scalar exceeds maximum" % \
_bigCrunchScalar
raise NormalDateException(msg)
from math import floor
if scalar >= -115860:
year = 1600 + int(floor((scalar + 109573) / 365.2425))
elif scalar >= -693597:
year = 4 + int(floor((scalar + 692502) / 365.2425))
else:
year = -4 + int(floor((scalar + 695058) / 365.2425))
days = scalar - firstDayOfYear(year) + 1
if days <= 0:
year = year - 1
days = scalar - firstDayOfYear(year) + 1
daysInYear = 365
if isLeapYear(year):
daysInYear = daysInYear + 1
if days > daysInYear:
year = year + 1
days = scalar - firstDayOfYear(year) + 1
# add 10 days if between Oct 15, 1582 and Dec 31, 1582
if (scalar >= -115860 and scalar <= -115783):
days = days + 10
if isLeapYear(year):
daysByMonth = _daysInMonthLeapYear
else:
daysByMonth = _daysInMonthNormal
dc = 0; month = 12
for m in range(len(daysByMonth)):
dc = dc + daysByMonth[m]
if dc >= days:
month = m + 1
break
# add up the days in prior months
priorMonthDays = 0
for m in range(month - 1):
priorMonthDays = priorMonthDays + daysByMonth[m]
day = days - priorMonthDays
self.setNormalDate((year, month, day))
def range(self, days):
"""Return a range of normalDates as a list. Parameter
may be an int or normalDate."""
if not isinstance(days,int):
days = days - self # if not int, assume arg is normalDate type
r = []
for i in range(days):
r.append(self + i)
return r
def __repr__(self):
"""print format: [-]yyyymmdd"""
# Note: When disassembling a NormalDate string, be sure to
# count from the right, i.e. epochMonth = int(repr(Epoch)[-4:-2]),
# or the slice won't work for dates B.C.
if self.normalDate < 0:
return "%09d" % self.normalDate
else:
return "%08d" % self.normalDate
def scalar(self):
"""days since baseline date: Jan 1, 1900"""
(year, month, day) = self.toTuple()
days = firstDayOfYear(year) + day - 1
if self.isLeapYear():
for m in range(month - 1):
days = days + _daysInMonthLeapYear[m]
else:
for m in range(month - 1):
days = days + _daysInMonthNormal[m]
if year == 1582:
if month > 10 or (month == 10 and day > 4):
days = days - 10
return days
def setDay(self, day):
"""set the day of the month"""
maxDay = self.lastDayOfMonth()
if day < 1 or day > maxDay:
msg = "day is outside of range 1 to %d" % maxDay
raise NormalDateException(msg)
(y, m, d) = self.toTuple()
self.setNormalDate((y, m, day))
def setMonth(self, month):
"""set the month [1-12]"""
if month < 1 or month > 12:
raise NormalDateException('month is outside range 1 to 12')
(y, m, d) = self.toTuple()
self.setNormalDate((y, month, d))
def setNormalDate(self, normalDate):
"""
accepts date as scalar string/integer (yyyymmdd) or tuple
(year, month, day, ...)"""
if isinstance(normalDate,int):
self.normalDate = normalDate
elif isStr(normalDate):
try:
self.normalDate = int(normalDate)
except:
m = _iso_re.match(normalDate)
if m:
self.setNormalDate(m.group(1)+m.group(2)+m.group(3))
else:
raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate))
elif isinstance(normalDate,_DateSeqTypes):
self.normalDate = int("%04d%02d%02d" % normalDate[:3])
elif isinstance(normalDate,NormalDate):
self.normalDate = normalDate.normalDate
elif isinstance(normalDate,(datetime.datetime,datetime.date)):
self.normalDate = (normalDate.year*100+normalDate.month)*100+normalDate.day
else:
self.normalDate = None
if not self._isValidNormalDate(self.normalDate):
raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate))
def setYear(self, year):
if year == 0:
raise NormalDateException('cannot set year to zero')
elif year < -9999:
raise NormalDateException('year cannot be less than -9999')
elif year > 9999:
raise NormalDateException('year cannot be greater than 9999')
(y, m, d) = self.toTuple()
self.setNormalDate((year, m, d))
__setstate__ = setNormalDate
def __sub__(self, v):
if isinstance(v,int):
return self.__add__(-v)
return self.scalar() - v.scalar()
def __rsub__(self,v):
if isinstance(v,int):
return NormalDate(v) - self
else:
return v.scalar() - self.scalar()
def toTuple(self):
"""return date as (year, month, day) tuple"""
return (self.year(), self.month(), self.day())
def year(self):
"""return year in yyyy format, negative values indicate B.C."""
return int(repr(self.normalDate)[:-4])
################# Utility functions #################
def bigBang():
"""return lower boundary as a NormalDate"""
return NormalDate((-9999, 1, 1))
def bigCrunch():
"""return upper boundary as a NormalDate"""
return NormalDate((9999, 12, 31))
def dayOfWeek(y, m, d):
"""return integer representing day of week, Mon=0, Tue=1, etc."""
if m == 1 or m == 2:
m = m + 12
y = y - 1
return (d + 2*m + 3*(m+1)//5 + y + y//4 - y//100 + y//400) % 7
def firstDayOfYear(year):
"""number of days to the first of the year, relative to Jan 1, 1900"""
if not isinstance(year,int):
msg = "firstDayOfYear() expected integer, got %s" % type(year)
raise NormalDateException(msg)
if year == 0:
raise NormalDateException('first day of year cannot be zero (0)')
elif year < 0: # BCE calculation
firstDay = (year * 365) + int((year - 1) / 4) - 693596
else: # CE calculation
leapAdjust = int((year + 3) / 4)
if year > 1600:
leapAdjust = leapAdjust - int((year + 99 - 1600) / 100) + \
int((year + 399 - 1600) / 400)
firstDay = year * 365 + leapAdjust - 693963
if year > 1582:
firstDay = firstDay - 10
return firstDay
def FND(d):
'''convert to ND if required'''
return isinstance(d,NormalDate) and d or ND(d)
Epoch=bigBang()
ND=NormalDate
BDEpoch=ND(15821018)
BDEpochScalar = -115857
class BusinessDate(NormalDate):
"""
Specialised NormalDate
"""
def add(self, days):
"""add days to date; use negative integers to subtract"""
if not isinstance(days,int):
raise NormalDateException('add method parameter must be integer')
self.normalize(self.scalar() + days)
def __add__(self, days):
"""add integer to BusinessDate and return a new, calculated value"""
if not isinstance(days,int):
raise NormalDateException('__add__ parameter must be integer')
cloned = self.clone()
cloned.add(days)
return cloned
def __sub__(self, v):
return isinstance(v,int) and self.__add__(-v) or self.scalar() - v.scalar()
def asNormalDate(self):
return ND(self.normalDate)
def daysBetweenDates(self, normalDate):
return self.asNormalDate.daysBetweenDates(normalDate)
def _checkDOW(self):
if self.dayOfWeek()>4: raise NormalDateException("%r isn't a business day" % self.normalDate)
def normalize(self, i):
i = int(i)
NormalDate.normalize(self,(i//5)*7+i%5+BDEpochScalar)
def scalar(self):
d = self.asNormalDate()
i = d - BDEpoch #luckily BDEpoch is a Monday so we don't have a problem
#concerning the relative weekday
return 5*(i//7) + i%7
def setNormalDate(self, normalDate):
NormalDate.setNormalDate(self,normalDate)
self._checkDOW()
if __name__ == '__main__':
today = NormalDate()
print("NormalDate test:")
print(" Today (%s) is: %s %s" % (today, today.dayOfWeekAbbrev(), today.localeFormat()))
yesterday = today - 1
print(" Yesterday was: %s %s" % (yesterday.dayOfWeekAbbrev(), yesterday.localeFormat()))
tomorrow = today + 1
print(" Tomorrow will be: %s %s" % (tomorrow.dayOfWeekAbbrev(), tomorrow.localeFormat()))
print(" Days between tomorrow and yesterday: %d" % (tomorrow - yesterday))
print(today.formatMS('{d}/{m}/{yy}'))
print(today.formatMS('{dd}/{m}/{yy}'))
print(today.formatMS('{ddd} {d}/{m}/{yy}'))
print(today.formatMS('{dddd} {d}/{m}/{yy}'))
print(today.formatMS('{d}/{mm}/{yy}'))
print(today.formatMS('{d}/{mmm}/{yy}'))
print(today.formatMS('{d}/{mmmm}/{yy}'))
print(today.formatMS('{d}/{m}/{yyyy}'))
b = BusinessDate('20010116')
print('b=',b,'b.scalar()', b.scalar())
@@ -0,0 +1,84 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/pagesizes.py
"""This module defines a few common page sizes in points (1/72 inch).
To be expanded to include things like label sizes, envelope windows
etc."""
__version__='3.4.18'
from reportlab.lib.units import mm, inch
#ISO 216 standard paer sizes; see eg https://en.wikipedia.org/wiki/ISO_216
A0 = (841*mm,1189*mm)
A1 = (594*mm,841*mm)
A2 = (420*mm,594*mm)
A3 = (297*mm,420*mm)
A4 = (210*mm,297*mm)
A5 = (148*mm,210*mm)
A6 = (105*mm,148*mm)
A7 = (74*mm,105*mm)
A8 = (52*mm,74*mm)
A9 = (37*mm,52*mm)
A10 = (26*mm,37*mm)
B0 = (1000*mm,1414*mm)
B1 = (707*mm,1000*mm)
B2 = (500*mm,707*mm)
B3 = (353*mm,500*mm)
B4 = (250*mm,353*mm)
B5 = (176*mm,250*mm)
B6 = (125*mm,176*mm)
B7 = (88*mm,125*mm)
B8 = (62*mm,88*mm)
B9 = (44*mm,62*mm)
B10 = (31*mm,44*mm)
C0 = (917*mm,1297*mm)
C1 = (648*mm,917*mm)
C2 = (458*mm,648*mm)
C3 = (324*mm,458*mm)
C4 = (229*mm,324*mm)
C5 = (162*mm,229*mm)
C6 = (114*mm,162*mm)
C7 = (81*mm,114*mm)
C8 = (57*mm,81*mm)
C9 = (40*mm,57*mm)
C10 = (28*mm,40*mm)
#American paper sizes
LETTER = (8.5*inch, 11*inch)
LEGAL = (8.5*inch, 14*inch)
ELEVENSEVENTEEN = (11*inch, 17*inch)
# From https://en.wikipedia.org/wiki/Paper_size
JUNIOR_LEGAL = (5*inch, 8*inch)
HALF_LETTER = (5.5*inch, 8*inch)
GOV_LETTER = (8*inch, 10.5*inch)
GOV_LEGAL = (8.5*inch, 13*inch)
TABLOID = ELEVENSEVENTEEN
LEDGER = (17*inch, 11*inch)
# lower case is deprecated as of 12/2001, but here
# for compatability
letter=LETTER
legal=LEGAL
elevenSeventeen = ELEVENSEVENTEEN
#functions to mess with pagesizes
def landscape(pagesize):
"""Use this to get page orientation right"""
a, b = pagesize
if a < b:
return (b, a)
else:
return (a, b)
def portrait(pagesize):
"""Use this to get page orientation right"""
a, b = pagesize
if a >= b:
return (b, a)
else:
return (a, b)
@@ -0,0 +1,776 @@
#copyright ReportLab Europe Limited. 2000-2016
#see license.txt for license details
__version__='3.3.0'
"""helpers for pdf encryption/decryption"""
import sys, os
from binascii import hexlify, unhexlify
from hashlib import md5
from io import BytesIO
from reportlab.lib.utils import asBytes, int2Byte, rawBytes, asNative
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase.pdfdoc import PDFObject
from reportlab.platypus.flowables import Flowable
from reportlab import rl_config
try:
import pyaes
from hashlib import sha256
except ImportError:
pyaes = None
def xorKey(num,key):
"xor's each byte of the key with the number, which is <256"
if num==0: return key
return bytes(num^k for k in key)
#AR debug hooks - leaving in for now
CLOBBERID = 0 # set a constant Doc ID to allow comparison with other software like iText
CLOBBERPERMISSIONS = 0
DEBUG = rl_config.debug # print stuff to trace calculations
# permission bits
reserved1 = 1 # bit 1 must be 0
reserved2 = 1<<1 # bit 2 must be 0
printable = 1<<2
modifiable = 1<<3
copypastable = 1<<4
annotatable = 1<<5
# others [7..32] are reserved, must be 1
higherbits = 0
for i in range(6,31):
higherbits = higherbits | (1<<i)
if rl_config.invariant:
_os_random_x=0
_os_random_b = b'\xbd\x8f\xdc\xabovp\xe8\x15\xec\\C\x9d\x92B~\xb8\xf4\xdeEg8\xb2f\x80Sj\'y\xcfG\xcaY\xb9\xdc-\xc4Q\x17\x88\xaf\xd1\xf7\x7f\xa1L>\x99\x89i\xf7\xc4\xb4\'\xe9k\xc9\xfa\xa6p\x80\xcd\xaa\xaf|\x97\xf7\xcc \xc1\xef\xc7\x97\xd2;\xaf\xe1\xfc\x16,\xd3\x0b\x19\xa1\x02\xe6\x01\xcb\x1c\xd8\xe6\\H}\r\xdc\x85\xe1\xbc\xc4\x02>|\xc5\x97\xb5T\xad\x0cT\x95\xb1\xdc!\xb6+E#\xa1\xa4O\xf3j\x98"\xc2\x1a\xcb\x8cHB\xd8B~\xa7\x7f7\xd2\xe8\x131.\xd7\xa9\x0b\r\xdd2\x0b}\xc0\xffm\x9e3\xe2/\xea\x84W\x82\xbd\xc8K\xc2;?\xbe#\x84`W\xf3\xe0\xec\x9e\x85\x9c\xcb\xc7\xc9#\x19\xff\xde\x17\xea\xb2\xd4\x0e\x9a\xbd\xbaz\xbd\x87O\xd4\xf4\xac\xb3(z\x92\xfc\xbc\x85i\x8d\x1f\xfb!\t|w,\x8bI\xc9_D`A\xbc}\x0e+r\x1b-%F(@\xc8\\cL\x172(\x9c\x95BM\xa1\x89UG\x9d\xfd\xed\xce\xd8\x1f\xb1'
def os_urandom(n):
global _os_random_x
b = [_os_random_b[(i+_os_random_x)%256] for i in range(n)]
b = bytes(b)
_os_random_x = (_os_random_x + n) % 256
return b
else:
os_urandom = os.urandom
# no encryption
class StandardEncryption:
prepared = 0
def __init__(self, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=None):
'''
This class defines the encryption properties to be used while creating a pdf document.
Once initiated, a StandardEncryption object can be applied to a Canvas or a BaseDocTemplate.
The userPassword parameter sets the user password on the encrypted pdf.
The ownerPassword parameter sets the owner password on the encrypted pdf.
The boolean flags canPrint, canModify, canCopy, canAnnotate determine wether a user can
perform the corresponding actions on the pdf when only a user password has been supplied.
If the user supplies the owner password while opening the pdf, all actions can be performed regardless
of the flags.
Note that the security provided by these encryption settings (and even more so for the flags) is very weak.
'''
self.userPassword = userPassword
if ownerPassword:
self.ownerPassword = ownerPassword
else:
self.ownerPassword = userPassword
if strength is None:
strength = rl_config.encryptionStrength
if strength == 40:
self.revision = 2
elif strength == 128:
self.revision = 3
elif strength == 256:
if not pyaes:
raise ValueError('strength==256 is not supported as package pyaes is not importable')
self.revision = 5
else:
raise ValueError('Unknown encryption strength=%s' % repr(strength))
self.canPrint = canPrint
self.canModify = canModify
self.canCopy = canCopy
self.canAnnotate = canAnnotate
self.O = self.U = self.P = self.key = self.OE = self.UE = self.Perms = None
def setAllPermissions(self, value):
self.canPrint = \
self.canModify = \
self.canCopy = \
self.canAnnotate = value
def permissionBits(self):
p = 0
if self.canPrint: p = p | printable
if self.canModify: p = p | modifiable
if self.canCopy: p = p | copypastable
if self.canAnnotate: p = p | annotatable
p = p | higherbits
return p
def encode(self, t):
"encode a string, stream, text"
if not self.prepared:
raise ValueError("encryption not prepared!")
if self.objnum is None:
raise ValueError("not registered in PDF object")
return encodePDF(self.key, self.objnum, self.version, t, revision=self.revision)
def prepare(self, document, overrideID=None):
# get ready to do encryption
if DEBUG>=10: print('StandardEncryption.prepare(...) - revision %d' % self.revision)
if self.prepared:
raise ValueError("encryption already prepared!")
# get the unescaped string value of the document id (first array element).
# we allow one to be passed in instead to permit reproducible tests
# of our algorithm, but in real life overrideID will always be None
if overrideID:
internalID = overrideID
else:
externalID = document.ID() # initialize it...
internalID = document.signature.digest()
#AR debugging
if CLOBBERID:
internalID = "xxxxxxxxxxxxxxxx"
if DEBUG>=10:
print('userPassword = %r' % self.userPassword)
print('ownerPassword = %r' % self.ownerPassword)
print('internalID = %r' % internalID)
self.P = int(self.permissionBits() - 2**31)
if CLOBBERPERMISSIONS: self.P = -44 # AR hack
if DEBUG>=10:
print("self.P = %s" % repr(self.P))
if self.revision == 5:
# Init vectro for AES cipher (should be 16 bytes null array)
iv = b'\x00' * 16
# Random User salts
uvs = os_urandom(8)
uks = os_urandom(8)
# the main encryption key
self.key = asBytes(os_urandom(32))
if DEBUG>=10:
print("uvs (hex) = %s" % hexText(uvs))
print("uks (hex) = %s" % hexText(uks))
print("self.key (hex) = %s" % hexText(self.key))
# Calculate the sha-256 hash of the User password (U)
md = sha256(asBytes(self.userPassword[:127]) + uvs)
self.U = md.digest() + uvs + uks
if DEBUG>=10:
print("self.U (hex) = %s" % hexText(self.U))
# Calculate the User encryption key (UE)
md = sha256(asBytes(self.userPassword[:127]) + uks)
encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(md.digest(), iv=iv))
self.UE = encrypter.feed(self.key)
self.UE += encrypter.feed()
if DEBUG>=10:
print("self.UE (hex) = %s" % hexText(self.UE))
# Random Owner salts
ovs = os_urandom(8)
oks = os_urandom(8)
# Calculate the hash of the Owner password (U)
md = sha256(asBytes(self.ownerPassword[:127]) + ovs + self.U )
self.O = md.digest() + ovs + oks
if DEBUG>=10:
print("self.O (hex) = %s" % hexText(self.O))
# Calculate the User encryption key (OE)
md = sha256(asBytes(self.ownerPassword[:127]) + oks + self.U)
encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(md.digest(), iv=iv))
self.OE = encrypter.feed(self.key)
self.OE += encrypter.feed()
if DEBUG>=10:
print("self.OE (hex) = %s" % hexText(self.OE))
# Compute permissions array
permsarr = [
self.P & 0xFF, # store the permission value in the first 32-bits
self.P >> 8 & 0xFF,
self.P >> 16 & 0xFF,
self.P >> 24 & 0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
ord('T'), # 'T' if EncryptMetaData is True (default), 'F' otherwise
ord('a'), # a, d, b are magic values
ord('d'),
ord('b'),
0x01, # trailing zeros will be ignored
0x01,
0x01,
0x01
]
# the permission array should be enrypted in the Perms field
encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(self.key, iv=iv))
self.Perms = encrypter.feed(bytes(permsarr))
self.Perms += encrypter.feed()
if DEBUG>=10:
print("self.Perms (hex) = %s" % hexText(self.Perms))
elif self.revision in (2, 3):
self.O = computeO(self.userPassword, self.ownerPassword, self.revision)
if DEBUG>=10:
print("self.O (as hex) = %s" % hexText(self.O))
#print "\nself.O", self.O, repr(self.O)
self.key = encryptionkey(self.userPassword, self.O, self.P, internalID, revision=self.revision)
if DEBUG>=10:
print("self.key (hex) = %s" % hexText(self.key))
self.U = computeU(self.key, revision=self.revision, documentId=internalID)
if DEBUG>=10:
print("self.U (as hex) = %s" % hexText(self.U))
self.objnum = self.version = None
self.prepared = 1
def register(self, objnum, version):
# enter a new direct object
if not self.prepared:
raise ValueError("encryption not prepared!")
self.objnum = objnum
self.version = version
def info(self):
# the representation of self in file if any (should be None or PDFDict)
if not self.prepared:
raise ValueError("encryption not prepared!")
return StandardEncryptionDictionary(O=self.O, OE=self.OE, U=self.U, UE=self.UE, P=self.P, Perms=self.Perms, revision=self.revision)
class StandardEncryptionDictionary(PDFObject):
__RefOnly__ = 1
def __init__(self, O, OE, U, UE, P, Perms, revision):
self.O, self.OE, self.U, self.UE, self.P, self.Perms = O, OE, U, UE, P, Perms
self.revision = revision
def format(self, document):
# use a dummy document to bypass encryption
from reportlab.pdfbase.pdfdoc import DummyDoc, PDFDictionary, PDFName
dummy = DummyDoc()
dict = {"Filter": PDFName("Standard"),
"O": hexText(self.O),
"U": hexText(self.U),
"P": self.P}
if self.revision == 5:
dict['Length'] = 256
dict['R'] = 5
dict['V'] = 5
dict['O'] = hexText(self.O)
dict['U'] = hexText(self.U)
dict['OE'] = hexText(self.OE)
dict['UE'] = hexText(self.UE)
dict['Perms'] = hexText(self.Perms)
dict['StrF'] = PDFName("StdCF")
dict['StmF'] = PDFName("StdCF")
stdcf = {
"Length": 32,
"AuthEvent": PDFName("DocOpen"),
"CFM": PDFName("AESV3")
}
cf = {
"StdCF": PDFDictionary(stdcf)
}
dict['CF'] = PDFDictionary(cf)
elif self.revision == 3:
dict['Length'] = 128
dict['R'] = 3
dict['V'] = 2
else:
dict['R'] = 2
dict['V'] = 1
pdfdict = PDFDictionary(dict)
return pdfdict.format(dummy)
# from pdf spec
padding = """
28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08
2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A
"""
def hexText(text):
"a legitimate way to show strings in PDF"
return '<%s>' % asNative(hexlify(rawBytes(text))).upper()
def unHexText(hexText):
equalityCheck(hexText[0], '<', 'bad hex text')
equalityCheck(hexText[-1], '>', 'bad hex text')
return unhexlify(hexText[1:-1])
PadString = rawBytes(''.join(chr(int(c, 16)) for c in padding.strip().split()))
def checkRevision(revision):
if revision is None:
strength = rl_config.encryptionStrength
if strength == 40:
revision = 2
elif strength == 128:
revision = 3
elif strength == 256:
if not pyaes:
raise ValueError('strength==256 is not supported as package pyaes is not importable')
revision = 5
else:
raise ValueError('Unknown encryption strength=%s' % repr(strength))
return revision
def encryptionkey(password, OwnerKey, Permissions, FileId1, revision=None):
revision = checkRevision(revision)
# FileId1 is first string of the fileid array
# add padding string
#AR force same as iText example
#Permissions = -1836 #int(Permissions - 2**31)
password = asBytes(password) + PadString
# truncate to 32 bytes
password = password[:32]
# translate permissions to string, low order byte first
p = Permissions# + 2**32L
permissionsString = b""
for i in range(4):
byte = (p & 0xff) # seems to match what iText does
p = p>>8
permissionsString += int2Byte(byte % 256)
hash = md5(asBytes(password))
hash.update(asBytes(OwnerKey))
hash.update(asBytes(permissionsString))
hash.update(asBytes(FileId1))
md5output = hash.digest()
if revision==2:
key = md5output[:5]
elif revision==3: #revision 3 algorithm - loop 50 times
for x in range(50):
md5output = md5(md5output).digest()
key = md5output[:16]
if DEBUG>=10: print('encryptionkey(%s,%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (password, OwnerKey, Permissions, FileId1, revision, key)]))
return key
def computeO(userPassword, ownerPassword, revision):
from reportlab.lib.arciv import ArcIV
#print 'digest of hello is %s' % md5('hello').digest()
assert revision in (2,3), 'Unknown algorithm revision %s' % revision
if not ownerPassword:
ownerPassword = userPassword
ownerPad = asBytes(ownerPassword) + PadString
ownerPad = ownerPad[0:32]
password = asBytes(userPassword) + PadString
userPad = password[:32]
digest = md5(ownerPad).digest()
if DEBUG>=10: print('PadString=%s\nownerPad=%s\npassword=%s\nuserPad=%s\ndigest=%s\nrevision=%s' % (ascii(PadString),ascii(ownerPad),ascii(password),ascii(userPad),ascii(digest),revision))
if revision == 2:
O = ArcIV(digest[:5]).encode(userPad)
elif revision == 3:
for i in range(50):
digest = md5(digest).digest()
digest = digest[:16]
O = userPad
for i in range(20):
thisKey = xorKey(i, digest)
O = ArcIV(thisKey).encode(O)
if DEBUG>=10: print('computeO(%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (userPassword, ownerPassword, revision,O)]))
return O
def computeU(encryptionkey, encodestring=PadString,revision=None,documentId=None):
revision = checkRevision(revision)
from reportlab.lib.arciv import ArcIV
if revision == 2:
result = ArcIV(encryptionkey).encode(encodestring)
elif revision == 3:
assert documentId is not None, "Revision 3 algorithm needs the document ID!"
h = md5(PadString)
h.update(rawBytes(documentId))
tmp = h.digest()
tmp = ArcIV(encryptionkey).encode(tmp)
for n in range(1,20):
thisKey = xorKey(n, encryptionkey)
tmp = ArcIV(thisKey).encode(tmp)
while len(tmp) < 32:
tmp += b'\0'
result = tmp
if DEBUG>=10: print('computeU(%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (encryptionkey, encodestring,revision,documentId,result)]))
return result
def checkU(encryptionkey, U):
decoded = computeU(encryptionkey, U)
#print len(decoded), len(U), len(PadString)
if decoded!=PadString:
if len(decoded)!=len(PadString):
raise ValueError("lengths don't match! (password failed)")
raise ValueError("decode of U doesn't match fixed padstring (password failed)")
def encodePDF(key, objectNumber, generationNumber, string, revision=None):
"Encodes a string or stream"
revision = checkRevision(revision)
#print 'encodePDF (%s, %d, %d, %s)' % (hexText(key), objectNumber, generationNumber, string)
# extend 3 bytes of the object Number, low byte first
if revision in (2,3):
newkey = key
n = objectNumber
for i in range(3):
newkey += int2Byte(n & 0xff)
n = n>>8
# extend 2 bytes of the generationNumber
n = generationNumber
for i in range(2):
newkey += int2Byte(n & 0xff)
n = n>>8
md5output = md5(newkey).digest()
if revision == 2:
key = md5output[:10]
elif revision == 3:
key = md5output #all 16 bytes
from reportlab.lib.arciv import ArcIV
encrypted = ArcIV(key).encode(string)
#print 'encrypted=', hexText(encrypted)
elif revision == 5:
iv = os_urandom(16)
encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv=iv))
# pkcs7 style padding so that the size of the encrypted block is multiple of 16
string_len = len(string)
padding = ""
padding_len = (16 - (string_len % 16)) if string_len > 16 else (16 - string_len)
if padding_len > 0:
padding = chr(padding_len) * padding_len
if isinstance(string, str):
string = (string + padding).encode("utf-8")
else:
string += asBytes(padding)
encrypted = iv + encrypter.feed(string)
encrypted += encrypter.feed()
if DEBUG>=10: print('encodePDF(%s,%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (key, objectNumber, generationNumber, string, revision,encrypted)]))
return encrypted
def equalityCheck(observed,expected,label):
assert observed==expected,'%s\n expected=%s\n observed=%s' % (label,expected,observed)
######################################################################
#
# quick tests of algorithm, should be moved elsewhere
#
######################################################################
def test():
# do a 40 bit example known to work in Acrobat Reader 4.0
enc = StandardEncryption('User','Owner', strength=40)
enc.prepare(None, overrideID='xxxxxxxxxxxxxxxx')
expectedO = '<FA7F558FACF8205D25A7F1ABFA02629F707AE7B0211A2BB26F5DF4C30F684301>'
expectedU = '<09F26CF46190AF8F93B304AD50C16B615DC43C228C9B2D2EA34951A80617B2B1>'
expectedKey = '<BB2C00EB3D>' # 5 byte key = 40 bits
equalityCheck(hexText(enc.O),expectedO, '40 bit O value')
equalityCheck(hexText(enc.U),expectedU, '40 bit U value')
equalityCheck(hexText(enc.key),expectedKey, '40 bit key value')
# now for 128 bit example
enc = StandardEncryption('userpass','ownerpass', strength=128)
enc.prepare(None, overrideID = 'xxxxxxxxxxxxxxxx')
expectedO = '<68E5704AC779A5F0CD89704406587A52F25BF61CADC56A0F8DB6C4DB0052534D>'
expectedU = '<A9AE45CDE827FE0B7D6536267948836A00000000000000000000000000000000>'
expectedKey = '<13DDE7585D9BE366C976DDD56AF541D1>' # 16 byte key = 128 bits
equalityCheck(hexText(enc.O), expectedO, '128 bit O value')
equalityCheck(hexText(enc.U), expectedU, '128 bit U value')
equalityCheck(hexText(enc.key), expectedKey, '128 key value')
######################################################################
#
# These represent the higher level API functions
#
######################################################################
def encryptCanvas(canvas,
userPassword, ownerPassword=None,
canPrint=1, canModify=1, canCopy=1, canAnnotate=1,
strength=40):
"Applies encryption to the document being generated"
enc = StandardEncryption(userPassword, ownerPassword,
canPrint, canModify, canCopy, canAnnotate,
strength=strength)
canvas._doc.encrypt = enc
# Platypus stuff needs work, sadly. I wanted to do it without affecting
# needing changes to latest release.
class EncryptionFlowable(StandardEncryption, Flowable):
"""Drop this in your Platypus story and it will set up the encryption options.
If you do it multiple times, the last one before saving will win."""
def wrap(self, availWidth, availHeight):
return (0,0)
def draw(self):
encryptCanvas(self.canv,
self.userPassword,
self.ownerPassword,
self.canPrint,
self.canModify,
self.canCopy,
self.canAnnotate)
## I am thinking about this one. Needs a change to reportlab to
## work.
def encryptDocTemplate(dt,
userPassword, ownerPassword=None,
canPrint=1, canModify=1, canCopy=1, canAnnotate=1,
strength=40):
"For use in Platypus. Call before build()."
raise Exception("Not implemented yet")
def encryptPdfInMemory(inputPDF,
userPassword, ownerPassword=None,
canPrint=1, canModify=1, canCopy=1, canAnnotate=1,
strength=40):
"""accepts a PDF file 'as a byte array in memory'; return encrypted one.
This is a high level convenience and does not touch the hard disk in any way.
If you are encrypting the same file over and over again, it's better to use
pageCatcher and cache the results."""
try:
from rlextra.pageCatcher.pageCatcher import storeFormsInMemory, restoreFormsInMemory
except ImportError:
raise ImportError('''reportlab.lib.pdfencrypt.encryptPdfInMemory failed because rlextra cannot be imported.
See https://www.reportlab.com/downloads''')
(bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1)
names = list(bboxInfo.keys())
firstPageSize = bboxInfo['PageForms0'][2:]
#now make a new PDF document
buf = BytesIO()
canv = Canvas(buf, pagesize=firstPageSize)
# set a standard ID while debugging
if CLOBBERID:
canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]"
formNames = restoreFormsInMemory(pickledForms, canv)
for formName in formNames:
canv.setPageSize(bboxInfo[formName][2:])
canv.doForm(formName)
canv.showPage()
encryptCanvas(canv,
userPassword, ownerPassword,
canPrint, canModify, canCopy, canAnnotate,
strength=strength)
canv.save()
return buf.getvalue()
def encryptPdfOnDisk(inputFileName, outputFileName,
userPassword, ownerPassword=None,
canPrint=1, canModify=1, canCopy=1, canAnnotate=1,
strength=40):
"Creates encrypted file OUTPUTFILENAME. Returns size in bytes."
inputPDF = open(inputFileName, 'rb').read()
outputPDF = encryptPdfInMemory(inputPDF,
userPassword, ownerPassword,
canPrint, canModify, canCopy, canAnnotate,
strength=strength)
open(outputFileName, 'wb').write(outputPDF)
return len(outputPDF)
def scriptInterp():
sys_argv = sys.argv[:] # copy
usage = """PDFENCRYPT USAGE:
PdfEncrypt encrypts your PDF files.
Line mode usage:
% pdfencrypt.exe pdffile [-o ownerpassword] | [owner ownerpassword],
\t[-u userpassword] | [user userpassword],
\t[-p 1|0] | [printable 1|0],
\t[-m 1|0] | [modifiable 1|0],
\t[-c 1|0] | [copypastable 1|0],
\t[-a 1|0] | [annotatable 1|0],
\t[-s savefilename] | [savefile savefilename],
\t[-v 1|0] | [verbose 1|0],
\t[-e128], [encrypt128],
\t[-h] | [help]
-o or owner set the owner password.
-u or user set the user password.
-p or printable set the printable attribute (must be 1 or 0).
-m or modifiable sets the modifiable attribute (must be 1 or 0).
-c or copypastable sets the copypastable attribute (must be 1 or 0).
-a or annotatable sets the annotatable attribute (must be 1 or 0).
-s or savefile sets the name for the output PDF file
-v or verbose prints useful output to the screen.
(this defaults to 'pdffile_encrypted.pdf').
'-e128' or 'encrypt128' allows you to use 128 bit encryption (in beta).
'-e256' or 'encrypt256' allows you to use 256 bit encryption (in beta AES).
-h or help prints this message.
See PdfEncryptIntro.pdf for more information.
"""
known_modes = ['-o', 'owner',
'-u', 'user',
'-p', 'printable',
'-m', 'modifiable',
'-c', 'copypastable',
'-a', 'annotatable',
'-s', 'savefile',
'-v', 'verbose',
'-h', 'help',
'-e128', 'encrypt128',
'-e256', 'encryptAES',
]
OWNER = ''
USER = ''
PRINTABLE = 1
MODIFIABLE = 1
COPYPASTABLE = 1
ANNOTATABLE = 1
SAVEFILE = 'encrypted.pdf'
#try:
caller = sys_argv[0] # may be required later - eg if called by security.py
argv = list(sys_argv)[1:]
if len(argv)>0:
if argv[0] == '-h' or argv[0] == 'help':
print(usage)
return
if len(argv)<2:
raise ValueError("Must include a filename and one or more arguments!")
if argv[0] not in known_modes:
infile = argv[0]
argv = argv[1:]
if not os.path.isfile(infile):
raise ValueError("Can't open input file '%s'!" % infile)
else:
raise ValueError("First argument must be name of the PDF input file!")
# meaningful name at this stage
STRENGTH = 40
for (s,_a) in ((128,('-e128','encrypt128')),(256,('-e256','encrypt256'))):
for a in _a:
if a in argv:
STRENGTH = s
argv.remove(a)
if ('-v' in argv) or ('verbose' in argv):
if '-v' in argv:
pos = argv.index('-v')
arg = "-v"
elif 'verbose' in argv:
pos = argv.index('verbose')
arg = "verbose"
try:
verbose = int(argv[pos+1])
except:
verbose = 1
argv.remove(argv[pos+1])
argv.remove(arg)
else:
from reportlab.rl_config import verbose
#argument, valid license variable, invalid license variable, text for print
arglist = (('-o', 'OWNER', OWNER, 'Owner password'),
('owner', 'OWNER', OWNER, 'Owner password'),
('-u', 'USER', USER, 'User password'),
('user', 'USER', USER, 'User password'),
('-p', 'PRINTABLE', PRINTABLE, "'Printable'"),
('printable', 'PRINTABLE', PRINTABLE, "'Printable'"),
('-m', 'MODIFIABLE', MODIFIABLE, "'Modifiable'"),
('modifiable', 'MODIFIABLE', MODIFIABLE, "'Modifiable'"),
('-c', 'COPYPASTABLE', COPYPASTABLE, "'Copypastable'"),
('copypastable', 'COPYPASTABLE', COPYPASTABLE, "'Copypastable'"),
('-a', 'ANNOTATABLE', ANNOTATABLE, "'Annotatable'"),
('annotatable', 'ANNOTATABLE', ANNOTATABLE, "'Annotatable'"),
('-s', 'SAVEFILE', SAVEFILE, "Output file"),
('savefile', 'SAVEFILE', SAVEFILE, "Output file"),
)
binaryrequired = ('-p', 'printable', '-m', 'modifiable', 'copypastable', '-c', 'annotatable', '-a')
for thisarg in arglist:
if thisarg[0] in argv:
pos = argv.index(thisarg[0])
if thisarg[0] in binaryrequired:
if argv[pos+1] not in ('1', '0'):
raise ValueError("%s value must be either '1' or '0'!" % thisarg[1])
try:
if argv[pos+1] not in known_modes:
if thisarg[0] in binaryrequired:
exec(thisarg[1] +' = int(argv[pos+1])',vars())
else:
exec(thisarg[1] +' = argv[pos+1]',vars())
if verbose:
print("%s set to: '%s'." % (thisarg[3], argv[pos+1]))
argv.remove(argv[pos+1])
argv.remove(thisarg[0])
except:
raise "Unable to set %s." % thisarg[3]
if verbose>4:
#useful if feeling paranoid and need to double check things at this point...
print("\ninfile:", infile)
print("STRENGTH:", STRENGTH)
print("SAVEFILE:", SAVEFILE)
print("USER:", USER)
print("OWNER:", OWNER)
print("PRINTABLE:", PRINTABLE)
print("MODIFIABLE:", MODIFIABLE)
print("COPYPASTABLE:", COPYPASTABLE)
print("ANNOTATABLE:", ANNOTATABLE)
print("SAVEFILE:", SAVEFILE)
print("VERBOSE:", verbose)
if SAVEFILE == 'encrypted.pdf':
if infile[-4:] == '.pdf' or infile[-4:] == '.PDF':
tinfile = infile[:-4]
else:
tinfile = infile
SAVEFILE = tinfile+"_encrypted.pdf"
filesize = encryptPdfOnDisk(infile, SAVEFILE, USER, OWNER,
PRINTABLE, MODIFIABLE, COPYPASTABLE, ANNOTATABLE,
strength=STRENGTH)
if verbose:
print("wrote output file '%s'(%s bytes)\n owner password is '%s'\n user password is '%s'" % (SAVEFILE, filesize, OWNER, USER))
if len(argv)>0:
raise ValueError("\nUnrecognised arguments : %s\nknown arguments are:\n%s" % (str(argv)[1:-1], known_modes))
else:
print(usage)
def main():
scriptInterp()
if __name__=="__main__": #NO RUNTESTS
a = [x for x in sys.argv if x[:7]=='--debug']
if a:
sys.argv = [x for x in sys.argv if x[:7]!='--debug']
DEBUG = len(a)
if '--test' in sys.argv: test()
else: main()
@@ -0,0 +1,71 @@
"""Helps you output colourised code snippets in ReportLab documents.
Platypus has an 'XPreformatted' flowable for handling preformatted
text, with variations in fonts and colors. If Pygments is installed,
calling 'pygments2xpre' will return content suitable for display in
an XPreformatted object. If it's not installed, you won't get colours.
For a list of available lexers see http://pygments.org/docs/
"""
__all__ = ('pygments2xpre',)
import re
from io import StringIO
def _2xpre(s,styles):
"Helper to transform Pygments HTML output to ReportLab markup"
s = s.replace('<div class="highlight">','')
s = s.replace('</div>','')
s = s.replace('<pre>','')
s = s.replace('</pre>','')
for k,c in styles+[('p','#000000'),('n','#000000'),('err','#000000')]:
s = s.replace('<span class="%s">' % k,'<span color="%s">' % c)
s = re.sub(r'<span class="%s\s+.*">'% k,'<span color="%s">' % c,s)
s = re.sub(r'<span class=".*">','<span color="#0f0f0f">',s)
return s
def pygments2xpre(s, language="python"):
"Return markup suitable for XPreformatted"
try:
from pygments import highlight
from pygments.formatters import HtmlFormatter
except ImportError:
return s
from pygments.lexers import get_lexer_by_name
rconv = lambda x: x
out = StringIO()
l = get_lexer_by_name(language)
h = HtmlFormatter()
highlight(s,l,h,out)
styles = [(cls, style.split(';')[0].split(':')[1].strip())
for cls, (style, ttype, level) in h.class2style.items()
if cls and style and style.startswith('color:')]
return rconv(_2xpre(out.getvalue(),styles))
def convertSourceFiles(filenames):
"Helper function - makes minimal PDF document"
from reportlab.platypus import Paragraph, SimpleDocTemplate, XPreformatted
from reportlab.lib.styles import getSampleStyleSheet
styT=getSampleStyleSheet()["Title"]
styC=getSampleStyleSheet()["Code"]
doc = SimpleDocTemplate("pygments2xpre.pdf")
S = [].append
for filename in filenames:
S(Paragraph(filename,style=styT))
src = open(filename, 'r').read()
fmt = pygments2xpre(src)
S(XPreformatted(fmt, style=styC))
doc.build(S.__self__)
print('saved pygments2xpre.pdf')
if __name__=='__main__':
import sys
filenames = sys.argv[1:]
if not filenames:
print('usage: pygments2xpre.py file1.py [file2.py] [...]')
sys.exit(0)
convertSourceFiles(filenames)
@@ -0,0 +1,366 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/randomtext.py
__version__='3.3.0'
###############################################################################
# generates so-called 'Greek Text' for use in filling documents.
###############################################################################
__doc__="""Like Lorem Ipsum, but more fun and extensible.
This module exposes a function randomText() which generates paragraphs.
These can be used when testing out document templates and stylesheets.
A number of 'themes' are provided - please contribute more!
We need some real Greek text too.
There are currently six themes provided:
STARTUP (words suitable for a business plan - or not as the case may be),
COMPUTERS (names of programming languages and operating systems etc),
BLAH (variations on the word 'blah'),
BUZZWORD (buzzword bingo),
STARTREK (Star Trek),
PRINTING (print-related terms)
PYTHON (snippets and quotes from Monty Python)
CHOMSKY (random lingusitic nonsense)
EXAMPLE USAGE:
from reportlab.lib import randomtext
print randomtext.randomText(randomtext.PYTHON, 10)
This prints a random number of random sentences (up to a limit
of ten) using the theme 'PYTHON'.
"""
#theme one :-)
STARTUP = ['strategic', 'direction', 'proactive', 'venture capital',
'reengineering', 'forecast', 'resources', 'SWOT analysis',
'forward-thinking', 'profit', 'growth', 'doubletalk', 'B2B', 'B2C',
'venture capital', 'IPO', "NASDAQ meltdown - we're all doomed!"]
#theme two - computery things.
COMPUTERS = ['Python', 'Perl', 'Pascal', 'Java', 'Javascript',
'VB', 'Basic', 'LISP', 'Fortran', 'ADA', 'APL', 'C', 'C++',
'assembler', 'Larry Wall', 'Guido van Rossum', 'XML', 'HTML',
'cgi', 'cgi-bin', 'Amiga', 'Macintosh', 'Dell', 'Microsoft',
'firewall', 'server', 'Linux', 'Unix', 'MacOS', 'BeOS', 'AS/400',
'sendmail', 'TCP/IP', 'SMTP', 'RFC822-compliant', 'dynamic',
'Internet', 'A/UX', 'Amiga OS', 'BIOS', 'boot managers', 'CP/M',
'DOS', 'file system', 'FreeBSD', 'Freeware', 'GEOS', 'GNU',
'Hurd', 'Linux', 'Mach', 'Macintosh OS', 'mailing lists', 'Minix',
'Multics', 'NetWare', 'NextStep', 'OS/2', 'Plan 9', 'Realtime',
'UNIX', 'VMS', 'Windows', 'X Windows', 'Xinu', 'security', 'Intel',
'encryption', 'PGP' , 'software', 'ActiveX', 'AppleScript', 'awk',
'BETA', 'COBOL', 'Delphi', 'Dylan', 'Eiffel', 'extreme programming',
'Forth', 'Fortran', 'functional languages', 'Guile', 'format your hard drive',
'Icon', 'IDL', 'Infer', 'Intercal', 'J', 'Java', 'JavaScript', 'CD-ROM',
'JCL', 'Lisp', '"literate programming"', 'Logo', 'MUMPS', 'C: drive',
'Modula-2', 'Modula-3', 'Oberon', 'Occam', 'OpenGL', 'parallel languages',
'Pascal', 'Perl', 'PL/I', 'PostScript', 'Prolog', 'hardware', 'Blue Screen of Death',
'Rexx', 'RPG', 'Scheme', 'scripting languages', 'Smalltalk', 'crash!', 'disc crash',
'Spanner', 'SQL', 'Tcl/Tk', 'TeX', 'TOM', 'Visual', 'Visual Basic', '4GL',
'VRML', 'Virtual Reality Modeling Language', 'difference engine', '...went into "yo-yo mode"',
'Sun', 'Sun Microsystems', 'Hewlett Packard', 'output device',
'CPU', 'memory', 'registers', 'monitor', 'TFT display', 'plasma screen',
'bug report', '"mis-feature"', '...millions of bugs!', 'pizza',
'"illiterate programming"','...lots of pizza!', 'pepperoni pizza',
'coffee', 'Jolt Cola[TM]', 'beer', 'BEER!']
#theme three - 'blah' - for when you want to be subtle. :-)
BLAH = ['Blah', 'BLAH', 'blahblah', 'blahblahblah', 'blah-blah',
'blah!', '"Blah Blah Blah"', 'blah-de-blah', 'blah?', 'blah!!!',
'blah...', 'Blah.', 'blah;', 'blah, Blah, BLAH!', 'Blah!!!']
#theme four - 'buzzword bingo' time!
BUZZWORD = ['intellectual capital', 'market segment', 'flattening',
'regroup', 'platform', 'client-based', 'long-term', 'proactive',
'quality vector', 'out of the loop', 'implement',
'streamline', 'cost-centered', 'phase', 'synergy',
'synergize', 'interactive', 'facilitate',
'appropriate', 'goal-setting', 'empowering', 'low-risk high-yield',
'peel the onion', 'goal', 'downsize', 'result-driven',
'conceptualize', 'multidisciplinary', 'gap analysis', 'dysfunctional',
'networking', 'knowledge management', 'goal-setting',
'mastery learning', 'communication', 'real-estate', 'quarterly',
'scalable', 'Total Quality Management', 'best of breed',
'nimble', 'monetize', 'benchmark', 'hardball',
'client-centered', 'vision statement', 'empowerment',
'lean & mean', 'credibility', 'synergistic',
'backward-compatible', 'hardball', 'stretch the envelope',
'bleeding edge', 'networking', 'motivation', 'best practice',
'best of breed', 'implementation', 'Total Quality Management',
'undefined', 'disintermediate', 'mindset', 'architect',
'gap analysis', 'morale', 'objective', 'projection',
'contribution', 'proactive', 'go the extra mile', 'dynamic',
'world class', 'real estate', 'quality vector', 'credibility',
'appropriate', 'platform', 'projection', 'mastery learning',
'recognition', 'quality', 'scenario', 'performance based',
'solutioning', 'go the extra mile', 'downsize', 'phase',
'networking', 'experiencing slippage', 'knowledge management',
'high priority', 'process', 'ethical', 'value-added', 'implement',
're-factoring', 're-branding', 'embracing change']
#theme five - Star Trek
STARTREK = ['Starfleet', 'Klingon', 'Romulan', 'Cardassian', 'Vulcan',
'Benzite', 'IKV Pagh', 'emergency transponder', 'United Federation of Planets',
'Bolian', "K'Vort Class Bird-of-Prey", 'USS Enterprise', 'USS Intrepid',
'USS Reliant', 'USS Voyager', 'Starfleet Academy', 'Captain Picard',
'Captain Janeway', 'Tom Paris', 'Harry Kim', 'Counsellor Troi',
'Lieutenant Worf', 'Lieutenant Commander Data', 'Dr. Beverly Crusher',
'Admiral Nakamura', 'Irumodic Syndrome', 'Devron system', 'Admiral Pressman',
'asteroid field', 'sensor readings', 'Binars', 'distress signal', 'shuttlecraft',
'cloaking device', 'shuttle bay 2', 'Dr. Pulaski', 'Lwaxana Troi', 'Pacifica',
'William Riker', "Chief O'Brian", 'Soyuz class science vessel', 'Wolf-359',
'Galaxy class vessel', 'Utopia Planitia yards', 'photon torpedo', 'Archer IV',
'quantum flux', 'spacedock', 'Risa', 'Deep Space Nine', 'blood wine',
'quantum torpedoes', 'holodeck', 'Romulan Warbird', 'Betazoid', 'turbolift', 'battle bridge',
'Memory Alpha', '...with a phaser!', 'Romulan ale', 'Ferrengi', 'Klingon opera',
'Quark', 'wormhole', 'Bajoran', 'cruiser', 'warship', 'battlecruiser', '"Intruder alert!"',
'scout ship', 'science vessel', '"Borg Invasion imminent!" ', '"Abandon ship!"',
'Red Alert!', 'warp-core breech', '"All hands abandon ship! This is not a drill!"']
#theme six - print-related terms
PRINTING = ['points', 'picas', 'leading', 'kerning', 'CMYK', 'offset litho',
'type', 'font family', 'typography', 'type designer',
'baseline', 'white-out type', 'WOB', 'bicameral', 'bitmap',
'blockletter', 'bleed', 'margin', 'body', 'widow', 'orphan',
'cicero', 'cursive', 'letterform', 'sidehead', 'dingbat', 'leader',
'DPI', 'drop-cap', 'paragraph', 'En', 'Em', 'flush left', 'left justified',
'right justified', 'centered', 'italic', 'Latin letterform', 'ligature',
'uppercase', 'lowercase', 'serif', 'sans-serif', 'weight', 'type foundry',
'fleuron', 'folio', 'gutter', 'whitespace', 'humanist letterform', 'caption',
'page', 'frame', 'ragged setting', 'flush-right', 'rule', 'drop shadows',
'prepress', 'spot-colour', 'duotones', 'colour separations', 'four-colour printing',
'Pantone[TM]', 'service bureau', 'imagesetter']
#it had to be done!...
#theme seven - the "full Monty"!
PYTHON = ['Good evening ladies and Bruces','I want to buy some cheese', 'You do have some cheese, do you?',
"Of course sir, it's a cheese shop sir, we've got...",'discipline?... naked? ... With a melon!?',
'The Church Police!!' , "There's a dead bishop on the landing", 'Would you like a twist of lemming sir?',
'"Conquistador Coffee brings a new meaning to the word vomit"','Your lupins please',
'Crelm Toothpaste, with the miracle ingredient Fraudulin',
"Well there's the first result and the Silly Party has held Leicester.",
'Hello, I would like to buy a fish license please', "Look, it's people like you what cause unrest!",
"When we got home, our Dad would thrash us to sleep with his belt!", 'Luxury', "Gumby Brain Specialist",
"My brain hurts!!!", "My brain hurts too.", "How not to be seen",
"In this picture there are 47 people. None of them can be seen",
"Mrs Smegma, will you stand up please?",
"Mr. Nesbitt has learned the first lesson of 'Not Being Seen', not to stand up.",
"My hovercraft is full of eels", "Ah. You have beautiful thighs.", "My nipples explode with delight",
"Drop your panties Sir William, I cannot wait 'til lunchtime",
"I'm a completely self-taught idiot.", "I always wanted to be a lumberjack!!!",
"Told you so!! Oh, coitus!!", "",
"Nudge nudge?", "Know what I mean!", "Nudge nudge, nudge nudge?", "Say no more!!",
"Hello, well it's just after 8 o'clock, and time for the penguin on top of your television set to explode",
"Oh, intercourse the penguin!!", "Funny that penguin being there, isn't it?",
"I wish to register a complaint.", "Now that's what I call a dead parrot", "Pining for the fjords???",
"No, that's not dead, it's ,uhhhh, resting", "This is an ex-parrot!!",
"That parrot is definitely deceased.", "No, no, no - it's spelt Raymond Luxury Yach-t, but it's pronounced 'Throatwobbler Mangrove'.",
"You're a very silly man and I'm not going to interview you.", "No Mungo... never kill a customer."
"And I'd like to conclude by putting my finger up my nose",
"egg and Spam", "egg bacon and Spam", "egg bacon sausage and Spam", "Spam bacon sausage and Spam",
"Spam egg Spam Spam bacon and Spam", "Spam sausage Spam Spam Spam bacon Spam tomato and Spam",
"Spam Spam Spam egg and Spam", "Spam Spam Spam Spam Spam Spam baked beans Spam Spam Spam",
"Spam!!", "I don't like Spam!!!", "You can't have egg, bacon, Spam and sausage without the Spam!",
"I'll have your Spam. I Love it!",
"I'm having Spam Spam Spam Spam Spam Spam Spam baked beans Spam Spam Spam and Spam",
"Have you got anything without Spam?", "There's Spam egg sausage and Spam, that's not got much Spam in it.",
"No one expects the Spanish Inquisition!!", "Our weapon is surprise, surprise and fear!",
"Get the comfy chair!", "Amongst our weaponry are such diverse elements as: fear, surprise, ruthless efficiency, an almost fanatical devotion to the Pope, and nice red uniforms - Oh damn!",
"Nobody expects the... Oh bugger!", "What swims in the sea and gets caught in nets? Henri Bergson?",
"Goats. Underwater goats with snorkels and flippers?", "A buffalo with an aqualung?",
"Dinsdale was a looney, but he was a happy looney.", "Dinsdale!!",
"The 127th Upper-Class Twit of the Year Show", "What a great Twit!",
"thought by many to be this year's outstanding twit",
"...and there's a big crowd here today to see these prize idiots in action.",
"And now for something completely different.", "Stop that, it's silly",
"We interrupt this program to annoy you and make things generally irritating",
"This depraved and degrading spectacle is going to stop right now, do you hear me?",
"Stop right there!", "This is absolutely disgusting and I'm not going to stand for it",
"I object to all this sex on the television. I mean, I keep falling off",
"Right! Stop that, it's silly. Very silly indeed", "Very silly indeed", "Lemon curry?",
"And now for something completely different, a man with 3 buttocks",
"I've heard of unisex, but I've never had it", "That's the end, stop the program! Stop it!"]
leadins=[
"To characterize a linguistic level L,",
"On the other hand,",
"This suggests that",
"It appears that",
"Furthermore,",
"We will bring evidence in favor of the following thesis: ",
"To provide a constituent structure for T(Z,K),",
"From C1, it follows that",
"For any transformation which is sufficiently diversified in application to be of any interest,",
"Analogously,",
"Clearly,",
"Note that",
"Of course,",
"Suppose, for instance, that",
"Thus",
"With this clarification,",
"Conversely,",
"We have already seen that",
"By combining adjunctions and certain deformations,",
"I suggested that these results would follow from the assumption that",
"If the position of the trace in (99c) were only relatively inaccessible to movement,",
"However, this assumption is not correct, since",
"Comparing these examples with their parasitic gap counterparts in (96) and (97), we see that",
"In the discussion of resumptive pronouns following (81),",
"So far,",
"Nevertheless,",
"For one thing,",
"Summarizing, then, we assume that",
"A consequence of the approach just outlined is that",
"Presumably,",
"On our assumptions,",
"It may be, then, that",
"It must be emphasized, once again, that",
"Let us continue to suppose that",
"Notice, incidentally, that",
"A majority of informed linguistic specialists agree that",
"There is also a different approach to the [unification] problem,",
"This approach divorces the cognitive sciences from a biological setting,",
"The approach relies on the \"Turing Test,\" devised by mathematician Alan Turing,",
"Adopting this approach,",
"There is no fact, no meaningful question to be answered,",
"Another superficial similarity is the interest in simulation of behavior,",
"A lot of sophistication has been developed about the utilization of machines for complex purposes,",
]
subjects = [
"the notion of level of grammaticalness",
"a case of semigrammaticalness of a different sort",
"most of the methodological work in modern linguistics",
"a subset of English sentences interesting on quite independent grounds",
"the natural general principle that will subsume this case",
"an important property of these three types of EC",
"any associated supporting element",
"the appearance of parasitic gaps in domains relatively inaccessible to ordinary extraction",
"the speaker-hearer's linguistic intuition",
"the descriptive power of the base component",
"the earlier discussion of deviance",
"this analysis of a formative as a pair of sets of features",
"this selectionally introduced contextual feature",
"a descriptively adequate grammar",
"the fundamental error of regarding functional notions as categorial",
"relational information",
"the systematic use of complex symbols",
"the theory of syntactic features developed earlier",
]
verbs= [
"can be defined in such a way as to impose",
"delimits",
"suffices to account for",
"cannot be arbitrary in",
"is not subject to",
"does not readily tolerate",
"raises serious doubts about",
"is not quite equivalent to",
"does not affect the structure of",
"may remedy and, at the same time, eliminate",
"is not to be considered in determining",
"is to be regarded as",
"is unspecified with respect to",
"is, apparently, determined by",
"is necessary to impose an interpretation on",
"appears to correlate rather closely with",
"is rather different from",
]
objects = [
"problems of phonemic and morphological analysis.",
"a corpus of utterance tokens upon which conformity has been defined by the paired utterance test.",
"the traditional practice of grammarians.",
"the levels of acceptability from fairly high (e.g. (99a)) to virtual gibberish (e.g. (98d)).",
"a stipulation to place the constructions into these various categories.",
"a descriptive fact.",
"a parasitic gap construction.",
"the extended c-command discussed in connection with (34).",
"the ultimate standard that determines the accuracy of any proposed grammar.",
"the system of base rules exclusive of the lexicon.",
"irrelevant intervening contexts in selectional rules.",
"nondistinctness in the sense of distinctive feature theory.",
"a general convention regarding the forms of the grammar.",
"an abstract underlying order.",
"an important distinction in language use.",
"the requirement that branching is not tolerated within the dominance scope of a complex symbol.",
"the strong generative capacity of the theory.",
]
def format_wisdom(text,line_length=72):
try:
import textwrap
return textwrap.fill(text, line_length)
except:
return text
def chomsky(times = 1):
if not isinstance(times, int):
return format_wisdom(__doc__)
import random
prevparts = []
newparts = []
output = []
for i in range(times):
for partlist in (leadins, subjects, verbs, objects):
while 1:
part = random.choice(partlist)
if part not in prevparts:
break
newparts.append(part)
output.append(' '.join(newparts))
prevparts = newparts
newparts = []
return format_wisdom(' '.join(output))
def randomText(theme=STARTUP, sentences=5):
#this may or may not be appropriate in your company
if type(theme)==type(''):
if theme.lower()=='chomsky': return chomsky(sentences)
elif theme.upper() in ('STARTUP','COMPUTERS','BLAH','BUZZWORD','STARTREK','PRINTING','PYTHON'):
theme = globals()[theme.upper()]
else:
raise ValueError('Unknown theme "%s"' % theme)
from random import randint, choice
RANDOMWORDS = theme
#sentences = 5
output = ""
for sentenceno in range(randint(1,sentences)):
output = output + 'Blah'
for wordno in range(randint(10,25)):
if randint(0,4)==0:
word = choice(RANDOMWORDS)
else:
word = 'blah'
output = output + ' ' +word
output = output+'. '
return output
if __name__=='__main__':
import sys, random
from reportlab.rl_config import invariant as rl_invariant
if rl_invariant:
random.seed(1854640162)
print(f'{" ".join((str(random.randrange(100)) for _ in range(10)))}')
argv = sys.argv[1:]
if argv:
theme = argv.pop(0)
if argv:
sentences = int(argv.pop(0))
else:
sentences = 5
try:
print(randomText(theme,sentences))
except:
sys.stderr.write("Usage: randomtext.py [theme [#sentences]]\n")
sys.stderr.write(" theme in chomsky|STARTUP|COMPUTERS|BLAH|BUZZWORD|STARTREK|PRINTING|PYTHON\n")
raise
else:
print(chomsky(5))
@@ -0,0 +1,361 @@
#this is the interface module that imports all from the C extension _rl_accel
_c_funcs = {}
_py_funcs = {}
### NOTE! FP_STR SHOULD PROBABLY ALWAYS DO A PYTHON STR() CONVERSION ON ARGS
### IN CASE THEY ARE "LAZY OBJECTS". ACCELLERATOR DOESN'T DO THIS (YET)
__all__ = list(filter(None,'''
fp_str
unicode2T1
instanceStringWidthT1
instanceStringWidthTTF
asciiBase85Encode
asciiBase85Decode
escapePDF
sameFrag
calcChecksum
add32
hex32
'''.split()))
import reportlab
testing = getattr(reportlab,'_rl_testing',False)
del reportlab
for fn in __all__:
D={}
try:
exec('from _rl_accel import %s as f' % fn,D)
_c_funcs[fn] = D['f']
if testing: _py_funcs[fn] = None
except ImportError:
_py_funcs[fn] = None
del D
if _py_funcs:
from reportlab.lib.utils import isUnicode, isSeq, rawBytes, asNative, asBytes
from math import log
from struct import unpack
if 'fp_str' in _py_funcs:
_log_10 = lambda x,log=log,_log_e_10=log(10.0): log(x)/_log_e_10
_fp_fmts = "%.0f", "%.1f", "%.2f", "%.3f", "%.4f", "%.5f", "%.6f"
def _py_fp_str(*a):
'''convert separate arguments (or single sequence arg) into space separated numeric strings'''
if len(a)==1 and isSeq(a[0]): a = a[0]
s = []
A = s.append
for i in a:
sa =abs(i)
if sa<=1e-7: A('0')
else:
l = sa<=1 and 6 or min(max(0,(6-int(_log_10(sa)))),6)
n = _fp_fmts[l]%i
if l:
j = len(n)
while j:
j -= 1
if n[j]!='0':
if n[j]!='.': j += 1
break
n = n[:j]
A((n[0]!='0' or len(n)==1) and n or n[1:])
return ' '.join(s)
#hack test for comma users
if ',' in _py_fp_str(0.25):
_FP_STR = _fp_str
def __py_fp_str(*a):
return _FP_STR(*a).replace(',','.')
_py_funcs['fp_str'] = _py_fp_str
if 'unicode2T1' in _py_funcs:
def _py_unicode2T1(utext,fonts):
'''return a list of (font,string) pairs representing the unicode text'''
R = []
font, fonts = fonts[0], fonts[1:]
enc = font.encName
if 'UCS-2' in enc:
enc = 'UTF16'
while utext:
try:
if isUnicode(utext):
s = utext.encode(enc)
else:
s = utext
R.append((font,s))
break
except UnicodeEncodeError as e:
i0, il = e.args[2:4]
if i0:
R.append((font,utext[:i0].encode(enc)))
if fonts:
R.extend(_py_unicode2T1(utext[i0:il],fonts))
else:
R.append((font._notdefFont,font._notdefChar*(il-i0)))
utext = utext[il:]
return R
_py_funcs['unicode2T1'] = _py_unicode2T1
if 'instanceStringWidthT1' in _py_funcs:
def _py_instanceStringWidthT1(self, text, size, encoding='utf8'):
"""This is the "purist" approach to width"""
if not isUnicode(text): text = text.decode(encoding)
return sum((sum(map(f.widths.__getitem__,t)) for f, t in _py_unicode2T1(text,[self]+self.substitutionFonts)))*0.001*size
_py_funcs['instanceStringWidthT1'] = _py_instanceStringWidthT1
if 'instanceStringWidthTTF' in _py_funcs:
def _py_instanceStringWidthTTF(self, text, size, encoding='utf8'):
"Calculate text width"
if not isUnicode(text):
text = text.decode(encoding or 'utf8')
g = self.face.charWidths.get
dw = self.face.defaultWidth
return 0.001*size*sum((g(ord(u),dw) for u in text))
_py_funcs['instanceStringWidthTTF'] = _py_instanceStringWidthTTF
if 'hex32' in _py_funcs:
def _py_hex32(i):
return '0X%8.8X' % (int(i)&0xFFFFFFFF)
_py_funcs['hex32'] = _py_hex32
if 'add32' in _py_funcs:
def add32(x, y):
"Calculate (x + y) modulo 2**32"
return (x+y) & 0xFFFFFFFF
_py_funcs['add32'] = add32
if 'calcChecksum' in _py_funcs:
def _py_calcChecksum(data):
"""Calculates TTF-style checksums"""
data = rawBytes(data)
if len(data)&3: data = data + (4-(len(data)&3))*b"\0"
return sum(unpack(">%dl" % (len(data)>>2), data)) & 0xFFFFFFFF
_py_funcs['calcChecksum'] = _py_calcChecksum
if 'escapePDF' in _py_funcs:
_ESCAPEDICT={}
for c in range(256):
if c<32 or c>=127:
_ESCAPEDICT[c]= '\\%03o' % c
elif c in (ord('\\'),ord('('),ord(')')):
_ESCAPEDICT[c] = '\\'+chr(c)
else:
_ESCAPEDICT[c] = chr(c)
del c
#Michael Hudson donated this
def _py_escapePDF(s):
r = []
for c in s:
if not type(c) is int:
c = ord(c)
r.append(_ESCAPEDICT[c])
return ''.join(r)
_py_funcs['escapePDF'] = _py_escapePDF
if 'asciiBase85Encode' in _py_funcs:
def _py_asciiBase85Encode(input):
"""Encodes input using ASCII-Base85 coding.
This is a compact encoding used for binary data within
a PDF file. Four bytes of binary data become five bytes of
ASCII. This is the default method used for encoding images."""
doOrd = isUnicode(input)
# special rules apply if not a multiple of four bytes.
whole_word_count, remainder_size = divmod(len(input), 4)
cut = 4 * whole_word_count
body, lastbit = input[0:cut], input[cut:]
out = [].append
for i in range(whole_word_count):
offset = i*4
b1 = body[offset]
b2 = body[offset+1]
b3 = body[offset+2]
b4 = body[offset+3]
if doOrd:
b1 = ord(b1)
b2 = ord(b2)
b3 = ord(b3)
b4 = ord(b4)
if b1<128:
num = (((((b1<<8)|b2)<<8)|b3)<<8)|b4
else:
num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4
if num == 0:
#special case
out('z')
else:
#solve for five base-85 numbers
temp, c5 = divmod(num, 85)
temp, c4 = divmod(temp, 85)
temp, c3 = divmod(temp, 85)
c1, c2 = divmod(temp, 85)
assert ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 == num, 'dodgy code!'
out(chr(c1+33))
out(chr(c2+33))
out(chr(c3+33))
out(chr(c4+33))
out(chr(c5+33))
# now we do the final bit at the end. I repeated this separately as
# the loop above is the time-critical part of a script, whereas this
# happens only once at the end.
#encode however many bytes we have as usual
if remainder_size > 0:
lastbit += (4-len(lastbit))*('\0' if doOrd else b'\000')
b1 = lastbit[0]
b2 = lastbit[1]
b3 = lastbit[2]
b4 = lastbit[3]
if doOrd:
b1 = ord(b1)
b2 = ord(b2)
b3 = ord(b3)
b4 = ord(b4)
num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4
#solve for c1..c5
temp, c5 = divmod(num, 85)
temp, c4 = divmod(temp, 85)
temp, c3 = divmod(temp, 85)
c1, c2 = divmod(temp, 85)
#print 'encoding: %d %d %d %d -> %d -> %d %d %d %d %d' % (
# b1,b2,b3,b4,num,c1,c2,c3,c4,c5)
lastword = chr(c1+33) + chr(c2+33) + chr(c3+33) + chr(c4+33) + chr(c5+33)
#write out most of the bytes.
out(lastword[0:remainder_size + 1])
#terminator code for ascii 85
out('~>')
return ''.join(out.__self__)
_py_funcs['asciiBase85Encode'] = _py_asciiBase85Encode
if 'asciiBase85Decode' in _py_funcs:
def _py_asciiBase85Decode(input):
"""Decodes input using ASCII-Base85 coding.
This is not normally used - Acrobat Reader decodes for you
- but a round trip is essential for testing."""
#strip all whitespace
stripped = ''.join(asNative(input).split())
#check end
assert stripped[-2:] == '~>', 'Invalid terminator for Ascii Base 85 Stream'
stripped = stripped[:-2] #chop off terminator
#may have 'z' in it which complicates matters - expand them
stripped = stripped.replace('z','!!!!!')
# special rules apply if not a multiple of five bytes.
whole_word_count, remainder_size = divmod(len(stripped), 5)
#print '%d words, %d leftover' % (whole_word_count, remainder_size)
#assert remainder_size != 1, 'invalid Ascii 85 stream!'
cut = 5 * whole_word_count
body, lastbit = stripped[0:cut], stripped[cut:]
out = [].append
for i in range(whole_word_count):
offset = i*5
c1 = ord(body[offset]) - 33
c2 = ord(body[offset+1]) - 33
c3 = ord(body[offset+2]) - 33
c4 = ord(body[offset+3]) - 33
c5 = ord(body[offset+4]) - 33
num = ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5
temp, b4 = divmod(num,256)
temp, b3 = divmod(temp,256)
b1, b2 = divmod(temp, 256)
assert num == 16777216 * b1 + 65536 * b2 + 256 * b3 + b4, 'dodgy code!'
out(chr(b1))
out(chr(b2))
out(chr(b3))
out(chr(b4))
#decode however many bytes we have as usual
if remainder_size > 0:
while len(lastbit) < 5:
lastbit = lastbit + '!'
c1 = ord(lastbit[0]) - 33
c2 = ord(lastbit[1]) - 33
c3 = ord(lastbit[2]) - 33
c4 = ord(lastbit[3]) - 33
c5 = ord(lastbit[4]) - 33
num = (((85*c1+c2)*85+c3)*85+c4)*85 + (c5
+(0,0,0xFFFFFF,0xFFFF,0xFF)[remainder_size])
temp, b4 = divmod(num,256)
temp, b3 = divmod(temp,256)
b1, b2 = divmod(temp, 256)
assert num == 16777216 * b1 + 65536 * b2 + 256 * b3 + b4, 'dodgy code!'
#print 'decoding: %d %d %d %d %d -> %d -> %d %d %d %d' % (
# c1,c2,c3,c4,c5,num,b1,b2,b3,b4)
#the last character needs 1 adding; the encoding loses
#data by rounding the number to x bytes, and when
#divided repeatedly we get one less
if remainder_size == 2:
lastword = chr(b1)
elif remainder_size == 3:
lastword = chr(b1) + chr(b2)
elif remainder_size == 4:
lastword = chr(b1) + chr(b2) + chr(b3)
else:
lastword = ''
out(lastword)
r = ''.join(out.__self__)
return asBytes(r,enc='latin1')
_py_funcs['asciiBase85Decode'] = _py_asciiBase85Decode
if 'sameFrag' in _py_funcs:
def _py_sameFrag(f,g, _cmp=('fontName', 'fontSize', 'textColor', 'rise', 'us_lines', 'link', "backColor", "nobr")):
fdict = f.__dict__
gdict = g.__dict__
if 'cbDefn' in fdict or 'lineBreak' in fdict or 'cbDefn' in gdict or 'lineBreak' in gdict: return 0
fg = fdict.get
gg = gdict.get
return [fg(k) for k in _cmp]==[gg(k) for k in _cmp]
_py_funcs['sameFrag'] = _py_sameFrag
G=globals()
for fn in __all__:
f = _c_funcs[fn] if fn in _c_funcs else _py_funcs[fn]
if not f:
raise RuntimeError('function %s is not properly defined' % fn)
G[fn] = f
del fn, f, G
if __name__=='__main__':
import sys, subprocess
funclist = ','.join("""add32 asciiBase85Decode asciiBase85Encode
calcChecksum escapePDF fp_str hex32
instanceStringWidthT1 instanceStringWidthTTF
sameFrag unicode2T1""".split())
for cmd,xs in (
("instanceStringWidthTTF(font,text,10)",("font=TTFont('Vera','Vera.ttf')","text='abcde fghi . jkl ; mno'")),
("instanceStringWidthT1(font,'abcde fghi . jkl ; mno',10)",
("fonts=[getFont('Helvetica')]+getFont('Helvetica').substitutionFonts""",
"font=fonts[0]","text='abcde fghi . jkl ; mno'")),
("escapePDF(text)",("text='\x11abcdefghijkl\xf3'",)),
("fp_str(1.23456,2.7891666,2,13,11)",()),
("calcChecksum(text)",("text=5*' abcdefgiijklMnoPQrstuvwxyz1234567890'",)),
("hex32(0x12345678)",()),
("add32(0x12345678,123456789)",()),
("asciiBase85Encode(src)",("src=5*' abcdefgiijklMnoPQrstuvwxyz1234567890'",)),
("asciiBase85Decode(_85text)",("_85text=asciiBase85Encode(5*' abcdefgiijklMnoPQrstuvwxyz1234567890')",)),
):
for modname in '_rl_accel','reportlab.lib.rl_accel':
s = ';'.join((
"from reportlab.pdfbase.pdfmetrics import getFont",
"from reportlab.pdfbase.ttfonts import TTFont",
f"from {modname} import {funclist}",
)+xs)
if modname!='_rl_accel':
s = "import sys;sys.modules['_rl_accel']=None;"+s
print(f'timing {modname} {cmd}')
for i in range(2):
subprocess.check_call([sys.executable,'-mtimeit','-s',s,cmd])
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,38 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
# $URI:$
__version__='3.3.0'
__doc__='''Helper for the test suite - determines where to write output.
When our test suite runs as source, a script "test_foo.py" will typically
create "test_foo.pdf" alongside it. But if you are testing a package of
compiled code inside a zip archive, this won't work. This determines
where to write test suite output, creating a subdirectory of /tmp/ or
whatever if needed.
'''
_rl_tempdir=None
__all__ = ('get_rl_tempdir', 'get_rl_tempdir')
import os, tempfile
def _rl_getuid():
if hasattr(os,'getuid'):
return os.getuid()
else:
return ''
def get_rl_tempdir(*subdirs):
global _rl_tempdir
if _rl_tempdir is None:
_rl_tempdir = os.path.join(tempfile.gettempdir(),'ReportLab_tmp%s' % str(_rl_getuid()))
d = _rl_tempdir
if subdirs: d = os.path.join(*((d,)+subdirs))
try:
os.makedirs(d)
except:
pass
return d
def get_rl_tempfile(fn=None):
if not fn:
fn = tempfile.mktemp()
return os.path.join(get_rl_tempdir(),fn)
@@ -0,0 +1,449 @@
"""Very simple and fast XML parser, used for intra-paragraph text.
Devised by Aaron Watters in the bad old days before Python had fast
parsers available. Constructs the lightest possible in-memory
representation; parses most files we have seen in pure python very
quickly.
The output structure is the same as the one produced by pyRXP,
our validating C-based parser, which was written later. It will
use pyRXP if available.
This is used to parse intra-paragraph markup.
Example parse::
<this type="xml">text <b>in</b> xml</this>
( "this",
{"type": "xml"},
[ "text ",
("b", None, ["in"], None),
" xml"
]
None )
{ 0: "this"
"type": "xml"
1: ["text ",
{0: "b", 1:["in"]},
" xml"]
}
Ie, xml tag translates to a tuple:
(name, dictofattributes, contentlist, miscellaneousinfo)
where miscellaneousinfo can be anything, (but defaults to None)
(with the intention of adding, eg, line number information)
special cases: name of "" means "top level, no containing tag".
Top level parse always looks like this::
("", list, None, None)
contained text of None means <simple_tag/>
In order to support stuff like::
<this></this><one></one>
AT THE MOMENT &amp; ETCETERA ARE IGNORED. THEY MUST BE PROCESSED
IN A POST-PROCESSING STEP.
PROLOGUES ARE NOT UNDERSTOOD. OTHER STUFF IS PROBABLY MISSING.
"""
RequirePyRXP = 0 # set this to 1 to disable the nonvalidating fallback parser.
try:
#raise ImportError, "dummy error"
simpleparse = 0
import pyRXPU
def warnCB(s):
print(s)
pyRXP_parser = pyRXPU.Parser(
ErrorOnValidityErrors=1,
NoNoDTDWarning=1,
ExpandCharacterEntities=1,
ExpandGeneralEntities=1,
warnCB = warnCB,
srcName='string input',
ReturnUTF8 = 0,
)
def parsexml(xmlText, oneOutermostTag=0,eoCB=None,entityReplacer=None,parseOpts={}):
pyRXP_parser.eoCB = eoCB
p = pyRXP_parser.parse(xmlText,**parseOpts)
return oneOutermostTag and p or ('',None,[p],None)
except ImportError:
simpleparse = 1
class smartDecode:
@staticmethod
def __call__(s):
from charset_normalizer import detect
def __call__(s):
if isinstance(s,str): return s
cdd = detect(s)
return s.decode(cdd["encoding"])
smartDecode.__class__.__call__ = staticmethod(__call__)
return __call__(s)
smartDecode = smartDecode()
NONAME = ""
NAMEKEY = 0
CONTENTSKEY = 1
CDATAMARKER = "<![CDATA["
LENCDATAMARKER = len(CDATAMARKER)
CDATAENDMARKER = "]]>"
replacelist = [("&lt;", "<"), ("&gt;", ">"), ("&amp;", "&")] # amp must be last
#replacelist = []
def unEscapeContentList(contentList):
result = []
for e in contentList:
if "&" in e:
for (old, new) in replacelist:
e = e.replace(old, new)
result.append(e)
return result
def parsexmlSimple(xmltext, oneOutermostTag=0,eoCB=None,entityReplacer=unEscapeContentList):
"""official interface: discard unused cursor info"""
if RequirePyRXP:
raise ImportError("pyRXP not found, fallback parser disabled")
(result, cursor) = parsexml0(xmltext,entityReplacer=entityReplacer)
if oneOutermostTag:
return result[2][0]
else:
return result
if simpleparse:
parsexml = parsexmlSimple
def parseFile(filename):
raw = open(filename, 'r').read()
return parsexml(raw)
verbose = 0
def skip_prologue(text, cursor):
"""skip any prologue found after cursor, return index of rest of text"""
### NOT AT ALL COMPLETE!!! definitely can be confused!!!
prologue_elements = ("!DOCTYPE", "?xml", "!--")
done = None
while done is None:
#print "trying to skip:", repr(text[cursor:cursor+20])
openbracket = text.find("<", cursor)
if openbracket<0: break
past = openbracket+1
found = None
for e in prologue_elements:
le = len(e)
if text[past:past+le]==e:
found = 1
cursor = text.find(">", past)
if cursor<0:
raise ValueError("can't close prologue %r" % e)
cursor = cursor+1
if found is None:
done=1
#print "done skipping"
return cursor
def parsexml0(xmltext, startingat=0, toplevel=1,
# snarf in some globals
entityReplacer=unEscapeContentList,
#len=len, None=None
#LENCDATAMARKER=LENCDATAMARKER, CDATAMARKER=CDATAMARKER
):
"""simple recursive descent xml parser...
return (dictionary, endcharacter)
special case: comment returns (None, endcharacter)"""
xmltext = smartDecode(xmltext)
#print "parsexml0", repr(xmltext[startingat: startingat+10])
# DEFAULTS
NameString = NONAME
ContentList = AttDict = ExtraStuff = None
if toplevel is not None:
#if verbose: print "at top level"
#if startingat!=0:
# raise ValueError, "have to start at 0 for top level!"
xmltext = xmltext.strip()
cursor = startingat
#look for interesting starting points
firstbracket = xmltext.find("<", cursor)
afterbracket2char = xmltext[firstbracket+1:firstbracket+3]
#print "a", repr(afterbracket2char)
#firstampersand = xmltext.find("&", cursor)
#if firstampersand>0 and firstampersand<firstbracket:
# raise ValueError, "I don't handle ampersands yet!!!"
docontents = 1
if firstbracket<0:
# no tags
#if verbose: print "no tags"
if toplevel is not None:
#D = {NAMEKEY: NONAME, CONTENTSKEY: [xmltext[cursor:]]}
ContentList = [xmltext[cursor:]]
if entityReplacer: ContentList = entityReplacer(ContentList)
return (NameString, AttDict, ContentList, ExtraStuff), len(xmltext)
else:
raise ValueError("no tags at non-toplevel %s" % repr(xmltext[cursor:cursor+20]))
#D = {}
L = []
# look for start tag
# NEED to force always outer level is unnamed!!!
#if toplevel and firstbracket>0:
#afterbracket2char = xmltext[firstbracket:firstbracket+2]
if toplevel is not None:
#print "toplevel with no outer tag"
NameString = name = NONAME
cursor = skip_prologue(xmltext, cursor)
#break
elif firstbracket<0:
raise ValueError("non top level entry should be at start tag: %s" % repr(xmltext[:10]))
# special case: CDATA
elif afterbracket2char=="![" and xmltext[firstbracket:firstbracket+9]=="<![CDATA[":
#print "in CDATA", cursor
# skip straight to the close marker
startcdata = firstbracket+9
endcdata = xmltext.find(CDATAENDMARKER, startcdata)
if endcdata<0:
raise ValueError("unclosed CDATA %s" % repr(xmltext[cursor:cursor+20]))
NameString = CDATAMARKER
ContentList = [xmltext[startcdata: endcdata]]
cursor = endcdata+len(CDATAENDMARKER)
docontents = None
# special case COMMENT
elif afterbracket2char=="!-" and xmltext[firstbracket:firstbracket+4]=="<!--":
#print "in COMMENT"
endcommentdashes = xmltext.find("--", firstbracket+4)
if endcommentdashes<firstbracket:
raise ValueError("unterminated comment %s" % repr(xmltext[cursor:cursor+20]))
endcomment = endcommentdashes+2
if xmltext[endcomment]!=">":
raise ValueError("invalid comment: contains double dashes %s" % repr(xmltext[cursor:cursor+20]))
return (None, endcomment+1) # shortcut exit
else:
# get the rest of the tag
#if verbose: print "parsing start tag"
# make sure the tag isn't in doublequote pairs
closebracket = xmltext.find(">", firstbracket)
noclose = closebracket<0
startsearch = closebracket+1
pastfirstbracket = firstbracket+1
tagcontent = xmltext[pastfirstbracket:closebracket]
# shortcut, no equal means nothing but name in the tag content
if '=' not in tagcontent:
if tagcontent[-1]=="/":
# simple case
#print "simple case", tagcontent
tagcontent = tagcontent[:-1]
docontents = None
name = tagcontent.strip()
NameString = name
cursor = startsearch
else:
if '"' in tagcontent:
# check double quotes
stop = None
# not inside double quotes! (the split should have odd length)
if noclose or len((tagcontent+".").split('"'))% 2:
stop=1
while stop is None:
closebracket = xmltext.find(">", startsearch)
startsearch = closebracket+1
noclose = closebracket<0
tagcontent = xmltext[pastfirstbracket:closebracket]
# not inside double quotes! (the split should have odd length)
if noclose or len((tagcontent+".").split('"'))% 2:
stop=1
if noclose:
raise ValueError("unclosed start tag %s" % repr(xmltext[firstbracket:firstbracket+20]))
cursor = startsearch
#cursor = closebracket+1
# handle simple tag /> syntax
if xmltext[closebracket-1]=="/":
#if verbose: print "it's a simple tag"
closebracket = closebracket-1
tagcontent = tagcontent[:-1]
docontents = None
#tagcontent = xmltext[firstbracket+1:closebracket]
tagcontent = tagcontent.strip()
taglist = tagcontent.split("=")
#if not taglist:
# raise ValueError, "tag with no name %s" % repr(xmltext[firstbracket:firstbracket+20])
taglist0 = taglist[0]
taglist0list = taglist0.split()
#if len(taglist0list)>2:
# raise ValueError, "bad tag head %s" % repr(taglist0)
name = taglist0list[0]
#print "tag name is", name
NameString = name
# now parse the attributes
attributename = taglist0list[-1]
# put a fake att name at end of last taglist entry for consistent parsing
taglist[-1] = taglist[-1]+" f"
AttDict = D = {}
taglistindex = 1
lasttaglistindex = len(taglist)
#for attentry in taglist[1:]:
while taglistindex<lasttaglistindex:
#print "looking for attribute named", attributename
attentry = taglist[taglistindex]
taglistindex = taglistindex+1
attentry = attentry.strip()
if attentry[0]!='"':
raise ValueError("attribute value must start with double quotes" + repr(attentry))
while '"' not in attentry[1:]:
# must have an = inside the attribute value...
if taglistindex>lasttaglistindex:
raise ValueError("unclosed value " + repr(attentry))
nextattentry = taglist[taglistindex]
taglistindex = taglistindex+1
attentry = "%s=%s" % (attentry, nextattentry)
attentry = attentry.strip() # only needed for while loop...
attlist = attentry.split()
nextattname = attlist[-1]
attvalue = attentry[:-len(nextattname)]
attvalue = attvalue.strip()
try:
first = attvalue[0]; last=attvalue[-1]
except:
raise ValueError("attvalue,attentry,attlist="+repr((attvalue, attentry,attlist)))
if first==last=='"' or first==last=="'":
attvalue = attvalue[1:-1]
#print attributename, "=", attvalue
D[attributename] = attvalue
attributename = nextattname
# pass over other tags and content looking for end tag
if docontents is not None:
#print "now looking for end tag"
ContentList = L
while docontents is not None:
nextopenbracket = xmltext.find("<", cursor)
if nextopenbracket<cursor:
#if verbose: print "no next open bracket found"
if name==NONAME:
#print "no more tags for noname", repr(xmltext[cursor:cursor+10])
docontents=None # done
remainder = xmltext[cursor:]
cursor = len(xmltext)
if remainder:
L.append(remainder)
else:
raise ValueError("no close bracket for %s found after %s" % (name,repr(xmltext[cursor: cursor+20])))
# is it a close bracket?
elif xmltext[nextopenbracket+1]=="/":
#print "found close bracket", repr(xmltext[nextopenbracket:nextopenbracket+20])
nextclosebracket = xmltext.find(">", nextopenbracket)
if nextclosebracket<nextopenbracket:
raise ValueError("unclosed close tag %s" % repr(xmltext[nextopenbracket: nextopenbracket+20]))
closetagcontents = xmltext[nextopenbracket+2: nextclosebracket]
closetaglist = closetagcontents.split()
#if len(closetaglist)!=1:
#print closetagcontents
#raise ValueError, "bad close tag format %s" % repr(xmltext[nextopenbracket: nextopenbracket+20])
# name should match
closename = closetaglist[0]
#if verbose: print "closetag name is", closename
if name!=closename:
prefix = xmltext[:cursor]
endlinenum = len(prefix.split("\n"))
prefix = xmltext[:startingat]
linenum = len(prefix.split("\n"))
raise ValueError("at lines %s...%s close tag name doesn't match %s...%s %s" %(
linenum, endlinenum, repr(name), repr(closename), repr(xmltext[cursor: cursor+100])))
remainder = xmltext[cursor:nextopenbracket]
if remainder:
#if verbose: print "remainder", repr(remainder)
L.append(remainder)
cursor = nextclosebracket+1
#print "for", name, "found close tag"
docontents = None # done
# otherwise we are looking at a new tag, recursively parse it...
# first record any intervening content
else:
remainder = xmltext[cursor:nextopenbracket]
if remainder:
L.append(remainder)
#if verbose:
# #print "skipping", repr(remainder)
# #print "--- recursively parsing starting at", xmltext[nextopenbracket:nextopenbracket+20]
(parsetree, cursor) = parsexml0(xmltext, startingat=nextopenbracket, toplevel=None, entityReplacer=entityReplacer)
if parsetree:
L.append(parsetree)
# maybe should check for trailing garbage?
# toplevel:
# remainder = xmltext[cursor:].strip()
# if remainder:
# raise ValueError, "trailing garbage at top level %s" % repr(remainder[:20])
if ContentList:
if entityReplacer: ContentList = entityReplacer(ContentList)
t = (NameString, AttDict, ContentList, ExtraStuff)
return (t, cursor)
def pprettyprint(parsedxml):
"""pretty printer mainly for testing"""
if isinstance(parsedxml,(str,bytes)):
return parsedxml
(name, attdict, textlist, extra) = parsedxml
if not attdict: attdict={}
attlist = []
for k in attdict.keys():
v = attdict[k]
attlist.append("%s=%s" % (k, repr(v)))
attributes = " ".join(attlist)
if not name and attributes:
raise ValueError("name missing with attributes???")
if textlist is not None:
# with content
textlistpprint = list(map(pprettyprint, textlist))
textpprint = "\n".join(textlistpprint)
if not name:
return textpprint # no outer tag
# indent it
nllist = textpprint.split("\n")
textpprint = " "+ ("\n ".join(nllist))
return "<%s %s>\n%s\n</%s>" % (name, attributes, textpprint, name)
# otherwise must be a simple tag
return "<%s %s/>" % (name, attributes)
def testparse(s,dump=0):
from time import time
from pprint import pprint
now = time()
D = parsexmlSimple(s,oneOutermostTag=1)
print("DONE", time()-now)
if dump&4:
pprint(D)
#pprint(D)
if dump&1:
print("============== reformatting")
p = pprettyprint(D)
print(p)
def test(dump=0):
testparse("""<this type="xml">text &lt;&gt;<b>in</b> <funnytag foo="bar"/> xml</this>
<!-- comment -->
<![CDATA[
<this type="xml">text <b>in</b> xml</this> ]]>
<tag with="<brackets in values>">just testing brackets feature</tag>
""",dump=dump)
if __name__=="__main__":
test(dump=1)
import sys, os
from time import time
import reportlab
now = time()
seen = 0
for f in sys.argv[1:]:
if not os.path.isfile(f):
print("!!!!! no file at {f!r}")
else:
with open(f) as _f:
t = _f.read()
print(f"parsing {f!r} |t|={len(t)}")
testparse(t,dump=1)
seen += 1
if seen:
print(f"timed at {time()-now:.2f} secs.")
@@ -0,0 +1,311 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__="""A Sequencer class counts things. It aids numbering and formatting lists."""
__all__='''Sequencer getSequencer setSequencer'''.split()
#
# roman numbers conversion thanks to
#
# fredrik lundh, november 1996 (based on a C hack from 1984)
#
# fredrik@pythonware.com
# http://www.pythonware.com
_RN_TEMPLATES = [ 0, 0o1, 0o11, 0o111, 0o12, 0o2, 0o21, 0o211, 0o2111, 0o13 ]
_RN_LETTERS = "IVXLCDM"
def _format_I(value):
if value < 0 or value > 3999:
raise ValueError("illegal value")
str = ""
base = -1
while value:
value, index = divmod(value, 10)
tmp = _RN_TEMPLATES[index]
while tmp:
tmp, index = divmod(tmp, 8)
str = _RN_LETTERS[index+base] + str
base += 2
return str
def _format_i(num):
return _format_I(num).lower()
def _format_123(num):
"""The simplest formatter"""
return str(num)
def _format_ABC(num):
"""Uppercase. Wraps around at 26."""
n = (num -1) % 26
return chr(n+65)
def _format_abc(num):
"""Lowercase. Wraps around at 26."""
n = (num -1) % 26
return chr(n+97)
_type2formatter = {
'I':_format_I,
'i':_format_i,
'1':_format_123,
'A':_format_ABC,
'a':_format_abc,
}
class _Counter:
"""Private class used by Sequencer. Each counter
knows its format, and the IDs of anything it
resets, as well as its value. Starts at zero
and increments just before you get the new value,
so that it is still 'Chapter 5' and not 'Chapter 6'
when you print 'Figure 5.1'"""
def __init__(self):
self._base = 0
self._value = self._base
self._formatter = _format_123
self._resets = []
def setFormatter(self, formatFunc):
self._formatter = formatFunc
def reset(self, value=None):
if value:
self._value = value
else:
self._value = self._base
def next(self):
self._value += 1
v = self._value
for counter in self._resets:
counter.reset()
return v
__next__ = next
def _this(self):
return self._value
def nextf(self):
"""Returns next value formatted"""
return self._formatter(next(self))
def thisf(self):
return self._formatter(self._this())
def chain(self, otherCounter):
if not otherCounter in self._resets:
self._resets.append(otherCounter)
class Sequencer:
"""Something to make it easy to number paragraphs, sections,
images and anything else. The features include registering
new string formats for sequences, and 'chains' whereby
some counters are reset when their parents.
It keeps track of a number of
'counters', which are created on request:
Usage::
>>> seq = layout.Sequencer()
>>> seq.next('Bullets')
1
>>> seq.next('Bullets')
2
>>> seq.next('Bullets')
3
>>> seq.reset('Bullets')
>>> seq.next('Bullets')
1
>>> seq.next('Figures')
1
>>>
"""
def __init__(self):
self._counters = {} #map key to current number
self._formatters = {}
self._reset()
def _reset(self):
self._counters.clear()
self._formatters.clear()
self._formatters.update({
# the formats it knows initially
'1':_format_123,
'A':_format_ABC,
'a':_format_abc,
'I':_format_I,
'i':_format_i,
})
d = dict(_counters=self._counters,_formatters=self._formatters)
self.__dict__.clear()
self.__dict__.update(d)
self._defaultCounter = None
def _getCounter(self, counter=None):
"""Creates one if not present"""
try:
return self._counters[counter]
except KeyError:
cnt = _Counter()
self._counters[counter] = cnt
return cnt
def _this(self, counter=None):
"""Retrieves counter value but does not increment. For
new counters, sets base value to 1."""
if not counter:
counter = self._defaultCounter
return self._getCounter(counter)._this()
def __next__(self):
"""Retrieves the numeric value for the given counter, then
increments it by one. New counters start at one."""
return next(self._getCounter(self._defaultCounter))
def next(self,counter=None):
if not counter:
return next(self)
else:
dc = self._defaultCounter
try:
self._defaultCounter = counter
return next(self)
finally:
self._defaultCounter = dc
def thisf(self, counter=None):
if not counter:
counter = self._defaultCounter
return self._getCounter(counter).thisf()
def nextf(self, counter=None):
"""Retrieves the numeric value for the given counter, then
increments it by one. New counters start at one."""
if not counter:
counter = self._defaultCounter
return self._getCounter(counter).nextf()
def setDefaultCounter(self, default=None):
"""Changes the key used for the default"""
self._defaultCounter = default
def registerFormat(self, format, func):
"""Registers a new formatting function. The funtion
must take a number as argument and return a string;
fmt is a short menmonic string used to access it."""
self._formatters[format] = func
def setFormat(self, counter, format):
"""Specifies that the given counter should use
the given format henceforth."""
func = self._formatters[format]
self._getCounter(counter).setFormatter(func)
def reset(self, counter=None, base=0):
if not counter:
counter = self._defaultCounter
self._getCounter(counter)._value = base
def chain(self, parent, child):
p = self._getCounter(parent)
c = self._getCounter(child)
p.chain(c)
def __getitem__(self, key):
"""Allows compact notation to support the format function.
s['key'] gets current value, s['key+'] increments."""
if key[-1:] == '+':
counter = key[:-1]
return self.nextf(counter)
else:
return self.thisf(key)
def format(self, template):
"""The crowning jewels - formats multi-level lists."""
return template % self
def dump(self):
"""Write current state to stdout for diagnostics"""
counters = list(self._counters.items())
counters.sort()
print('Sequencer dump:')
for (key, counter) in counters:
print(' %s: value = %d, base = %d, format example = %s' % (
key, counter._this(), counter._base, counter.thisf()))
"""Your story builder needs to set this to"""
_sequencer = None
def getSequencer():
global _sequencer
if _sequencer is None:
_sequencer = Sequencer()
return _sequencer
def setSequencer(seq):
global _sequencer
s = _sequencer
_sequencer = seq
return s
def _reset():
global _sequencer
if _sequencer:
_sequencer._reset()
from reportlab.rl_config import register_reset
register_reset(_reset)
del register_reset
def test():
s = Sequencer()
print('Counting using default sequence: %d %d %d' % (next(s),next(s), next(s)))
print('Counting Figures: Figure %d, Figure %d, Figure %d' % (
s.next('figure'), s.next('figure'), s.next('figure')))
print('Back to default again: %d' % next(s))
s.setDefaultCounter('list1')
print('Set default to list1: %d %d %d' % (next(s),next(s), next(s)))
s.setDefaultCounter()
print('Set default to None again: %d %d %d' % (next(s),next(s), next(s)))
print()
print('Creating Appendix counter with format A, B, C...')
s.setFormat('Appendix', 'A')
print(' Appendix %s, Appendix %s, Appendix %s' % (
s.nextf('Appendix'), s.nextf('Appendix'),s.nextf('Appendix')))
def format_french(num):
return ('un','deux','trois','quatre','cinq')[(num-1)%5]
print()
print('Defining a custom format with french words:')
s.registerFormat('french', format_french)
s.setFormat('FrenchList', 'french')
print(' ' +(' '.join(str(s.nextf('FrenchList')) for i in range(1,6))))
print()
print('Chaining H1 and H2 - H2 goes back to one when H1 increases')
s.chain('H1','H2')
print(' H1 = %d' % s.next('H1'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print(' H1 = %d' % s.next('H1'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print()
print('GetItem notation - append a plus to increment')
print(' seq["Appendix"] = %s' % s["Appendix"])
print(' seq["Appendix+"] = %s' % s["Appendix+"])
print(' seq["Appendix+"] = %s' % s["Appendix+"])
print(' seq["Appendix"] = %s' % s["Appendix"])
print()
print('Finally, string format notation for nested lists. Cool!')
print('The expression ("Figure %(Chapter)s.%(Figure+)s" % seq) gives:')
print(' Figure %(Chapter)s.%(Figure+)s' % s)
print(' Figure %(Chapter)s.%(Figure+)s' % s)
print(' Figure %(Chapter)s.%(Figure+)s' % s)
if __name__=='__main__':
test()
@@ -0,0 +1,436 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/styles.py
__version__='3.3.0'
__doc__='''Classes for ParagraphStyle and similar things.
A style is a collection of attributes, but with some extra features
to allow 'inheritance' from a parent, and to ensure nobody makes
changes after construction.
ParagraphStyle shows all the attributes available for formatting
paragraphs.
getSampleStyleSheet() returns a stylesheet you can use for initial
development, with a few basic heading and text styles.
'''
__all__=(
'PropertySet',
'ParagraphStyle',
'str2alignment',
'LineStyle',
'ListStyle',
'StyleSheet1',
'getSampleStyleSheet',
)
from reportlab.lib.colors import black
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
from reportlab.lib.fonts import tt2ps
from reportlab.rl_config import canvas_basefontname as _baseFontName, \
underlineWidth as _baseUnderlineWidth, \
underlineOffset as _baseUnderlineOffset, \
underlineGap as _baseUnderlineGap, \
strikeWidth as _baseStrikeWidth, \
strikeOffset as _baseStrikeOffset, \
strikeGap as _baseStrikeGap, \
spaceShrinkage as _spaceShrinkage, \
platypus_link_underline as _platypus_link_underline, \
hyphenationLang as _hyphenationLang, \
hyphenationMinWordLength as _hyphenationMinWordLength, \
uriWasteReduce as _uriWasteReduce, \
embeddedHyphenation as _embeddedHyphenation
_baseFontNameB = tt2ps(_baseFontName,1,0)
_baseFontNameI = tt2ps(_baseFontName,0,1)
_baseFontNameBI = tt2ps(_baseFontName,1,1)
###########################################################
# This class provides an 'instance inheritance'
# mechanism for its descendants, simpler than acquisition
# but not as far-reaching
###########################################################
class PropertySet:
defaults = {}
def __init__(self, name, parent=None, **kw):
"""When initialized, it copies the class defaults;
then takes a copy of the attributes of the parent
if any. All the work is done in init - styles
should cost little to use at runtime."""
# step one - validate the hell out of it
assert 'name' not in self.defaults, "Class Defaults may not contain a 'name' attribute"
assert 'parent' not in self.defaults, "Class Defaults may not contain a 'parent' attribute"
if parent:
assert parent.__class__ == self.__class__, "Parent style %s must have same class as new style %s" % (parent.__class__.__name__,self.__class__.__name__)
#step two
self.name = name
self.parent = parent
self.__dict__.update(self.defaults)
#step two - copy from parent if any. Try to be
# very strict that only keys in class defaults are
# allowed, so they cannot inherit
self.refresh()
self._setKwds(**kw)
def _setKwds(self,**kw):
#step three - copy keywords if any
for key, value in kw.items():
self.__dict__[key] = value
def __repr__(self):
return "<%s '%s'>" % (self.__class__.__name__, self.name)
def refresh(self):
"""re-fetches attributes from the parent on demand;
use if you have been hacking the styles. This is
used by __init__"""
if self.parent:
for key, value in self.parent.__dict__.items():
if (key not in ['name','parent']):
self.__dict__[key] = value
def listAttrs(self, indent=''):
print(indent + 'name =', self.name)
print(indent + 'parent =', self.parent)
keylist = list(self.__dict__.keys())
keylist.sort()
keylist.remove('name')
keylist.remove('parent')
for key in keylist:
value = self.__dict__.get(key, None)
print(indent + '%s = %s' % (key, value))
def clone(self, name, parent=None, **kwds):
r = self.__class__(name,parent)
r.__dict__ = self.__dict__.copy()
r.name = name
r.parent = parent is None and self or parent
r._setKwds(**kwds)
return r
class ParagraphStyle(PropertySet):
defaults = {
'fontName':_baseFontName,
'fontSize':10,
'leading':12,
'leftIndent':0,
'rightIndent':0,
'firstLineIndent':0,
'alignment':TA_LEFT,
'spaceBefore':0,
'spaceAfter':0,
'bulletFontName':_baseFontName,
'bulletFontSize':10,
'bulletIndent':0,
#'bulletColor':black,
'textColor': black,
'backColor':None,
'wordWrap':None, #None means do nothing special
#CJK use Chinese Line breaking
#LTR RTL use left to right / right to left
#with support from pyfribi2 if available
'shaping': 0,
'borderWidth': 0,
'borderPadding': 0,
'borderColor': None,
'borderRadius': None,
'allowWidows': 1,
'allowOrphans': 0,
'textTransform':None, #uppercase lowercase (captitalize not yet) or None or absent
'endDots':None, #dots on the last line of left/right justified paras
#string or object with text and optional fontName, fontSize, textColor & backColor
#dy
'splitLongWords':1, #make best efforts to split long words
'underlineWidth': _baseUnderlineWidth, #underline width default
'bulletAnchor': 'start', #where the bullet is anchored ie start, middle, end or numeric
'justifyLastLine': 0, #n allow justification on the last line for more than n words 0 means don't bother
'justifyBreaks': 0, #justify lines broken with <br/>
'spaceShrinkage': _spaceShrinkage, #allow shrinkage of percentage of space to fit on line
'strikeWidth': _baseStrikeWidth, #stroke width default
'underlineOffset': _baseUnderlineOffset, #fraction of fontsize to offset underlines
'underlineGap': _baseUnderlineGap, #gap for double/triple underline
'strikeOffset': _baseStrikeOffset, #fraction of fontsize to offset strikethrough
'strikeGap': _baseStrikeGap, #gap for double/triple strike
'linkUnderline': _platypus_link_underline,
'underlineColor': None,
'strikeColor': None,
'hyphenationLang': _hyphenationLang,
#'hyphenationMinWordLength': _hyphenationMinWordLength,
'embeddedHyphenation': _embeddedHyphenation,
'uriWasteReduce': _uriWasteReduce,
}
def str2alignment(v,__map__=dict(
centre=TA_CENTER,
center=TA_CENTER,
left=TA_LEFT,right=TA_RIGHT,
justify=TA_JUSTIFY)):
_ = __map__.get(v.lower(),None)
if _ is None: raise ValueError(f'{v!r} is illegal value for alignment')
return _
class LineStyle(PropertySet):
defaults = {
'width':1,
'color': black
}
def prepareCanvas(self, canvas):
"""You can ask a LineStyle to set up the canvas for drawing
the lines."""
canvas.setLineWidth(1)
#etc. etc.
class ListStyle(PropertySet):
defaults = dict(
leftIndent=18,
rightIndent=0,
bulletAlign='left',
bulletType='1',
bulletColor=black,
bulletFontName='Helvetica',
bulletFontSize=12,
bulletOffsetY=0,
bulletDedent='auto',
bulletDir='ltr',
bulletFormat=None,
start=None, #starting value for a list; if a list then the start sequence
)
_stylesheet1_undefined = object()
class StyleSheet1:
"""
This may or may not be used. The idea is to:
1. slightly simplify construction of stylesheets;
2. enforce rules to validate styles when added
(e.g. we may choose to disallow having both
'heading1' and 'Heading1' - actual rules are
open to discussion);
3. allow aliases and alternate style lookup
mechanisms
4. Have a place to hang style-manipulation
methods (save, load, maybe support a GUI
editor)
Access is via getitem, so they can be
compatible with plain old dictionaries.
"""
def __init__(self):
self.byName = {}
self.byAlias = {}
def __getitem__(self, key):
try:
return self.byAlias[key]
except KeyError:
try:
return self.byName[key]
except KeyError:
raise KeyError("Style '%s' not found in stylesheet" % key)
def get(self,key,default=_stylesheet1_undefined):
try:
return self[key]
except KeyError:
if default!=_stylesheet1_undefined: return default
raise
def __contains__(self, key):
return key in self.byAlias or key in self.byName
def has_key(self,key):
return key in self
def add(self, style, alias=None):
key = style.name
if key in self.byName:
raise KeyError("Style '%s' already defined in stylesheet" % key)
if key in self.byAlias:
raise KeyError("Style name '%s' is already an alias in stylesheet" % key)
if alias:
if alias in self.byName:
raise KeyError("Style '%s' already defined in stylesheet" % alias)
if alias in self.byAlias:
raise KeyError("Alias name '%s' is already an alias in stylesheet" % alias)
#passed all tests? OK, add it
self.byName[key] = style
if alias:
self.byAlias[alias] = style
def __getattr__(self,a):
if a in self: return self.get(a)
raise AttributeError(f'{self.__class__.__name__} instance has no attribute {a!a}')
def list(self):
styles = list(self.byName.items())
styles.sort()
alii = {}
for (alias, style) in list(self.byAlias.items()):
alii[style] = alias
for (name, style) in styles:
alias = alii.get(style, None)
print(name, alias)
style.listAttrs(' ')
print()
def testStyles():
pNormal = ParagraphStyle('Normal',None)
pNormal.fontName = _baseFontName
pNormal.fontSize = 12
pNormal.leading = 14.4
pNormal.listAttrs()
print()
pPre = ParagraphStyle('Literal', pNormal)
pPre.fontName = 'Courier'
pPre.listAttrs()
return pNormal, pPre
def getSampleStyleSheet():
"""Returns a stylesheet object"""
stylesheet = StyleSheet1()
stylesheet.add(ParagraphStyle(name='Normal',
fontName=_baseFontName,
fontSize=10,
leading=12)
)
stylesheet.add(ParagraphStyle(name='BodyText',
parent=stylesheet['Normal'],
spaceBefore=6)
)
stylesheet.add(ParagraphStyle(name='Italic',
parent=stylesheet['BodyText'],
fontName = _baseFontNameI)
)
stylesheet.add(ParagraphStyle(name='Heading1',
parent=stylesheet['Normal'],
fontName = _baseFontNameB,
fontSize=18,
leading=22,
spaceAfter=6),
alias='h1')
stylesheet.add(ParagraphStyle(name='Title',
parent=stylesheet['Normal'],
fontName = _baseFontNameB,
fontSize=18,
leading=22,
alignment=TA_CENTER,
spaceAfter=6),
alias='title')
stylesheet.add(ParagraphStyle(name='Heading2',
parent=stylesheet['Normal'],
fontName = _baseFontNameB,
fontSize=14,
leading=18,
spaceBefore=12,
spaceAfter=6),
alias='h2')
stylesheet.add(ParagraphStyle(name='Heading3',
parent=stylesheet['Normal'],
fontName = _baseFontNameBI,
fontSize=12,
leading=14,
spaceBefore=12,
spaceAfter=6),
alias='h3')
stylesheet.add(ParagraphStyle(name='Heading4',
parent=stylesheet['Normal'],
fontName = _baseFontNameBI,
fontSize=10,
leading=12,
spaceBefore=10,
spaceAfter=4),
alias='h4')
stylesheet.add(ParagraphStyle(name='Heading5',
parent=stylesheet['Normal'],
fontName = _baseFontNameB,
fontSize=9,
leading=10.8,
spaceBefore=8,
spaceAfter=4),
alias='h5')
stylesheet.add(ParagraphStyle(name='Heading6',
parent=stylesheet['Normal'],
fontName = _baseFontNameB,
fontSize=7,
leading=8.4,
spaceBefore=6,
spaceAfter=2),
alias='h6')
stylesheet.add(ParagraphStyle(name='Bullet',
parent=stylesheet['Normal'],
firstLineIndent=0,
spaceBefore=3),
alias='bu')
stylesheet.add(ParagraphStyle(name='Definition',
parent=stylesheet['Normal'],
firstLineIndent=0,
leftIndent=36,
bulletIndent=0,
spaceBefore=6,
bulletFontName=_baseFontNameBI),
alias='df')
stylesheet.add(ParagraphStyle(name='Code',
parent=stylesheet['Normal'],
fontName='Courier',
fontSize=8,
leading=8.8,
firstLineIndent=0,
leftIndent=36,
hyphenationLang=''))
stylesheet.add(ListStyle(name='UnorderedList',
parent=None,
leftIndent=18,
rightIndent=0,
bulletAlign='left',
bulletType='1',
bulletColor=black,
bulletFontName='Helvetica',
bulletFontSize=12,
bulletOffsetY=0,
bulletDedent='auto',
bulletDir='ltr',
bulletFormat=None,
#start='circle square blackstar sparkle disc diamond'.split(),
start=None,
),
alias='ul')
stylesheet.add(ListStyle(name='OrderedList',
parent=None,
leftIndent=18,
rightIndent=0,
bulletAlign='left',
bulletType='1',
bulletColor=black,
bulletFontName='Helvetica',
bulletFontSize=12,
bulletOffsetY=0,
bulletDedent='auto',
bulletDir='ltr',
bulletFormat=None,
#start='1 a A i I'.split(),
start=None,
),
alias='ol')
return stylesheet
@@ -0,0 +1,406 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
import reportlab
reportlab._rl_testing=True
del reportlab
__version__='4.0.1'
__doc__="""Provides support for the test suite.
The test suite as a whole, and individual tests, need to share
certain support functions. We have to put these in here so they
can always be imported, and so that individual tests need to import
nothing more than "reportlab.whatever..."
"""
import sys, os, fnmatch, re, functools
from configparser import ConfigParser
import unittest, random
from reportlab.lib.utils import isCompactDistro, __rl_loader__, rl_isdir, asUnicode
from reportlab.rl_config import invariant as rl_invariant
def invariantSeed(n):
if rl_invariant: random.seed(n)
def haveRenderPM():
from reportlab.graphics.renderPM import _getPMBackend, RenderPMError
try:
return _getPMBackend()
except RenderPMError:
return False
DEJAVUSANS = ('DejaVuSans','DejaVuSans-Bold','DejaVuSans-Oblique','DejaVuSans-BoldOblique')
def haveDejaVu():
from reportlab.pdfbase.ttfonts import TTFont
for x in DEJAVUSANS:
try:
TTFont(x,x+'.ttf')
except:
return False
return True
# Helper functions.
def isWritable(D):
try:
fn = '00DELETE.ME'
f = open(fn, 'w')
f.write('test of writability - can be deleted')
f.close()
if os.path.isfile(fn):
os.remove(fn)
return 1
except:
return 0
_OUTDIR = None
RL_HOME = None
testsFolder = None
def setOutDir(name):
"""Is it a writable file system distro being invoked within
test directory? If so, can write test output here. If not,
it had better go in a temp directory. Only do this once per
process"""
global _OUTDIR, RL_HOME, testsFolder
if _OUTDIR: return _OUTDIR
D = [d[9:] for d in sys.argv if d.startswith('--outdir=')]
if not D:
D = os.environ.get('RL_TEST_OUTDIR','')
if D: D=[D]
if D:
_OUTDIR = D[-1]
try:
os.makedirs(_OUTDIR)
except:
pass
for d in D:
if d in sys.argv:
sys.argv.remove(d)
else:
assert name=='__main__',"setOutDir should only be called in the main script"
scriptDir=os.path.dirname(sys.argv[0])
if not scriptDir: scriptDir=os.getcwd()
_OUTDIR = scriptDir
if not isWritable(_OUTDIR):
_OUTDIR = get_rl_tempdir('reportlab_test')
import reportlab
RL_HOME=reportlab.__path__[0]
if not os.path.isabs(RL_HOME): RL_HOME=os.path.normpath(os.path.abspath(RL_HOME))
topDir = os.path.dirname(RL_HOME)
testsFolder = os.path.join(topDir,'tests')
if not os.path.isdir(testsFolder):
testsFolder = os.path.join(os.path.dirname(topDir),'tests')
if not os.path.isdir(testsFolder):
if name=='__main__':
scriptDir=os.path.dirname(sys.argv[0])
if not scriptDir: scriptDir=os.getcwd()
testsFolder = os.path.abspath(scriptDir)
else:
testsFolder = None
if testsFolder:
sys.path.insert(0,os.path.dirname(testsFolder))
return _OUTDIR
_mockumap = (
None if os.environ.get('OFFLINE_MOCK','1')!='1'
else'http://www.reportlab.com/rsrc/encryption.gif',
)
def mockUrlRead(name):
if name in _mockumap:
with open(os.path.join(testsFolder,os.path.basename(name)),'rb') as f:
return f.read()
else:
from urllib.request import urlopen
return urlopen(name).read()
def outputfile(fn):
"""This works out where to write test output. If running
code in a locked down file system, this will be a
temp directory; otherwise, the output of 'test_foo.py' will
normally be a file called 'test_foo.pdf', next door.
"""
D = setOutDir(__name__)
if fn: D = os.path.join(D,fn)
return D
def printLocation(depth=1):
if sys._getframe(depth).f_locals.get('__name__')=='__main__':
outDir = outputfile('')
if outDir!=_OUTDIR:
print('Logs and output files written to folder "%s"' % outDir)
def makeSuiteForClasses(*classes,testMethodPrefix=None):
"Return a test suite with tests loaded from provided classes."
suite = unittest.TestSuite()
loader = unittest.TestLoader()
if testMethodPrefix:
loader.testMethodPrefix = testMethodPrefix
for C in classes:
suite.addTest(loader.loadTestsFromTestCase(C))
return suite
def getCVSEntries(folder, files=1, folders=0):
"""Returns a list of filenames as listed in the CVS/Entries file.
'folder' is the folder that should contain the CVS subfolder.
If there is no such subfolder an empty list is returned.
'files' is a boolean; 1 and 0 means to return files or not.
'folders' is a boolean; 1 and 0 means to return folders or not.
"""
join = os.path.join
# If CVS subfolder doesn't exist return empty list.
try:
f = open(join(folder, 'CVS', 'Entries'))
except IOError:
return []
# Return names of files and/or folders in CVS/Entries files.
allEntries = []
for line in f.readlines():
if folders and line[0] == 'D' \
or files and line[0] != 'D':
entry = line.split('/')[1]
if entry:
allEntries.append(join(folder, entry))
return allEntries
# Still experimental class extending ConfigParser's behaviour.
class ExtConfigParser(ConfigParser):
"A slightly extended version to return lists of strings."
pat = re.compile(r'\s*\[.*\]\s*')
def getstringlist(self, section, option):
"Coerce option to a list of strings or return unchanged if that fails."
value = ConfigParser.get(self, section, option)
# This seems to allow for newlines inside values
# of the config file, but be careful!!
val = value.replace('\n', '')
if self.pat.match(val):
return eval(val,{__builtins__:None})
else:
return value
# This class as suggested by /F with an additional hook
# to be able to filter filenames.
class GlobDirectoryWalker:
"A forward iterator that traverses files in a directory tree."
def __init__(self, directory, pattern='*'):
self.index = 0
self.pattern = pattern
directory.replace('/',os.sep)
if os.path.isdir(directory):
self.stack = [directory]
self.files = []
else:
if not isCompactDistro() or not __rl_loader__ or not rl_isdir(directory):
raise ValueError('"%s" is not a directory' % directory)
self.directory = directory[len(__rl_loader__.archive)+len(os.sep):]
pfx = self.directory+os.sep
n = len(pfx)
self.files = list(map(lambda x, n=n: x[n:],list(filter(lambda x,pfx=pfx: x.startswith(pfx),list(__rl_loader__._files.keys())))))
self.files.sort()
self.stack = []
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
# now call the hook
self.files = self.filterFiles(self.directory, self.files)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
if fnmatch.fnmatch(file, self.pattern):
return fullname
def filterFiles(self, folder, files):
"Filter hook, overwrite in subclasses as needed."
return files
class RestrictedGlobDirectoryWalker(GlobDirectoryWalker):
"An restricted directory tree iterator."
def __init__(self, directory, pattern='*', ignore=None):
GlobDirectoryWalker.__init__(self, directory, pattern)
if ignore == None:
ignore = []
ip = [].append
if isinstance(ignore,(tuple,list)):
for p in ignore:
ip(p)
elif isinstance(ignore,str):
ip(ignore)
self.ignorePatterns = ([_.replace('/',os.sep) for _ in ip.__self__] if os.sep != '/'
else ip.__self__)
def filterFiles(self, folder, files):
"Filters all items from files matching patterns to ignore."
fnm = fnmatch.fnmatch
indicesToDelete = []
for i,f in enumerate(files):
for p in self.ignorePatterns:
if fnm(f, p) or fnm(os.path.join(folder,f),p):
indicesToDelete.append(i)
indicesToDelete.reverse()
for i in indicesToDelete:
del files[i]
return files
class CVSGlobDirectoryWalker(GlobDirectoryWalker):
"An directory tree iterator that checks for CVS data."
def filterFiles(self, folder, files):
"""Filters files not listed in CVS subfolder.
This will look in the CVS subfolder of 'folder' for
a file named 'Entries' and filter all elements from
the 'files' list that are not listed in 'Entries'.
"""
join = os.path.join
cvsFiles = getCVSEntries(folder)
if cvsFiles:
indicesToDelete = []
for i in range(len(files)):
f = files[i]
if join(folder, f) not in cvsFiles:
indicesToDelete.append(i)
indicesToDelete.reverse()
for i in indicesToDelete:
del files[i]
return files
# An experimental untested base class with additional 'security'.
class SecureTestCase(unittest.TestCase):
"""Secure testing base class with additional pre- and postconditions.
We try to ensure that each test leaves the environment it has
found unchanged after the test is performed, successful or not.
Currently we restore sys.path and the working directory, but more
of this could be added easily, like removing temporary files or
similar things.
Use this as a base class replacing unittest.TestCase and call
these methods in subclassed versions before doing your own
business!
"""
def setUp(self):
"Remember sys.path and current working directory."
self._initialPath = sys.path[:]
self._initialWorkDir = os.getcwd()
def tearDown(self):
"Restore previous sys.path and working directory."
sys.path = self._initialPath
os.chdir(self._initialWorkDir)
class NearTestCase(unittest.TestCase):
def assertNear(a,b,accuracy=1e-5):
if isinstance(a,(float,int)):
if abs(a-b)>accuracy:
raise AssertionError("%s not near %s" % (a, b))
else:
for ae,be in zip(a,b):
if abs(ae-be)>accuracy:
raise AssertionError("%s not near %s" % (a, b))
assertNear = staticmethod(assertNear)
class ScriptThatMakesFileTest(unittest.TestCase):
"""Runs a Python script at OS level, expecting it to produce a file.
It CDs to the working directory to run the script."""
def __init__(self, scriptDir, scriptName, outFileName, verbose=0):
self.scriptDir = scriptDir
self.scriptName = scriptName
self.outFileName = outFileName
self.verbose = verbose
# normally, each instance is told which method to run)
unittest.TestCase.__init__(self)
def setUp(self):
self.cwd = os.getcwd()
global testsFolder
scriptDir=self.scriptDir
if not os.path.isabs(scriptDir):
scriptDir=os.path.join(testsFolder,scriptDir)
os.chdir(scriptDir)
assert os.path.isfile(self.scriptName), "Script %s not found!" % self.scriptName
if os.path.isfile(self.outFileName):
os.remove(self.outFileName)
def tearDown(self):
os.chdir(self.cwd)
def runTest(self):
fmt = sys.platform=='win32' and '"%s" %s' or '%s %s'
import subprocess
out = subprocess.check_output((sys.executable,self.scriptName))
#p = os.popen(fmt % (sys.executable,self.scriptName),'r')
#out = p.read()
if self.verbose:
print(out)
#status = p.close()
assert os.path.isfile(self.outFileName), "File %s not created!" % self.outFileName
def equalStrings(a,b,enc='utf8'):
return a==b if type(a)==type(b) else asUnicode(a,enc)==asUnicode(b,enc)
def eqCheck(r,x):
if r!=x:
print('Strings unequal\nexp: %s\ngot: %s' % (ascii(x),ascii(r)))
def rlextraNeeded():
try:
import rlextra
return False
except:
return True
def rlSkipIf(cond,reason,__module__=None):
def inner(func):
@functools.wraps(func)
def wrapper(*args,**kwds):
if cond and os.environ.get('RL_indicateSkips','0')=='1':
print(f'''
skipping {func.__module__ or __module__}.{func.__name__} {reason}''')
return unittest.skipIf(cond,reason)(func)(*args,**kwds)
return wrapper
return inner
def rlSkipUnless(cond,reason,__module__=None):
return rlSkipIf(not cond,reason,__module__=__module__)
def rlSkip(reason,__module__=None):
return rlSkipIf(True,reason,__module__=__module__)
@@ -0,0 +1,241 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/textsplit.py
"""Helpers for text wrapping, hyphenation, Asian text splitting and kinsoku shori.
How to split a 'big word' depends on the language and the writing system. This module
works on a Unicode string. It ought to grow by allowing ore algoriths to be plugged
in based on possible knowledge of the language and desirable 'niceness' of the algorithm.
"""
__version__='3.3.0'
from unicodedata import category
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.rl_config import _FUZZ
from reportlab.lib.utils import isUnicode
CANNOT_START_LINE = [
#strongly prohibited e.g. end brackets, stop, exclamation...
u'!\',.:;?!")]\u3001\u3002\u300d\u300f\u3011\u3015\uff3d\u3011\uff09',
#middle priority e.g. continuation small vowels - wrapped on two lines but one string...
u'\u3005\u2015\u3041\u3043\u3045\u3047\u3049\u3063\u3083\u3085\u3087\u308e\u30a1\u30a3'
u'\u30a5\u30a7\u30a9\u30c3\u30e3\u30e5\u30e7\u30ee\u30fc\u30f5\u30f6',
#weakly prohibited - continuations, celsius symbol etc.
u'\u309b\u309c\u30fb\u30fd\u30fe\u309d\u309e\u2015\u2010\xb0\u2032\u2033\u2103\uffe0\uff05\u2030'
]
ALL_CANNOT_START = u''.join(CANNOT_START_LINE)
CANNOT_END_LINE = [
#strongly prohibited
u'\u2018\u201c\uff08[{\uff08\u3014\uff3b\uff5b\u3008\u300a\u300c\u300e\u3010',
#weaker - currency symbols, hash, postcode - prefixes
u'$\u00a3@#\uffe5\uff04\uffe1\uff20\u3012\u00a7'
]
ALL_CANNOT_END = u''.join(CANNOT_END_LINE)
def is_multi_byte(ch):
"Is this an Asian character?"
return (ord(ch) >= 0x3000)
def getCharWidths(word, fontName, fontSize):
"""Returns a list of glyph widths.
>>> getCharWidths('Hello', 'Courier', 10)
[6.0, 6.0, 6.0, 6.0, 6.0]
>>> from reportlab.pdfbase.cidfonts import UnicodeCIDFont
>>> from reportlab.pdfbase.pdfmetrics import registerFont
>>> registerFont(UnicodeCIDFont('HeiseiMin-W3'))
>>> getCharWidths(u'\u6771\u4EAC', 'HeiseiMin-W3', 10) #most kanji are 100 ems
[10.0, 10.0]
"""
#character-level function call; the performance is going to SUCK
return [stringWidth(uChar, fontName, fontSize) for uChar in word]
def wordSplit(word, maxWidths, fontName, fontSize, encoding='utf8'):
"""Attempts to break a word which lacks spaces into two parts, the first of which
fits in the remaining space. It is allowed to add hyphens or whatever it wishes.
This is intended as a wrapper for some language- and user-choice-specific splitting
algorithms. It should only be called after line breaking on spaces, which covers western
languages and is highly optimised already. It works on the 'last unsplit word'.
Presumably with further study one could write a Unicode splitting algorithm for text
fragments whick was much faster.
Courier characters should be 6 points wide.
>>> wordSplit('HelloWorld', 30, 'Courier', 10)
[[0.0, 'Hello'], [0.0, 'World']]
>>> wordSplit('HelloWorld', 31, 'Courier', 10)
[[1.0, 'Hello'], [1.0, 'World']]
"""
if not isUnicode(word):
uword = word.decode(encoding)
else:
uword = word
charWidths = getCharWidths(uword, fontName, fontSize)
lines = dumbSplit(uword, charWidths, maxWidths)
if not isUnicode(word):
lines2 = []
#convert back
for (extraSpace, text) in lines:
lines2.append([extraSpace, text.encode(encoding)])
lines = lines2
return lines
def dumbSplit(word, widths, maxWidths):
"""This function attempts to fit as many characters as possible into the available
space, cutting "like a knife" between characters. This would do for Chinese.
It returns a list of (text, extraSpace) items where text is a Unicode string,
and extraSpace is the points of unused space available on the line. This is a
structure which is fairly easy to display, and supports 'backtracking' approaches
after the fact.
Test cases assume each character is ten points wide...
>>> dumbSplit(u'Hello', [10]*5, 60)
[[10, u'Hello']]
>>> dumbSplit(u'Hello', [10]*5, 50)
[[0, u'Hello']]
>>> dumbSplit(u'Hello', [10]*5, 40)
[[0, u'Hell'], [30, u'o']]
"""
_more = """
#>>> dumbSplit(u'Hello', [10]*5, 4) # less than one character
#(u'', u'Hello')
# this says 'Nihongo wa muzukashii desu ne!' (Japanese is difficult isn't it?) in 12 characters
>>> jtext = u'\u65e5\u672c\u8a9e\u306f\u96e3\u3057\u3044\u3067\u3059\u306d\uff01'
>>> dumbSplit(jtext, [10]*11, 30) #
(u'\u65e5\u672c\u8a9e', u'\u306f\u96e3\u3057\u3044\u3067\u3059\u306d\uff01')
"""
if not isinstance(maxWidths,(list,tuple)): maxWidths = [maxWidths]
assert isUnicode(word)
lines = []
i = widthUsed = lineStartPos = 0
maxWidth = maxWidths[0]
nW = len(word)
while i<nW:
w = widths[i]
c = word[i]
widthUsed += w
i += 1
if widthUsed > maxWidth + _FUZZ and widthUsed>0:
extraSpace = maxWidth - widthUsed
if ord(c)<0x3000:
# we appear to be inside a non-Asian script section.
# (this is a very crude test but quick to compute).
# This is likely to be quite rare so the speed of the
# code below is hopefully not a big issue. The main
# situation requiring this is that a document title
# with an english product name in it got cut.
# we count back and look for
# - a space-like character
# - reversion to Kanji (which would be a good split point)
# - in the worst case, roughly half way back along the line
limitCheck = (lineStartPos+i)>>1 #(arbitrary taste issue)
for j in range(i-1,limitCheck,-1):
cj = word[j]
if category(cj)=='Zs' or ord(cj)>=0x3000:
k = j+1
if k<i:
j = k+1
extraSpace += sum(widths[j:i])
w = widths[k]
c = word[k]
i = j
break
#end of English-within-Asian special case
#we are pushing this character back, but
#the most important of the Japanese typography rules
#if this character cannot start a line, wrap it up to this line so it hangs
#in the right margin. We won't do two or more though - that's unlikely and
#would result in growing ugliness.
#and increase the extra space
#bug fix contributed by Alexander Vasilenko <alexs.vasilenko@gmail.com>
if c not in ALL_CANNOT_START and i>lineStartPos+1:
#otherwise we need to push the character back
#the i>lineStart+1 condition ensures progress
i -= 1
extraSpace += w
#lines.append([maxWidth-sum(widths[lineStartPos:i]), word[lineStartPos:i].strip()])
lines.append([extraSpace, word[lineStartPos:i].strip()])
try:
maxWidth = maxWidths[len(lines)]
except IndexError:
maxWidth = maxWidths[-1] # use the last one
lineStartPos = i
widthUsed = 0
#any characters left?
if widthUsed > 0:
lines.append([maxWidth - widthUsed, word[lineStartPos:]])
return lines
def kinsokuShoriSplit(word, widths, availWidth):
#NOT USED OR FINISHED YET!
"""Split according to Japanese rules according to CJKV (Lunde).
Essentially look for "nice splits" so that we don't end a line
with an open bracket, or start one with a full stop, or stuff like
that. There is no attempt to try to split compound words into
constituent kanji. It currently uses wrap-down: packs as much
on a line as possible, then backtracks if needed
This returns a number of words each of which should just about fit
on a line. If you give it a whole paragraph at once, it will
do all the splits.
It's possible we might slightly step over the width limit
if we do hanging punctuation marks in future (e.g. dangle a Japanese
full stop in the right margin rather than using a whole character
box.
"""
lines = []
assert len(word) == len(widths)
curWidth = 0.0
curLine = []
i = 0 #character index - we backtrack at times so cannot use for loop
while 1:
ch = word[i]
w = widths[i]
if curWidth + w < availWidth:
curLine.append(ch)
curWidth += w
else:
#end of line. check legality
if ch in CANNOT_END_LINE[0]:
pass
#to be completed
# This recipe refers:
#
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
import re
rx=re.compile("([\u2e80-\uffff])", re.UNICODE)
def cjkwrap(text, width, encoding="utf8"):
return reduce(lambda line, word, width=width: '%s%s%s' %
(line,
[' ','\n', ''][(len(line)-line.rfind('\n')-1
+ len(word.split('\n',1)[0] ) >= width) or
line[-1:] == '\0' and 2],
word),
rx.sub(r'\1\0 ', str(text,encoding)).split(' ')
).replace('\0', '').encode(encoding)
if __name__=='__main__':
import doctest
from reportlab.lib import textsplit
doctest.testmod(textsplit)
@@ -0,0 +1,30 @@
#!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/units.py
__version__='3.3.0'
__doc__='''Defines inch, cm, mm etc as multiples of a point
You can now in user-friendly units by doing::
from reportlab.lib.units import inch
r = Rect(0, 0, 3 * inch, 6 * inch)
'''
inch = 72.0
cm = inch / 2.54
mm = cm * 0.1
pica = 12.0
def toLength(s):
'''convert a string to a length'''
try:
if s[-2:]=='cm': return float(s[:-2])*cm
if s[-2:]=='in': return float(s[:-2])*inch
if s[-2:]=='pt': return float(s[:-2])
if s[-1:]=='i': return float(s[:-1])*inch
if s[-2:]=='mm': return float(s[:-2])*mm
if s[-4:]=='pica': return float(s[:-4])*pica
return float(s)
except:
raise ValueError("Can't convert '%s' to length" % s)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,382 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/validators.py
__version__='3.5.33'
__doc__="""Standard verifying functions used by attrmap."""
import codecs, re
from reportlab.lib.utils import isSeq, isBytes, isStr
from reportlab.lib import colors
try:
_re_Pattern = re.Pattern
except AttributeError:
_re_Pattern = re._pattern_type
class Percentage(float):
pass
class Validator:
"base validator class"
def __call__(self,x):
return self.test(x)
def __str__(self):
return getattr(self,'_str',self.__class__.__name__)
def normalize(self,x):
return x
def normalizeTest(self,x):
try:
self.normalize(x)
return True
except:
return False
class _isAnything(Validator):
def test(self,x):
return True
class _isNothing(Validator):
def test(self,x):
return False
class _isBoolean(Validator):
def test(self,x):
if isinstance(int,bool): return x in (0,1)
return self.normalizeTest(x)
def normalize(self,x):
if x in (0,1): return x
try:
S = x.upper()
except:
raise ValueError('Must be boolean not %s' % ascii(s))
if S in ('YES','TRUE'): return True
if S in ('NO','FALSE',None): return False
raise ValueError('Must be boolean not %s' % ascii(s))
class _isString(Validator):
def test(self,x):
return isStr(x)
class _isCodec(Validator):
def test(self,x):
if not isStr(x):
return False
try:
a,b,c,d = codecs.lookup(x)
return True
except LookupError:
return False
class _isNumber(Validator):
def test(self,x):
if isinstance(x,(float,int)): return True
return self.normalizeTest(x)
def normalize(self,x):
try:
return float(x)
except:
return int(x)
class _isInt(Validator):
def test(self,x):
if not isinstance(x,int) and not isStr(x): return False
return self.normalizeTest(x)
def normalize(self,x):
return int(x.decode('utf8') if isBytes(x) else x)
class _isNumberOrNone(_isNumber):
def test(self,x):
return x is None or isNumber(x)
def normalize(self,x):
if x is None: return x
return _isNumber.normalize(x)
class _isListOfNumbersOrNone(Validator):
"ListOfNumbersOrNone validator class."
def test(self, x):
if x is None: return True
return isListOfNumbers(x)
class isNumberInRange(_isNumber):
def __init__(self, min, max):
self.min = min
self.max = max
def test(self, x):
try:
n = self.normalize(x)
if self.min <= n <= self.max:
return True
except ValueError:
pass
return False
class _isListOfShapes(Validator):
"ListOfShapes validator class."
def test(self, x):
from reportlab.graphics.shapes import Shape
if isSeq(x):
answer = 1
for e in x:
if not isinstance(e, Shape):
answer = 0
return answer
else:
return False
class _isListOfStringsOrNone(Validator):
"ListOfStringsOrNone validator class."
def test(self, x):
if x is None: return True
return isListOfStrings(x)
class _isTransform(Validator):
"Transform validator class."
def test(self, x):
if isSeq(x):
if len(x) == 6:
for element in x:
if not isNumber(element):
return False
return True
else:
return False
else:
return False
class _isColor(Validator):
"Color validator class."
def test(self, x):
return isinstance(x, colors.Color)
class _isColorOrNone(Validator):
"ColorOrNone validator class."
def test(self, x):
if x is None: return True
return isColor(x)
from reportlab.lib.normalDate import NormalDate
class _isNormalDate(Validator):
def test(self,x):
if isinstance(x,NormalDate):
return True
return x is not None and self.normalizeTest(x)
def normalize(self,x):
return NormalDate(x)
class _isValidChild(Validator):
"ValidChild validator class."
def test(self, x):
"""Is this child allowed in a drawing or group?
I.e. does it descend from Shape or UserNode?
"""
from reportlab.graphics.shapes import UserNode, Shape
return isinstance(x, UserNode) or isinstance(x, Shape)
class _isValidChildOrNone(_isValidChild):
def test(self,x):
return _isValidChild.test(self,x) or x is None
class _isCallable(Validator):
def test(self, x):
return hasattr(x,'__call__')
class OneOf(Validator):
"""Make validator functions for list of choices.
Usage:
f = reportlab.lib.validators.OneOf('happy','sad')
or
f = reportlab.lib.validators.OneOf(('happy','sad'))
f('sad'),f('happy'), f('grumpy')
(1,1,0)
"""
def __init__(self, enum,*args):
if isSeq(enum):
if args!=():
raise ValueError("Either all singleton args or a single sequence argument")
self._enum = tuple(enum)+args
else:
self._enum = (enum,)+args
self._patterns = tuple((_ for _ in self._enum if isinstance(_,_re_Pattern)))
if self._patterns:
self._enum = tuple((_ for _ in self._enum if not isinstance(_,_re_Pattern)))
self.test = self._test_patterns
def test(self, x):
return x in self._enum
def _test_patterns(self, x):
v = x in self._enum
#print(f'{x=} {self._enum=!r} {self._patterns=!r} {v=}')
if v: return True
for p in self._patterns:
v = p.match(x)
if v: return True
return False
class SequenceOf(Validator):
def __init__(self,elemTest,name=None,emptyOK=1, NoneOK=0, lo=0,hi=0x7fffffff):
self._elemTest = elemTest
self._emptyOK = emptyOK
self._NoneOK = NoneOK
self._lo, self._hi = lo, hi
if name: self._str = name
def test(self, x):
if not isSeq(x):
if x is None: return self._NoneOK
return False
if x==[] or x==():
return self._emptyOK
elif not self._lo<=len(x)<=self._hi: return False
for e in x:
if not self._elemTest(e): return False
return True
class EitherOr(Validator):
def __init__(self,tests,name=None):
if not isSeq(tests): tests = (tests,)
self._tests = tests
if name: self._str = name
def test(self, x):
for t in self._tests:
if t(x): return True
return False
class NoneOr(EitherOr):
def test(self, x):
return x is None or super().test(x)
class NotSetOr(EitherOr):
_not_set = object()
def test(self, x):
return x is NotSetOr._not_set or super().test(x)
@staticmethod
def conditionalValue(v,a):
return a if v is NotSetOr._not_set else v
class _isNotSet(Validator):
def test(self,x):
return x is NotSetOr._not_set
class Auto(Validator):
def __init__(self,**kw):
self.__dict__.update(kw)
def test(self,x):
return x is self.__class__ or isinstance(x,self.__class__)
class AutoOr(EitherOr):
def test(self,x):
return isAuto(x) or super().test(x)
class isInstanceOf(Validator):
def __init__(self,klass=None):
self._klass = klass
def test(self,x):
return isinstance(x,self._klass)
class isSubclassOf(Validator):
def __init__(self,klass=None):
self._klass = klass
def test(self,x):
return isinstance(x,type) and issubclass(x,self._klass)
class matchesPattern(Validator):
"""Matches value, or its string representation, against regex"""
def __init__(self, pattern):
self._pattern = re.compile(pattern)
def test(self,x):
x = str(x)
print('testing %s against %s' % (x, self._pattern))
return (self._pattern.match(x) != None)
class DerivedValue:
"""This is used for magic values which work themselves out.
An example would be an "inherit" property, so that one can have
drawing.chart.categoryAxis.labels.fontName = inherit
and pick up the value from the top of the drawing.
Validators will permit this provided that a value can be pulled
in which satisfies it. And the renderer will have special
knowledge of these so they can evaluate themselves.
"""
def getValue(self, renderer, attr):
"""Override this. The renderers will pass the renderer,
and the attribute name. Algorithms can then backtrack up
through all the stuff the renderer provides, including
a correct stack of parent nodes."""
return None
class Inherit(DerivedValue):
def __repr__(self):
return "inherit"
def getValue(self, renderer, attr):
return renderer.getStateValue(attr)
inherit = Inherit()
class NumericAlign(str):
'''for creating the numeric string value for anchors etc etc
dp is the character to align on (the last occurrence will be used)
dpLen is the length of characters after the dp
'''
def __new__(cls,dp='.',dpLen=0):
self = str.__new__(cls,'numeric')
self._dp=dp
self._dpLen = dpLen
return self
isAuto = Auto()
isBoolean = _isBoolean()
isString = _isString()
isCodec = _isCodec()
isNumber = _isNumber()
isInt = _isInt()
isNoneOrInt = NoneOr(isInt,'isNoneOrInt')
isNumberOrNone = _isNumberOrNone()
isTextAnchor = OneOf('start','middle','end','boxauto')
isListOfNumbers = SequenceOf(isNumber,'isListOfNumbers')
isListOfNoneOrNumber = SequenceOf(isNumberOrNone,'isListOfNoneOrNumber')
isListOfListOfNoneOrNumber = SequenceOf(isListOfNoneOrNumber,'isListOfListOfNoneOrNumber')
isListOfNumbersOrNone = _isListOfNumbersOrNone()
isListOfShapes = _isListOfShapes()
isListOfStrings = SequenceOf(isString,'isListOfStrings')
isListOfStringsOrNone = _isListOfStringsOrNone()
isTransform = _isTransform()
isColor = _isColor()
isListOfColors = SequenceOf(isColor,'isListOfColors')
isColorOrNone = _isColorOrNone()
isShape = isValidChild = _isValidChild()
isNoneOrShape = isValidChildOrNone = _isValidChildOrNone()
isAnything = _isAnything()
isNothing = _isNothing()
isXYCoord = SequenceOf(isNumber,lo=2,hi=2,emptyOK=0)
isBoxAnchor = OneOf('nw','n','ne','w','c','e','sw','s','se', 'autox', 'autoy')
isNoneOrString = NoneOr(isString,'NoneOrString')
isNoneOrListOfNoneOrStrings=SequenceOf(isNoneOrString,'isNoneOrListOfNoneOrStrings',NoneOK=1)
isListOfNoneOrString=SequenceOf(isNoneOrString,'isListOfNoneOrString',NoneOK=0)
isNoneOrListOfNoneOrNumbers=SequenceOf(isNumberOrNone,'isNoneOrListOfNoneOrNumbers',NoneOK=1)
isCallable = _isCallable()
isNoneOrCallable = NoneOr(isCallable)
isStringOrCallable=EitherOr((isString,isCallable),'isStringOrCallable')
isStringOrCallableOrNone=NoneOr(isStringOrCallable,'isStringOrCallableNone')
isStringOrNone=NoneOr(isString,'isStringOrNone')
isNormalDate=_isNormalDate()
isNotSet=_isNotSet()
@@ -0,0 +1,185 @@
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/yaml.py
# parses "Yet Another Markup Language" into a list of tuples.
# Each tuple says what the data is e.g.
# ('Paragraph', 'Heading1', 'Why Reportlab Rules')
# and the pattern depends on type.
"""
.h1 Welcome to YAML!
YAML is "Yet Another Markup Language" - a markup language
which is easier to type in than XML, yet gives us a
reasonable selection of formats.
The general rule is that if a line begins with a '.',
it requires special processing. Otherwise lines
are concatenated to paragraphs, and blank lines
separate paragraphs.
If the line ".foo bar bletch" is encountered,
it immediately ends and writes out any current
paragraph.
It then looks for a parser method called 'foo';
if found, it is called with arguments (bar, bletch).
If this is not found, it assumes that 'foo' is a
paragraph style, and the text for the first line
of the paragraph is 'bar bletch'. It would be
up to the formatter to decide whether on not 'foo'
was a valid paragraph.
Special commands understood at present are:
dot image filename
- adds the image to the document
dot beginPre Code
- begins a Preformatted object in style 'Code'
dot endPre
- ends a preformatted object.
"""
__version__='3.3.0'
import sys
#modes:
PLAIN = 1
PREFORMATTED = 2
BULLETCHAR = '\267' # assumes font Symbol, but works on all platforms
class BaseParser:
""""Simplest possible parser with only the most basic options.
This defines the line-handling abilities and basic mechanism.
The class YAMLParser includes capabilities for a fairly rich
story."""
def __init__(self):
self.reset()
def reset(self):
self._lineNo = 0
self._style = 'Normal' # the default
self._results = []
self._buf = []
self._mode = PLAIN
def parseFile(self, filename):
#returns list of objects
data = open(filename, 'r').readlines()
for line in data:
#strip trailing newlines
self.readLine(line[:-1])
self.endPara()
return self._results
def parseText(self, textBlock):
"Parses the a possible multi-line text block"
lines = textBlock.split('\n')
for line in lines:
self.readLine(line)
self.endPara()
return self._results
def readLine(self, line):
#this is the inner loop
self._lineNo = self._lineNo + 1
stripped = line.lstrip()
if len(stripped) == 0:
if self._mode == PLAIN:
self.endPara()
else: #preformatted, append it
self._buf.append(line)
elif line[0]=='.':
# we have a command of some kind
self.endPara()
words = stripped[1:].split()
cmd, args = words[0], words[1:]
#is it a parser method?
if hasattr(self.__class__, cmd):
#this was very bad; any type error in the method was hidden
#we have to hack the traceback
try:
getattr(self,cmd)(*args)
except TypeError as err:
sys.stderr.write("Parser method: %s(*%s) %s at line %d\n" % (cmd, args, err, self._lineNo))
raise
else:
# assume it is a paragraph style -
# becomes the formatter's problem
self.endPara() #end the last one
words = stripped.split(' ', 1)
assert len(words)==2, "Style %s but no data at line %d" % (words[0], self._lineNo)
(styletag, data) = words
self._style = styletag[1:]
self._buf.append(data)
else:
#we have data, add to para
self._buf.append(line)
def endPara(self):
#ends the current paragraph, or preformatted block
text = ' '.join(self._buf)
if text:
if self._mode == PREFORMATTED:
#item 3 is list of lines
self._results.append(('PREFORMATTED', self._style,
'\n'.join(self._buf)))
else:
self._results.append(('PARAGRAPH', self._style, text))
self._buf = []
self._style = 'Normal'
def beginPre(self, stylename):
self._mode = PREFORMATTED
self._style = stylename
def endPre(self):
self.endPara()
self._mode = PLAIN
def image(self, filename):
self.endPara()
self._results.append(('IMAGE', filename))
class Parser(BaseParser):
"""This adds a basic set of "story" components compatible with HTML & PDF.
Images, spaces"""
def vSpace(self, points):
"""Inserts a vertical spacer"""
self._results.append(('VSpace', points))
def pageBreak(self):
"""Inserts a frame break"""
self._results.append(('PageBreak','blah')) # must be a tuple
def custom(self, moduleName, funcName):
"""Goes and gets the Python object and adds it to the story"""
self.endPara()
self._results.append(('Custom',moduleName, funcName))
def nextPageTemplate(self, templateName):
self._results.append(('NextPageTemplate',templateName))
def parseFile(filename):
p = Parser()
return p.parseFile(filename)
def parseText(textBlock):
p = Parser()
return p.parseText(textBlock)
if __name__=='__main__': #NORUNTESTS
if len(sys.argv) != 2:
results = parseText(__doc__)
else:
results = parseFile(sys.argv[1])
import pprint
pprint.pprint(results)