本文整理汇总了Python中reportlab.lib.utils.markfilename函数的典型用法代码示例。如果您正苦于以下问题:Python markfilename函数的具体用法?Python markfilename怎么用?Python markfilename使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了markfilename函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
def save(self,f=None):
if not hasattr(f,'write'):
file = open(f,'wb')
else:
file = f
if self.code[-1]!='showpage': self.clear()
self.code.insert(0,'''\
%%!PS-Adobe-3.0 EPSF-3.0
%%%%BoundingBox: 0 0 %d %d
%%%% Initialization:
/m {moveto} bind def
/l {lineto} bind def
/c {curveto} bind def
%s
''' % (self.width,self.height, PS_WinAnsiEncoding))
# for each font used, reencode the vectors
fontReencode = []
for fontName in self._fontsUsed:
fontReencode.append('WinAnsiEncoding /%s /%s RE' % (fontName, fontName))
self.code.insert(1, string.join(fontReencode, self._sep))
file.write(string.join(self.code,self._sep))
if file is not f:
file.close()
from reportlab.lib.utils import markfilename
markfilename(f,creatorcode='XPR3',filetype='EPSF')
示例2: save
def save(self, f=None):
if not hasattr(f, "write"):
file = open(f, "wb")
else:
file = f
if self.code[-1] != "showpage":
self.clear()
self.code.insert(
0,
"""\
%%!PS-Adobe-3.0 EPSF-3.0
%%%%BoundingBox: 0 0 %d %d
%%%% Initialization:
/m {moveto} bind def
/l {lineto} bind def
/c {curveto} bind def
"""
% (self.width, self.height),
)
self._t1_re_encode()
file.write(string.join(self.code, self._sep))
if file is not f:
file.close()
from reportlab.lib.utils import markfilename
markfilename(f, creatorcode="XPR3", filetype="EPSF")
示例3: test
def test():
def ext(x):
if x=='tiff': x='tif'
return x
#grab all drawings from the test module and write out.
#make a page of links in HTML to assist viewing.
import os
from reportlab.graphics import testshapes
getAllTestDrawings = testshapes.getAllTestDrawings
drawings = []
if not os.path.isdir('pmout'):
os.mkdir('pmout')
htmlTop = """<html><head><title>renderPM output results</title></head>
<body>
<h1>renderPM results of output</h1>
"""
htmlBottom = """</body>
</html>
"""
html = [htmlTop]
i = 0
#print in a loop, with their doc strings
for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_renderPM,'ft_get_face')):
fnRoot = 'renderPM%d' % i
if 1 or i==10:
w = int(drawing.width)
h = int(drawing.height)
html.append('<hr><h2>Drawing %s %d</h2>\n<pre>%s</pre>' % (name, i, docstring))
for k in ['gif','tiff', 'png', 'jpg', 'pct']:
if k in ['gif','png','jpg','pct']:
html.append('<p>%s format</p>\n' % string.upper(k))
try:
filename = '%s.%s' % (fnRoot, ext(k))
fullpath = os.path.join('pmout', filename)
if os.path.isfile(fullpath):
os.remove(fullpath)
if k=='pct':
from reportlab.lib.colors import white
drawToFile(drawing,fullpath,fmt=k,configPIL={'transparent':white})
else:
drawToFile(drawing,fullpath,fmt=k)
if k in ['gif','png','jpg']:
html.append('<img src="%s" border="1"><br>\n' % filename)
print 'wrote',fullpath
except AttributeError:
print 'Problem drawing %s file'%k
raise
if os.environ.get('RL_NOEPSPREVIEW','0')=='1': drawing.__dict__['preview'] = 0
drawing.save(formats=['eps','pdf'],outDir='pmout',fnRoot=fnRoot)
i = i + 1
#if i==10: break
html.append(htmlBottom)
htmlFileName = os.path.join('pmout', 'index.html')
open(htmlFileName, 'w').writelines(html)
if sys.platform=='mac':
from reportlab.lib.utils import markfilename
markfilename(htmlFileName,ext='HTML')
print 'wrote %s' % htmlFileName
示例4: save
def save(self,fn, preview=None, dviPreview=None):
cf = not hasattr(fn,'write')
if cf:
f = open(fn,'wb')
else:
f = fn
try:
ps = self._postscript(dviPreview)
if preview:
import struct
A = (b'\xc5',b'\xd0',b'\xd3',b'\xc6')if isPy3 else (chr(0xc5),chr(0xd0),chr(0xd3),chr(0xc6))
hdr=struct.pack(*(
("<4c7i",)
+A
+( 32,len(ps),0,0,32+len(ps),len(preview),0xffff)
)
)
f.write(hdr)
f.write(rawBytes(ps))
f.write(preview)
else:
f.write(rawBytes(ps))
finally:
if cf:
f.close()
if cf and os.name=='mac':
from reportlab.lib.utils import markfilename
markfilename(fn,ext='EPSF')
示例5: saveToFile
def saveToFile(self, fn, fmt=None):
im = self.toPIL()
if fmt is None:
if type(fn) is not StringType:
raise ValueError, "Invalid type '%s' for fn when fmt is None" % type(fn)
fmt = os.path.splitext(fn)[1]
if fmt.startswith("."):
fmt = fmt[1:]
configPIL = self.configPIL or {}
fmt = string.upper(fmt)
if fmt in ("GIF", "TIFFP"):
im = _convert2pilp(im)
if fmt == "TIFFP":
fmt = "TIFF"
if fmt in ("PCT", "PICT"):
return _saveAsPICT(im, fn, fmt, transparent=configPIL.get("transparent", None))
elif fmt in ["PNG", "TIFF", "BMP", "PPM", "TIF"]:
if fmt == "TIF":
fmt = "TIFF"
if fmt == "PNG":
try:
from PIL import PngImagePlugin
except ImportError:
import PngImagePlugin
elif fmt == "BMP":
try:
from PIL import BmpImagePlugin
except ImportError:
import BmpImagePlugin
elif fmt in ("JPG", "JPEG"):
fmt = "JPEG"
elif fmt in ("GIF",):
pass
else:
raise RenderPMError, "Unknown image kind %s" % fmt
if fmt == "TIFF":
tc = configPIL.get("transparent", None)
if tc:
from PIL import ImageChops, Image
T = 768 * [0]
for o, c in zip((0, 256, 512), tc.bitmap_rgb()):
T[o + c] = 255
# if type(fn) is type(''): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF')
im = Image.merge(
"RGBA", im.split() + (ImageChops.invert(im.point(T).convert("L").point(255 * [0] + [255])),)
)
# if type(fn) is type(''): im.save(fn+'_masked.gif','GIF')
for a, d in ("resolution", self._dpi), ("resolution unit", "inch"):
configPIL[a] = configPIL.get(a, d)
apply(im.save, (fn, fmt), configPIL)
if not hasattr(fn, "write") and os.name == "mac":
from reportlab.lib.utils import markfilename
markfilename(fn, ext=fmt)
示例6: _saveAsPICT
def _saveAsPICT(im,fn,fmt,transparent=None):
im = _convert2pilp(im)
cols, rows = im.size
#s = _renderPM.pil2pict(cols,rows,im.tostring(),im.im.getpalette(),transparent is not None and Color2Hex(transparent) or -1)
s = _renderPM.pil2pict(cols,rows,im.tostring(),im.im.getpalette())
if not hasattr(fn,'write'):
open(os.path.splitext(fn)[0]+'.'+string.lower(fmt),'wb').write(s)
if os.name=='mac':
from reportlab.lib.utils import markfilename
markfilename(fn,ext='PICT')
else:
fn.write(s)
示例7: saveToFile
def saveToFile(self,fn,fmt=None):
im = self.toPIL()
if fmt is None:
if type(fn) is not StringType:
raise ValueError, "Invalid type '%s' for fn when fmt is None" % type(fn)
fmt = os.path.splitext(fn)[1]
if fmt.startswith('.'): fmt = fmt[1:]
configPIL = self.configPIL or {}
fmt = string.upper(fmt)
if fmt in ('GIF','TIFFP'):
im = _convert2pilp(im)
if fmt=='TIFFP': fmt='TIFF'
if fmt in ('PCT','PICT'):
return _saveAsPICT(im,fn,fmt,transparent=configPIL.get('transparent',None))
elif fmt in ['PNG','TIFF','BMP', 'PPM', 'TIF']:
if fmt=='TIF': fmt = 'TIFF'
if fmt=='PNG':
try:
from PIL import PngImagePlugin
except ImportError:
import PngImagePlugin
elif fmt=='BMP':
try:
from PIL import BmpImagePlugin
except ImportError:
import BmpImagePlugin
elif fmt in ('JPG','JPEG'):
fmt = 'JPEG'
elif fmt in ('GIF',):
pass
else:
raise RenderPMError,"Unknown image kind %s" % fmt
if fmt=='TIFF':
tc = configPIL.get('transparent',None)
if tc:
from PIL import ImageChops, Image
T = 768*[0]
for o, c in zip((0,256,512), tc.bitmap_rgb()):
T[o+c] = 255
#if type(fn) is type(''): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF')
im = Image.merge('RGBA', im.split()+(ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])),))
#if type(fn) is type(''): im.save(fn+'_masked.gif','GIF')
for a,d in ('resolution',self._dpi),('resolution unit','inch'):
configPIL[a] = configPIL.get(a,d)
apply(im.save,(fn,fmt),configPIL)
if not hasattr(fn,'write') and os.name=='mac':
from reportlab.lib.utils import markfilename
markfilename(fn,ext=fmt)
示例8: save
def save(self,f=None):
if not hasattr(f,'write'):
_f = open(f,'wb')
else:
_f = f
if self.code[-1]!='showpage': self.clear()
self.code.insert(0,'''\
%%!PS-Adobe-3.0 EPSF-3.0
%%%%BoundingBox: 0 0 %d %d
%%%% Initialization:
/m {moveto} bind def
/l {lineto} bind def
/c {curveto} bind def
''' % (self.width,self.height))
self._t1_re_encode()
_f.write(rawBytes(self._sep.join(self.code)))
if _f is not f:
_f.close()
from reportlab.lib.utils import markfilename
markfilename(f,creatorcode='XPR3',filetype='EPSF')
示例9: test
def test():
def ext(x):
if x=='tiff': x='tif'
return x
#grab all drawings from the test module and write out.
#make a page of links in HTML to assist viewing.
import os
from reportlab.graphics import testshapes
getAllTestDrawings = testshapes.getAllTestDrawings
drawings = []
if not os.path.isdir('pmout'):
os.mkdir('pmout')
htmlTop = """<html><head><title>renderPM output results</title></head>
<body>
<h1>renderPM results of output</h1>
"""
htmlBottom = """</body>
</html>
"""
html = [htmlTop]
names = {}
argv = sys.argv[1:]
E = [a for a in argv if a.startswith('--ext=')]
if not E:
E = ['gif','tiff', 'png', 'jpg', 'pct', 'py', 'svg']
else:
for a in E:
argv.remove(a)
E = (','.join([a[6:] for a in E])).split(',')
#print in a loop, with their doc strings
for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_renderPM,'ft_get_face')):
i = names[name] = names.setdefault(name,0)+1
if i>1: name += '.%02d' % (i-1)
if argv and name not in argv: continue
fnRoot = name
w = int(drawing.width)
h = int(drawing.height)
html.append('<hr><h2>Drawing %s</h2>\n<pre>%s</pre>' % (name, docstring))
for k in E:
if k in ['gif','png','jpg','pct']:
html.append('<p>%s format</p>\n' % string.upper(k))
try:
filename = '%s.%s' % (fnRoot, ext(k))
fullpath = os.path.join('pmout', filename)
if os.path.isfile(fullpath):
os.remove(fullpath)
if k=='pct':
from reportlab.lib.colors import white
drawToFile(drawing,fullpath,fmt=k,configPIL={'transparent':white})
elif k in ['py','svg']:
drawing.save(formats=['py','svg'],outDir='pmout',fnRoot=fnRoot)
else:
drawToFile(drawing,fullpath,fmt=k)
if k in ['gif','png','jpg']:
html.append('<img src="%s" border="1"><br>\n' % filename)
elif k=='py':
html.append('<a href="%s">python source</a><br>\n' % filename)
elif k=='svg':
html.append('<a href="%s">SVG</a><br>\n' % filename)
print 'wrote',fullpath
except AttributeError:
print 'Problem drawing %s file'%k
raise
if os.environ.get('RL_NOEPSPREVIEW','0')=='1': drawing.__dict__['preview'] = 0
drawing.save(formats=['eps','pdf'],outDir='pmout',fnRoot=fnRoot)
html.append(htmlBottom)
htmlFileName = os.path.join('pmout', 'index.html')
open(htmlFileName, 'w').writelines(html)
if sys.platform=='mac':
from reportlab.lib.utils import markfilename
markfilename(htmlFileName,ext='HTML')
print 'wrote %s' % htmlFileName
示例10: test
def test():
def ext(x):
if x == "tiff":
x = "tif"
return x
# grab all drawings from the test module and write out.
# make a page of links in HTML to assist viewing.
import os
from reportlab.graphics import testshapes
getAllTestDrawings = testshapes.getAllTestDrawings
drawings = []
if not os.path.isdir("pmout"):
os.mkdir("pmout")
htmlTop = """<html><head><title>renderPM output results</title></head>
<body>
<h1>renderPM results of output</h1>
"""
htmlBottom = """</body>
</html>
"""
html = [htmlTop]
names = {}
argv = sys.argv[1:]
E = [a for a in argv if a.startswith("--ext=")]
if not E:
E = ["gif", "tiff", "png", "jpg", "pct", "py", "svg"]
else:
for a in E:
argv.remove(a)
E = (",".join([a[6:] for a in E])).split(",")
# print in a loop, with their doc strings
for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_renderPM, "ft_get_face")):
i = names[name] = names.setdefault(name, 0) + 1
if i > 1:
name += ".%02d" % (i - 1)
if argv and name not in argv:
continue
fnRoot = name
w = int(drawing.width)
h = int(drawing.height)
html.append("<hr><h2>Drawing %s</h2>\n<pre>%s</pre>" % (name, docstring))
for k in E:
if k in ["gif", "png", "jpg", "pct"]:
html.append("<p>%s format</p>\n" % string.upper(k))
try:
filename = "%s.%s" % (fnRoot, ext(k))
fullpath = os.path.join("pmout", filename)
if os.path.isfile(fullpath):
os.remove(fullpath)
if k == "pct":
from reportlab.lib.colors import white
drawToFile(drawing, fullpath, fmt=k, configPIL={"transparent": white})
elif k in ["py", "svg"]:
drawing.save(formats=["py", "svg"], outDir="pmout", fnRoot=fnRoot)
else:
drawToFile(drawing, fullpath, fmt=k)
if k in ["gif", "png", "jpg"]:
html.append('<img src="%s" border="1"><br>\n' % filename)
elif k == "py":
html.append('<a href="%s">python source</a><br>\n' % filename)
elif k == "svg":
html.append('<a href="%s">SVG</a><br>\n' % filename)
print "wrote", fullpath
except AttributeError:
print "Problem drawing %s file" % k
raise
if os.environ.get("RL_NOEPSPREVIEW", "0") == "1":
drawing.__dict__["preview"] = 0
drawing.save(formats=["eps", "pdf"], outDir="pmout", fnRoot=fnRoot)
html.append(htmlBottom)
htmlFileName = os.path.join("pmout", "index.html")
open(htmlFileName, "w").writelines(html)
if sys.platform == "mac":
from reportlab.lib.utils import markfilename
markfilename(htmlFileName, ext="HTML")
print "wrote %s" % htmlFileName
示例11: test
def test(outDir='pmout', shout=False):
def ext(x):
if x=='tiff': x='tif'
return x
#grab all drawings from the test module and write out.
#make a page of links in HTML to assist viewing.
import os
from reportlab.graphics import testshapes
from reportlab.rl_config import verbose
getAllTestDrawings = testshapes.getAllTestDrawings
drawings = []
if not os.path.isdir(outDir):
os.mkdir(outDir)
htmlTop = """<html><head><title>renderPM output results</title></head>
<body>
<h1>renderPM results of output</h1>
"""
htmlBottom = """</body>
</html>
"""
html = [htmlTop]
names = {}
argv = sys.argv[1:]
E = [a for a in argv if a.startswith('--ext=')]
if not E:
E = ['gif','tiff', 'png', 'jpg', 'pct', 'py', 'svg']
else:
for a in E:
argv.remove(a)
E = (','.join([a[6:] for a in E])).split(',')
errs = []
import traceback
from xml.sax.saxutils import escape
def handleError(name,fmt):
msg = 'Problem drawing %s fmt=%s file'%(name,fmt)
if shout or verbose>2: print(msg)
errs.append('<br/><h2 style="color:red">%s</h2>' % msg)
buf = getStringIO()
traceback.print_exc(file=buf)
errs.append('<pre>%s</pre>' % escape(buf.getvalue()))
#print in a loop, with their doc strings
for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_renderPM,'ft_get_face')):
i = names[name] = names.setdefault(name,0)+1
if i>1: name += '.%02d' % (i-1)
if argv and name not in argv: continue
fnRoot = name
w = int(drawing.width)
h = int(drawing.height)
html.append('<hr><h2>Drawing %s</h2>\n<pre>%s</pre>' % (name, docstring))
for k in E:
if k in ['gif','png','jpg','pct']:
html.append('<p>%s format</p>\n' % k.upper())
try:
filename = '%s.%s' % (fnRoot, ext(k))
fullpath = os.path.join(outDir, filename)
if os.path.isfile(fullpath):
os.remove(fullpath)
if k=='pct':
from reportlab.lib.colors import white
drawToFile(drawing,fullpath,fmt=k,configPIL={'transparent':white})
elif k in ['py','svg']:
drawing.save(formats=['py','svg'],outDir=outDir,fnRoot=fnRoot)
else:
drawToFile(drawing,fullpath,fmt=k)
if k in ['gif','png','jpg']:
html.append('<img src="%s" border="1"><br>\n' % filename)
elif k=='py':
html.append('<a href="%s">python source</a><br>\n' % filename)
elif k=='svg':
html.append('<a href="%s">SVG</a><br>\n' % filename)
if shout or verbose>2: print('wrote %s'%ascii(fullpath))
except AttributeError:
handleError(name,k)
if os.environ.get('RL_NOEPSPREVIEW','0')=='1': drawing.__dict__['preview'] = 0
for k in ('eps', 'pdf'):
try:
drawing.save(formats=[k],outDir=outDir,fnRoot=fnRoot)
except:
handleError(name,k)
if errs:
html[0] = html[0].replace('</h1>',' <a href="#errors" style="color: red">(errors)</a></h1>')
html.append('<a name="errors"/>')
html.extend(errs)
html.append(htmlBottom)
htmlFileName = os.path.join(outDir, 'pm-index.html')
open(htmlFileName, 'w').writelines(html)
if sys.platform=='mac':
from reportlab.lib.utils import markfilename
markfilename(htmlFileName,ext='HTML')
if shout or verbose>2: print('wrote %s' % htmlFileName)
示例12: saveToFile
def saveToFile(self,fn,fmt=None):
im = self.toPIL()
if fmt is None:
if not isinstance(fn,str):
raise ValueError("Invalid value '%s' for fn when fmt is None" % ascii(fn))
fmt = os.path.splitext(fn)[1]
if fmt.startswith('.'): fmt = fmt[1:]
configPIL = self.configPIL or {}
configPIL.setdefault('preConvertCB',None)
preConvertCB=configPIL.pop('preConvertCB')
if preConvertCB:
im = preConvertCB(im)
fmt = fmt.upper()
if fmt in ('GIF',):
im = _convert2pilp(im)
elif fmt in ('TIFF','TIFFP','TIFFL','TIF','TIFF1'):
if fmt.endswith('P'):
im = _convert2pilp(im)
elif fmt.endswith('L'):
im = _convert2pilL(im)
elif fmt.endswith('1'):
im = _convert2pil1(im)
fmt='TIFF'
elif fmt in ('PCT','PICT'):
return _saveAsPICT(im,fn,fmt,transparent=configPIL.get('transparent',None))
elif fmt in ('PNG','BMP', 'PPM'):
if fmt=='PNG':
try:
from PIL import PngImagePlugin
except ImportError:
import PngImagePlugin
elif fmt=='BMP':
try:
from PIL import BmpImagePlugin
except ImportError:
import BmpImagePlugin
elif fmt in ('JPG','JPEG'):
fmt = 'JPEG'
elif fmt in ('GIF',):
pass
else:
raise RenderPMError("Unknown image kind %s" % fmt)
if fmt=='TIFF':
tc = configPIL.get('transparent',None)
if tc:
from PIL import ImageChops, Image
T = 768*[0]
for o, c in zip((0,256,512), tc.bitmap_rgb()):
T[o+c] = 255
#if isinstance(fn,str): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF')
im = Image.merge('RGBA', im.split()+(ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])),))
#if isinstance(fn,str): im.save(fn+'_masked.gif','GIF')
for a,d in ('resolution',self._dpi),('resolution unit','inch'):
configPIL[a] = configPIL.get(a,d)
configPIL.setdefault('chops_invert',0)
if configPIL.pop('chops_invert'):
from PIL import ImageChops
im = ImageChops.invert(im)
configPIL.setdefault('preSaveCB',None)
preSaveCB=configPIL.pop('preSaveCB')
if preSaveCB:
im = preSaveCB(im)
im.save(fn,fmt,**configPIL)
if not hasattr(fn,'write') and os.name=='mac':
from reportlab.lib.utils import markfilename
markfilename(fn,ext=fmt)
示例13: test
def test():
def ext(x):
if x == "tiff":
x = "tif"
return x
# grab all drawings from the test module and write out.
# make a page of links in HTML to assist viewing.
import os
from reportlab.graphics import testshapes
getAllTestDrawings = testshapes.getAllTestDrawings
drawings = []
if not os.path.isdir("pmout"):
os.mkdir("pmout")
htmlTop = """<html><head><title>renderPM output results</title></head>
<body>
<h1>renderPM results of output</h1>
"""
htmlBottom = """</body>
</html>
"""
html = [htmlTop]
i = 0
# print in a loop, with their doc strings
for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_renderPM, "ft_get_face")):
fnRoot = "renderPM%d" % i
if 1 or i == 10:
w = int(drawing.width)
h = int(drawing.height)
html.append("<hr><h2>Drawing %s %d</h2>\n<pre>%s</pre>" % (name, i, docstring))
for k in ["gif", "tiff", "png", "jpg", "pct"]:
if k in ["gif", "png", "jpg", "pct"]:
html.append("<p>%s format</p>\n" % string.upper(k))
try:
filename = "%s.%s" % (fnRoot, ext(k))
fullpath = os.path.join("pmout", filename)
if os.path.isfile(fullpath):
os.remove(fullpath)
if k == "pct":
from reportlab.lib.colors import white
drawToFile(drawing, fullpath, fmt=k, configPIL={"transparent": white})
else:
drawToFile(drawing, fullpath, fmt=k)
if k in ["gif", "png", "jpg"]:
html.append('<img src="%s" border="1"><br>\n' % filename)
print "wrote", fullpath
except AttributeError:
print "Problem drawing %s file" % k
raise
if os.environ.get("RL_NOEPSPREVIEW", "0") == "1":
drawing.__dict__["preview"] = 0
drawing.save(formats=["eps", "pdf"], outDir="pmout", fnRoot=fnRoot)
i = i + 1
# if i==10: break
html.append(htmlBottom)
htmlFileName = os.path.join("pmout", "index.html")
open(htmlFileName, "w").writelines(html)
if sys.platform == "mac":
from reportlab.lib.utils import markfilename
markfilename(htmlFileName, ext="HTML")
print "wrote %s" % htmlFileName
示例14: test
#.........这里部分代码省略.........
# grab all drawings from the test module and write out.
# make a page of links in HTML to assist viewing.
import os
from reportlab.graphics import testshapes
from reportlab.rl_config import verbose
getAllTestDrawings = testshapes.getAllTestDrawings
drawings = []
if not os.path.isdir(outDir):
os.mkdir(outDir)
htmlTop = """<html><head><title>renderPM output results</title></head>
<body>
<h1>renderPM results of output</h1>
"""
htmlBottom = """</body>
</html>
"""
html = [htmlTop]
names = {}
argv = sys.argv[1:]
E = [a for a in argv if a.startswith("--ext=")]
if not E:
E = ["gif", "tiff", "png", "jpg", "pct", "py", "svg"]
else:
for a in E:
argv.remove(a)
E = (",".join([a[6:] for a in E])).split(",")
errs = []
import traceback
from xml.sax.saxutils import escape
def handleError(name, fmt):
msg = "Problem drawing %s fmt=%s file" % (name, fmt)
if shout or verbose > 2:
print(msg)
errs.append('<br/><h2 style="color:red">%s</h2>' % msg)
buf = getStringIO()
traceback.print_exc(file=buf)
errs.append("<pre>%s</pre>" % escape(buf.getvalue()))
# print in a loop, with their doc strings
for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_renderPM, "ft_get_face")):
i = names[name] = names.setdefault(name, 0) + 1
if i > 1:
name += ".%02d" % (i - 1)
if argv and name not in argv:
continue
fnRoot = name
w = int(drawing.width)
h = int(drawing.height)
html.append("<hr><h2>Drawing %s</h2>\n<pre>%s</pre>" % (name, docstring))
for k in E:
if k in ["gif", "png", "jpg", "pct"]:
html.append("<p>%s format</p>\n" % k.upper())
try:
filename = "%s.%s" % (fnRoot, ext(k))
fullpath = os.path.join(outDir, filename)
if os.path.isfile(fullpath):
os.remove(fullpath)
if k == "pct":
from reportlab.lib.colors import white
drawToFile(drawing, fullpath, fmt=k, configPIL={"transparent": white})
elif k in ["py", "svg"]:
drawing.save(formats=["py", "svg"], outDir=outDir, fnRoot=fnRoot)
else:
drawToFile(drawing, fullpath, fmt=k)
if k in ["gif", "png", "jpg"]:
html.append('<img src="%s" border="1"><br>\n' % filename)
elif k == "py":
html.append('<a href="%s">python source</a><br>\n' % filename)
elif k == "svg":
html.append('<a href="%s">SVG</a><br>\n' % filename)
if shout or verbose > 2:
print("wrote %s" % ascii(fullpath))
except AttributeError:
handleError(name, k)
if os.environ.get("RL_NOEPSPREVIEW", "0") == "1":
drawing.__dict__["preview"] = 0
for k in ("eps", "pdf"):
try:
drawing.save(formats=[k], outDir=outDir, fnRoot=fnRoot)
except:
handleError(name, k)
if errs:
html[0] = html[0].replace("</h1>", ' <a href="#errors" style="color: red">(errors)</a></h1>')
html.append('<a name="errors"/>')
html.extend(errs)
html.append(htmlBottom)
htmlFileName = os.path.join(outDir, "pm-index.html")
open(htmlFileName, "w").writelines(html)
if sys.platform == "mac":
from reportlab.lib.utils import markfilename
markfilename(htmlFileName, ext="HTML")
if shout or verbose > 2:
print("wrote %s" % htmlFileName)
示例15: saveToFile
def saveToFile(self, fn, fmt=None):
im = self.toPIL()
if fmt is None:
if not isinstance(fn, str):
raise ValueError("Invalid value '%s' for fn when fmt is None" % ascii(fn))
fmt = os.path.splitext(fn)[1]
if fmt.startswith("."):
fmt = fmt[1:]
configPIL = self.configPIL or {}
configPIL.setdefault("preConvertCB", None)
preConvertCB = configPIL.pop("preConvertCB")
if preConvertCB:
im = preConvertCB(im)
fmt = fmt.upper()
if fmt in ("GIF",):
im = _convert2pilp(im)
elif fmt in ("TIFF", "TIFFP", "TIFFL", "TIF", "TIFF1"):
if fmt.endswith("P"):
im = _convert2pilp(im)
elif fmt.endswith("L"):
im = _convert2pilL(im)
elif fmt.endswith("1"):
im = _convert2pil1(im)
fmt = "TIFF"
elif fmt in ("PCT", "PICT"):
return _saveAsPICT(im, fn, fmt, transparent=configPIL.get("transparent", None))
elif fmt in ("PNG", "BMP", "PPM"):
if fmt == "PNG":
try:
from PIL import PngImagePlugin
except ImportError:
import PngImagePlugin
elif fmt == "BMP":
try:
from PIL import BmpImagePlugin
except ImportError:
import BmpImagePlugin
elif fmt in ("JPG", "JPEG"):
fmt = "JPEG"
elif fmt in ("GIF",):
pass
else:
raise RenderPMError("Unknown image kind %s" % fmt)
if fmt == "TIFF":
tc = configPIL.get("transparent", None)
if tc:
from PIL import ImageChops, Image
T = 768 * [0]
for o, c in zip((0, 256, 512), tc.bitmap_rgb()):
T[o + c] = 255
# if isinstance(fn,str): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF')
im = Image.merge(
"RGBA", im.split() + (ImageChops.invert(im.point(T).convert("L").point(255 * [0] + [255])),)
)
# if isinstance(fn,str): im.save(fn+'_masked.gif','GIF')
for a, d in ("resolution", self._dpi), ("resolution unit", "inch"):
configPIL[a] = configPIL.get(a, d)
configPIL.setdefault("chops_invert", 0)
if configPIL.pop("chops_invert"):
from PIL import ImageChops
im = ImageChops.invert(im)
configPIL.setdefault("preSaveCB", None)
preSaveCB = configPIL.pop("preSaveCB")
if preSaveCB:
im = preSaveCB(im)
im.save(fn, fmt, **configPIL)
if not hasattr(fn, "write") and os.name == "mac":
from reportlab.lib.utils import markfilename
markfilename(fn, ext=fmt)