示例#1
0
 def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1):
     """If size to draw at not specified, get it from the image."""
     self.hAlign = 'CENTER'
     self._mask = mask
     fp = hasattr(filename,'read')
     if fp:
         self._file = filename
         self.filename = repr(filename)
     else:
         self._file = self.filename = filename
     if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
         # if it is a JPEG, will be inlined within the file -
         # but we still need to know its size now
         from reportlab.lib.utils import open_for_read
         f = open_for_read(filename, 'b')
         try:
             try:
                 info = pdfutils.readJPEGInfo(f)
             except:
                 #couldn't read as a JPEG, try like normal
                 self._setup(width,height,kind,lazy)
                 return
         finally:
             f.close()
         self.imageWidth = info[0]
         self.imageHeight = info[1]
         self._img = None
         self._setup(width,height,kind,0)
     elif fp:
         self._setup(width,height,kind,0)
     else:
         self._setup(width,height,kind,lazy)
示例#2
0
def cacheImageFile(filename, returnInMemory=0, IMG=None):
    "Processes image as if for encoding, saves to a file with .a85 extension."

    cachedname = os.path.splitext(filename)[0] + (rl_config.useA85 and '.a85'
                                                  or '.bin')
    if filename == cachedname:
        if cachedImageExists(filename):
            from reportlab.lib.utils import open_for_read
            if returnInMemory:
                return filter(None,
                              open_for_read(cachedname).read().split('\r\n'))
        else:
            raise IOError('No such cached image %s' % filename)
    else:
        if rl_config.useA85:
            code = makeA85Image(filename, IMG)
        else:
            code = makeRawImage(filename, IMG)
        if returnInMemory: return code

        #save it to a file
        f = open(cachedname, 'wb')
        f.write('\r\n'.join(code) + '\r\n')
        f.close()
        if rl_config.verbose:
            print('cached image as %s' % cachedname)
示例#3
0
 def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1):
     """If size to draw at not specified, get it from the image."""
     self.hAlign = 'CENTER'
     self._mask = mask
     fp = hasattr(filename,'read')
     if fp:
         self._file = filename
         self.filename = `filename`
     else:
         self._file = self.filename = filename
     if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
         # if it is a JPEG, will be inlined within the file -
         # but we still need to know its size now
         from reportlab.lib.utils import open_for_read
         f = open_for_read(filename, 'b')
         try:
             try:
                 info = pdfutils.readJPEGInfo(f)
             except:
                 #couldn't read as a JPEG, try like normal
                 self._setup(width,height,kind,lazy)
                 return
         finally:
             f.close()
         self.imageWidth = info[0]
         self.imageHeight = info[1]
         self._img = None
         self._setup(width,height,kind,0)
     elif fp:
         self._setup(width,height,kind,0)
     else:
         self._setup(width,height,kind,lazy)
示例#4
0
 def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1):
     """If size to draw at not specified, get it from the image."""
     self.hAlign = 'CENTER'
     self._mask = mask
     # if it is a JPEG, will be inlined within the file -
     # but we still need to know its size now
     fp = hasattr(filename,'read')
     if fp:
         self._file = filename
         self.filename = `filename`
     else:
         self._file = self.filename = filename
     if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
         from reportlab.lib.utils import open_for_read
         f = open_for_read(filename, 'b')
         try:
             info = pdfutils.readJPEGInfo(f)
         except:  #this is where we normally find a JPEG is corrupt.
             #if so, include filename to help people track it down.
             raise ValueError("Corrupt JPEG '%s', pdfutils.readJPEGInfo failed." % self.filename)
         f.close()
         self.imageWidth = info[0]
         self.imageHeight = info[1]
         self._img = None
         self._setup(width,height,kind,0)
     elif fp:
         self._setup(width,height,kind,0)
     else:
         self._setup(width,height,kind,lazy)
    def test0(self):
        "Test if pythonpoint.pdf can be created from pythonpoint.xml."

        join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
        rlDir = abspath(dirname(reportlab.__file__))
        from reportlab.tools.pythonpoint import pythonpoint
        from reportlab.lib.utils import isCompactDistro, open_for_read
        ppDir = dirname(pythonpoint.__file__)
        xml = join(ppDir, 'demos', 'pythonpoint.xml')
        datafilename = 'pythonpoint.pdf'
        outDir = outputfile('')
        if isCompactDistro():
            cwd = None
            xml = open_for_read(xml)
        else:
            cwd = os.getcwd()
            os.chdir(join(ppDir, 'demos'))
        pdf = join(outDir, datafilename)
        if isfile(pdf): os.remove(pdf)
        pythonpoint.process(xml,
                            outDir=outDir,
                            verbose=0,
                            datafilename=datafilename)
        if cwd: os.chdir(cwd)
        assert os.path.exists(pdf)
示例#6
0
def TTFOpenFile(fn):
    '''Opens a TTF file possibly after searching TTFSearchPath
    returns (filename,file)
    '''
    from reportlab.lib.utils import rl_isfile, open_for_read
    try:
        f = open_for_read(fn,'rb')
        return fn, f
    except IOError:
        import os
        if not os.path.isabs(fn):
            for D in rl_config.TTFSearchPath:
                tfn = os.path.join(D,fn)
                if rl_isfile(tfn):
                    f = open_for_read(tfn,'rb')
                    return tfn, f
        raise TTFError('Can\'t open file "%s"' % fn)
示例#7
0
def TTFOpenFile(fn):
    '''Opens a TTF file possibly after searching TTFSearchPath
    returns (filename,file)
    '''
    from reportlab.lib.utils import rl_isfile, open_for_read
    try:
        f = open_for_read(fn, 'rb')
        return fn, f
    except IOError:
        import os
        if not os.path.isabs(fn):
            for D in rl_config.TTFSearchPath:
                tfn = os.path.join(D, fn)
                if rl_isfile(tfn):
                    f = open_for_read(tfn, 'rb')
                    return tfn, f
        raise TTFError('Can\'t open file "%s"' % fn)
def cacheImageFile(filename, returnInMemory=0, IMG=None):
    "Processes image as if for encoding, saves to a file with .a85 extension."

    from reportlab.lib.utils import PIL_Image, open_for_read
    import zlib

    cachedname = os.path.splitext(filename)[0] + '.a85'
    if filename==cachedname:
        if cachedImageExists(filename):
            if returnInMemory: return split(open_for_read(cachedname).read(),LINEEND)[:-1]
        else:
            raise IOError, 'No such cached image %s' % filename
    else:
        img1 = PIL_Image.open(open_for_read(filename))
        img = img1.convert('RGB')
        if IMG is not None: IMG.append(img)
        imgwidth, imgheight = img.size
        code = []
        code.append('BI')   # begin image
        # this describes what is in the image itself
        code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight))
        code.append('ID')
        #use a flate filter and Ascii Base 85
        raw = img.tostring()
        assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image")
        compressed = zlib.compress(raw)   #this bit is very fast...
        encoded = _AsciiBase85Encode(compressed) #...sadly this isn't

        #write in blocks of 60 characters per line
        outstream = getStringIO(encoded)
        dataline = outstream.read(60)
        while dataline <> "":
            code.append(dataline)
            dataline = outstream.read(60)

        code.append('EI')
        if returnInMemory: return code

        #save it to a file
        f = open(cachedname,'wb')
        f.write(join(code, LINEEND)+LINEEND)
        f.close()
        if rl_config.verbose:
            print 'cached image as %s' % cachedname
示例#9
0
 def readFields(self,fileName):
     import csv
     from reportlab.lib.utils import open_for_read
     if hasattr(fileName,'read'):
         f=fileName
     else:
         f=open_for_read(fileName, "rb")
     ROWS=[list(map(str.strip,row)) for row in csv.reader(f)][1:]
     if f is not fileName: f.close()
     return ROWS
示例#10
0
 def readFields(self, fileName):
     import csv
     from reportlab.lib.utils import open_for_read
     if hasattr(fileName, 'read'):
         f = fileName
     else:
         f = open_for_read(fileName, "rb")
     ROWS = [list(map(str.strip, row)) for row in csv.reader(f)][1:]
     if f is not fileName: f.close()
     return ROWS
示例#11
0
文件: csv.py 项目: AndyKovv/hostel
def read(fn,sep=',',conv=0):
    '''
    read the csv file fn and return the fields as a list of lists.
    sep is the separator to use and conv determines whether an attempt is made to convert
    numeric fields.
    '''
    from reportlab.lib.utils import open_for_read
    f = open_for_read(fn,'t')

    F = []
    for l in f.readlines():
        F.append(_processLine(l,sep,conv))

    if f is not fn: f.close()
    return F
示例#12
0
def read(fn, sep=',', conv=0):
    '''
    read the csv file fn and return the fields as a list of lists.
    sep is the separator to use and conv determines whether an attempt is made to convert
    numeric fields.
    '''
    from reportlab.lib.utils import open_for_read
    f = open_for_read(fn, 't')

    F = []
    for l in f.readlines():
        F.append(_processLine(l, sep, conv))

    if f is not fn: f.close()
    return F
示例#13
0
    def test0(self):
        "Test if pythonpoint.pdf can be created from pythonpoint.xml."

        join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
        from tools.pythonpoint import pythonpoint
        from reportlab.lib.utils import isCompactDistro, open_for_read
        ppDir = dirname(pythonpoint.__file__)
        xml = abspath(join(ppDir, 'demos', 'pythonpoint.xml'))
        datafilename = 'pythonpoint.pdf'
        outDir = outputfile('')
        if isCompactDistro():
            xml = open_for_read(xml)
        pdf = join(outDir, datafilename)
        if isfile(pdf): os.remove(pdf)
        pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
        assert os.path.exists(pdf)
示例#14
0
def cacheImageFile(filename, returnInMemory=0, IMG=None):
    "Processes image as if for encoding, saves to a file with .a85 extension."

    cachedname = os.path.splitext(filename)[0] + '.a85'
    if filename==cachedname:
        if cachedImageExists(filename):
            from reportlab.lib.utils import open_for_read
            if returnInMemory: return filter(None,open_for_read(cachedname).read().split(LINEEND))
        else:
            raise IOError, 'No such cached image %s' % filename
    else:
        code = makeA85Image(filename,IMG)
        if returnInMemory: return code

        #save it to a file
        f = open(cachedname,'wb')
        f.write(LINEEND.join(code)+LINEEND)
        f.close()
        if rl_config.verbose:
            print 'cached image as %s' % cachedname
示例#15
0
def cacheImageFile(filename, returnInMemory=0, IMG=None):
    "Processes image as if for encoding, saves to a file with .a85 extension."

    from reportlab.lib.utils import open_for_read
    import zlib

    cachedname = os.path.splitext(filename)[0] + '.a85'
    if filename==cachedname:
        if cachedImageExists(filename):
            if returnInMemory: return split(open_for_read(cachedname).read(),LINEEND)[:-1]
        else:
            raise IOError, 'No such cached image %s' % filename
    else:
        img = ImageReader(filename)
        if IMG is not None: IMG.append(img)

        imgwidth, imgheight = img.getSize()
        raw = img.getRGBData()

        code = []
        # this describes what is in the image itself
        code.append('BI')
        code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight))
        code.append('ID')
        #use a flate filter and Ascii Base 85
        assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image")
        compressed = zlib.compress(raw)   #this bit is very fast...
        encoded = _AsciiBase85Encode(compressed) #...sadly this may not be

        #append in blocks of 60 characters
        _chunker(encoded,code)

        code.append('EI')
        if returnInMemory: return code

        #save it to a file
        f = open(cachedname,'wb')
        f.write(join(code, LINEEND)+LINEEND)
        f.close()
        if rl_config.verbose:
            print 'cached image as %s' % cachedname
示例#16
0
 def __init__(self, fileName):
     if isinstance(fileName, PmlImageReader):
         self.__dict__ = fileName.__dict__   # borgize
         return
     #start wih lots of null private fields, to be populated by
     #the relevant engine.
     self.fileName = fileName
     self._image = None
     self._width = None
     self._height = None
     self._transparent = None
     self._data = None
     imageReaderFlags = 0
     if PILImage and isinstance(fileName, PILImage.Image):
         self._image = fileName
         self.fp = getattr(fileName, 'fp', None)
         try:
             self.fileName = self._image.fileName
         except AttributeError:
             self.fileName = 'PILIMAGE_%d' % id(self)
     else:
         try:
             self.fp = open_for_read(fileName, 'b')
             if isinstance(self.fp, StringIO.StringIO().__class__):
                 imageReaderFlags = 0  # avoid messing with already internal files
             if imageReaderFlags > 0:  # interning
                 data = self.fp.read()
                 if imageReaderFlags & 2:  # autoclose
                     try:
                         self.fp.close()
                     except:
                         pass
                 if imageReaderFlags & 4:  # cache the data
                     if not self._cache:
                         from rl_config import register_reset
                         register_reset(self._cache.clear)
                     data = self._cache.setdefault(md5(data).digest(), data)
                 self.fp = getStringIO(data)
             elif imageReaderFlags == - 1 and isinstance(fileName, (str, unicode)):
                 #try Ralf Schmitt's re-opening technique of avoiding too many open files
                 self.fp.close()
                 del self.fp  # will become a property in the next statement
                 self.__class__ = LazyImageReader
             if haveImages:
                 #detect which library we are using and open the image
                 if not self._image:
                     self._image = self._read_image(self.fp)
                 if getattr(self._image, 'format', None) == 'JPEG':
                     self.jpeg_fh = self._jpeg_fh
             else:
                 from reportlab.pdfbase.pdfutils import readJPEGInfo
                 try:
                     self._width, self._height, c = readJPEGInfo(self.fp)
                 except:
                     raise RuntimeError('Imaging Library not available, unable to import bitmaps only jpegs')
                 self.jpeg_fh = self._jpeg_fh
                 self._data = self.fp.read()
                 self._dataA = None
                 self.fp.seek(0)
         except:  # TODO: Kill the catch-all
             et, ev, tb = sys.exc_info()
             if hasattr(ev, 'args'):
                 a = str(ev.args[- 1]) + (' fileName=%r' % fileName)
                 ev.args = ev.args[: - 1] + (a,)
                 raise et, ev, tb
             else:
                 raise
示例#17
0
 def __init__(self, fileName):
     if isinstance(fileName, PmlImageReader):
         self.__dict__ = fileName.__dict__   # borgize
         return
     #start wih lots of null private fields, to be populated by
     #the relevant engine.
     self.fileName = fileName
     self._image = None
     self._width = None
     self._height = None
     self._transparent = None
     self._data = None
     imageReaderFlags = 0
     if PILImage and isinstance(fileName, PILImage.Image):
         self._image = fileName
         self.fp = getattr(fileName, 'fp', None)
         try:
             self.fileName = self._image.fileName
         except AttributeError:
             self.fileName = 'PILIMAGE_%d' % id(self)
     else:
         try:
             self.fp = open_for_read(fileName, 'b')
             if isinstance(self.fp, StringIO.StringIO().__class__):
                 imageReaderFlags = 0  # avoid messing with already internal files
             if imageReaderFlags > 0:  # interning
                 data = self.fp.read()
                 if imageReaderFlags & 2:  # autoclose
                     try:
                         self.fp.close()
                     except:
                         pass
                 if imageReaderFlags & 4:  # cache the data
                     if not self._cache:
                         from rl_config import register_reset
                         register_reset(self._cache.clear)
                     data = self._cache.setdefault(md5(data).digest(), data)
                 self.fp = getStringIO(data)
             elif imageReaderFlags == - 1 and isinstance(fileName, (str, unicode)):
                 #try Ralf Schmitt's re-opening technique of avoiding too many open files
                 self.fp.close()
                 del self.fp  # will become a property in the next statement
                 self.__class__ = LazyImageReader
             if haveImages:
                 #detect which library we are using and open the image
                 if not self._image:
                     self._image = self._read_image(self.fp)
                 if getattr(self._image, 'format', None) == 'JPEG':
                     self.jpeg_fh = self._jpeg_fh
             else:
                 from reportlab.pdfbase.pdfutils import readJPEGInfo
                 try:
                     self._width, self._height, c = readJPEGInfo(self.fp)
                 except:
                     raise RuntimeError('Imaging Library not available, unable to import bitmaps only jpegs')
                 self.jpeg_fh = self._jpeg_fh
                 self._data = self.fp.read()
                 self._dataA = None
                 self.fp.seek(0)
         except:  # TODO: Kill the catch-all
             et, ev, tb = sys.exc_info()
             if hasattr(ev, 'args'):
                 a = str(ev.args[- 1]) + (' fileName=%r' % fileName)
                 ev.args = ev.args[: - 1] + (a,)
                 raise et, ev, tb
             else:
                 raise
示例#18
0
def getExamples():
    """Returns all the example flowable objects"""
    styleSheet = getSampleStyleSheet()

    story = []

    #make a style with indents and spacing
    sty = ParagraphStyle('obvious', None)
    sty.leftIndent = 18
    sty.rightIndent = 18
    sty.firstLineIndent = 18
    sty.spaceBefore = 6
    sty.spaceAfter = 6
    story.append(
        Paragraph(
            """Now for some demo stuff - we need some on this page,
        even before we explain the concepts fully""", styleSheet['BodyText']))
    p = Paragraph(
        """
        Platypus is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        Paragraph(
            """Same but with justification 1.5 extra leading and green text.""",
            styleSheet['BodyText']))
    p = Paragraph(
        """
        <para align=justify leading="+1.5" fg=green><font color=red>Platypus</font> is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.</para>""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        platypus.XBox(4 * inch, 0.75 * inch,
                      'This is a box with a fixed size'))

    story.append(
        Paragraph(
            """
        All of this is being drawn within a text frame which was defined
        on the page.  This frame is in 'debug' mode so you can see the border,
        and also see the margins which it reserves.  A frame does not have
        to have margins, but they have been set to 6 points each to create
        a little space around the contents.
        """, styleSheet['BodyText']))

    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 2
    #######################################################################

    story.append(
        Paragraph(
            """
        Here's the base class for Flowable...
        """, styleSheet['Italic']))

    code = '''class Flowable:
        """Abstract base class for things to be drawn.  Key concepts:
    1. It knows its size
    2. It draws in its own coordinate system (this requires the
        base API to provide a translate() function.
        """
    def __init__(self):
        self.width = 0
        self.height = 0
        self.wrapped = 0

    def drawOn(self, canvas, x, y):
        "Tell it to draw itself on the canvas.  Do not override"
        self.canv = canvas
        self.canv.saveState()
        self.canv.translate(x, y)

        self.draw()   #this is the bit you overload

        self.canv.restoreState()
        del self.canv

    def wrap(self, availWidth, availHeight):
        """This will be called by the enclosing frame before objects
        are asked their size, drawn or whatever.  It returns the
        size actually used."""
        return (self.width, self.height)
    '''

    story.append(Preformatted(code, styleSheet['Code'], dedent=4))
    story.append(FrameBreak())
    #######################################################################
    #     Examples Page 3
    #######################################################################

    story.append(
        Paragraph("Here are some examples of the remaining objects above.",
                  styleSheet['Italic']))

    story.append(
        Paragraph("This is a bullet point",
                  styleSheet['Bullet'],
                  bulletText='O'))
    story.append(
        Paragraph("Another bullet point", styleSheet['Bullet'],
                  bulletText='O'))

    story.append(
        Paragraph(
            """Here is a Table, which takes all kinds of formatting options...""",
            styleSheet['Italic']))
    story.append(platypus.Spacer(0, 12))

    g = platypus.Table(
        (('', 'North', 'South', 'East', 'West'),
         ('Quarter 1', 100, 200, 300, 400), ('Quarter 2', 100, 200, 300, 400),
         ('Total', 200, 400, 600, 800)), (72, 36, 36, 36, 36),
        (24, 16, 16, 18))
    style = platypus.TableStyle([
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('ALIGN', (0, 0), (-1, 0), 'CENTRE'),
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
        ('LINEBELOW', (1, -1), (-1, -1), 2, (0.5, 0.5, 0.5)),
        ('TEXTCOLOR', (0, 1), (0, -1), colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), (0, 0.7, 0.7))
    ])
    g.setStyle(style)
    story.append(g)
    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 4 - custom fonts
    #######################################################################
    # custom font with LettError-Robot font
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    from reportlab.pdfbase import pdfmetrics
    fontDir = os.path.join(_RL_DIR, 'fonts')
    face = pdfmetrics.EmbeddedType1Face(
        os.path.join(fontDir, 'DarkGardenMK.afm'),
        os.path.join(fontDir, 'DarkGardenMK.pfb'))
    faceName = face.name  # should be 'DarkGardenMK'
    pdfmetrics.registerTypeFace(face)
    font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(font)

    # put it inside a paragraph.
    story.append(
        Paragraph(
            """This is an ordinary paragraph, which happens to contain
        text in an embedded font:
        <font name="DarkGardenMK">DarkGardenMK</font>.
        Now for the real challenge...""", styleSheet['Normal']))

    styRobot = ParagraphStyle('Robot', styleSheet['Normal'])
    styRobot.fontSize = 16
    styRobot.leading = 20
    styRobot.fontName = 'DarkGardenMK'

    story.append(
        Paragraph("This whole paragraph is 16-point DarkGardenMK.", styRobot))
    story.append(FrameBreak())

    if _GIF:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string filename.",
                styleSheet['Italic']))
        story.append(platypus.Image(_GIF))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 filename.",
                styleSheet['Italic']))
        #story.append(platypus.Image(fileName2FSEnc(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string file url.",
                styleSheet['Italic']))
        story.append(platypus.Image(getFurl(_GIF)))
        story.append(
            Paragraph("Here is an Image flowable obtained from an open file.",
                      styleSheet['Italic']))
        story.append(platypus.Image(open_for_read(_GIF, 'b')))
        story.append(FrameBreak())
        try:
            img = platypus.Image(
                'http://www.reportlab.com/rsrc/encryption.gif')
            story.append(
                Paragraph(
                    "Here is an Image flowable obtained from a string http url.",
                    styleSheet['Italic']))
            story.append(img)
        except:
            story.append(
                Paragraph(
                    "The image could not be obtained from a string http url.",
                    styleSheet['Italic']))
        story.append(FrameBreak())

    if _JPG:
        img = platypus.Image(_JPG)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from a filename.",
                styleSheet['Italic']))
        story.append(img)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from an open file.",
                styleSheet['Italic']))
        img = platypus.Image(open_for_read(_JPG, 'b'))
        story.append(img)
        story.append(FrameBreak())

    return story
def run():
    from reportlab.platypus import  BaseDocTemplate, PageTemplate, Image, Frame, PageTemplate, \
                                    ShowBoundaryValue, SimpleDocTemplate, FrameBG, Paragraph, \
                                    FrameBreak
    from reportlab.lib.colors import toColor
    from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read, fileName2FSEnc, asNative
    from reportlab.lib.styles import getSampleStyleSheet
    styleSheet = getSampleStyleSheet()
    if haveImages:
        _GIF = os.path.join(testsFolder, 'pythonpowered.gif')
        if not rl_isfile(_GIF): _GIF = None
        _GAPNG = os.path.join(testsFolder, 'gray-alpha.png')
        if not rl_isfile(_GAPNG): _GAPNG = None
    else:
        _GIF = None
    if _GIF: _GIFFSEnc = fileName2FSEnc(_GIF)
    if _GAPNG: _GAPNGFSEnc = fileName2FSEnc(_GAPNG)

    _JPG = os.path.join(testsFolder, '..', 'docs', 'images', 'lj8100.jpg')
    if not rl_isfile(_JPG): _JPG = None

    doc = SimpleDocTemplate(outputfile('test_platypus_images.pdf'))
    story = [
        FrameBG(color=toColor('lightblue'), start='frame-permanent'),
    ]
    if _GIF:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF filename.",
                styleSheet['Italic']))
        story.append(Image(_GIF))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 GIF filename.",
                styleSheet['Italic']))
        #story.append(Image(fileName2FSEnc(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF file url.",
                styleSheet['Italic']))
        story.append(Image(getFurl(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from an open GIF file.",
                styleSheet['Italic']))
        story.append(Image(open_for_read(_GIF, 'b')))
        story.append(FrameBreak())
        img = Image('http://www.reportlab.com/rsrc/encryption.gif')
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF http url.",
                styleSheet['Italic']))
        story.append(img)
        story.append(FrameBreak())

    if _GAPNG:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string PNGA filename.",
                styleSheet['Italic']))
        story.append(Image('rltw-icon-tr.png'))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string PNG filename.",
                styleSheet['Italic']))
        story.append(Image(_GAPNG))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 PNG filename.",
                styleSheet['Italic']))
        #story.append(Image(fileName2FSEnc(_GAPNG)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string file PNG url.",
                styleSheet['Italic']))
        story.append(Image(getFurl(_GAPNG)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from an open PNG file.",
                styleSheet['Italic']))
        story.append(Image(open_for_read(_GAPNG, 'b')))
        story.append(FrameBreak())

    if _JPG:
        img = Image(_JPG)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from a JPEG filename.",
                styleSheet['Italic']))
        story.append(img)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from an open JPEG file.",
                styleSheet['Italic']))
        img = Image(open_for_read(_JPG, 'b'))
        story.append(img)
        story.append(FrameBreak())
    doc.build(story)
def getExamples():
    """Returns all the example flowable objects"""
    styleSheet = getSampleStyleSheet()

    story = []

    #make a style with indents and spacing
    sty = ParagraphStyle('obvious', None)
    sty.leftIndent = 18
    sty.rightIndent = 18
    sty.firstLineIndent = 18
    sty.spaceBefore = 6
    sty.spaceAfter = 6
    story.append(Paragraph("""Now for some demo stuff - we need some on this page,
        even before we explain the concepts fully""", styleSheet['BodyText']))
    p = Paragraph("""
        Platypus is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.""", sty)

    p.debug = 1   #show me the borders
    story.append(p)

    story.append(Paragraph("""Same but with justification 1.5 extra leading and green text.""", styleSheet['BodyText']))
    p = Paragraph("""
        <para align=justify leading=+1.5 fg=green><font color=red>Platypus</font> is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.</para>""", sty)

    p.debug = 1   #show me the borders
    story.append(p)

    story.append(platypus.XBox(4*inch, 0.75*inch,
            'This is a box with a fixed size'))

    story.append(Paragraph("""
        All of this is being drawn within a text frame which was defined
        on the page.  This frame is in 'debug' mode so you can see the border,
        and also see the margins which it reserves.  A frame does not have
        to have margins, but they have been set to 6 points each to create
        a little space around the contents.
        """, styleSheet['BodyText']))

    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 2
    #######################################################################

    story.append(Paragraph("""
        Here's the base class for Flowable...
        """, styleSheet['Italic']))

    code = '''class Flowable:
        """Abstract base class for things to be drawn.  Key concepts:
    1. It knows its size
    2. It draws in its own coordinate system (this requires the
        base API to provide a translate() function.
        """
    def __init__(self):
        self.width = 0
        self.height = 0
        self.wrapped = 0

    def drawOn(self, canvas, x, y):
        "Tell it to draw itself on the canvas.  Do not override"
        self.canv = canvas
        self.canv.saveState()
        self.canv.translate(x, y)

        self.draw()   #this is the bit you overload

        self.canv.restoreState()
        del self.canv

    def wrap(self, availWidth, availHeight):
        """This will be called by the enclosing frame before objects
        are asked their size, drawn or whatever.  It returns the
        size actually used."""
        return (self.width, self.height)
    '''

    story.append(Preformatted(code, styleSheet['Code'], dedent=4))
    story.append(FrameBreak())
    #######################################################################
    #     Examples Page 3
    #######################################################################

    story.append(Paragraph(
                "Here are some examples of the remaining objects above.",
                styleSheet['Italic']))

    story.append(Paragraph("This is a bullet point", styleSheet['Bullet'], bulletText='O'))
    story.append(Paragraph("Another bullet point", styleSheet['Bullet'], bulletText='O'))


    story.append(Paragraph("""Here is a Table, which takes all kinds of formatting options...""",
                styleSheet['Italic']))
    story.append(platypus.Spacer(0, 12))

    g = platypus.Table(
            (('','North','South','East','West'),
             ('Quarter 1',100,200,300,400),
             ('Quarter 2',100,200,300,400),
             ('Total',200,400,600,800)),
            (72,36,36,36,36),
            (24, 16,16,18)
            )
    style = platypus.TableStyle([('ALIGN', (1,1), (-1,-1), 'RIGHT'),
                               ('ALIGN', (0,0), (-1,0), 'CENTRE'),
                               ('GRID', (0,0), (-1,-1), 0.25, colors.black),
                               ('LINEBELOW', (0,0), (-1,0), 2, colors.black),
                               ('LINEBELOW',(1,-1), (-1, -1), 2, (0.5, 0.5, 0.5)),
                               ('TEXTCOLOR', (0,1), (0,-1), colors.black),
                               ('BACKGROUND', (0,0), (-1,0), (0,0.7,0.7))
                               ])
    g.setStyle(style)
    story.append(g)
    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 4 - custom fonts
    #######################################################################
    # custom font with LettError-Robot font
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    from reportlab.pdfbase import pdfmetrics
    fontDir = os.path.join(os.path.dirname(reportlab.__file__),'fonts')
    face = pdfmetrics.EmbeddedType1Face(os.path.join(fontDir,'LeERC___.AFM'),os.path.join(fontDir,'LeERC___.PFB'))
    faceName = face.name  # should be 'LettErrorRobot-Chrome'
    pdfmetrics.registerTypeFace(face)
    font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(font)


    # put it inside a paragraph.
    story.append(Paragraph(
        """This is an ordinary paragraph, which happens to contain
        text in an embedded font:
        <font name="LettErrorRobot-Chrome">LettErrorRobot-Chrome</font>.
        Now for the real challenge...""", styleSheet['Normal']))


    styRobot = ParagraphStyle('Robot', styleSheet['Normal'])
    styRobot.fontSize = 16
    styRobot.leading = 20
    styRobot.fontName = 'LettErrorRobot-Chrome'

    story.append(Paragraph(
                "This whole paragraph is 16-point Letterror-Robot-Chrome.",
                styRobot))
    story.append(FrameBreak())

    if _GIF:
        story.append(Paragraph("Here is an Image flowable obtained from a string filename.",styleSheet['Italic']))
        story.append(platypus.Image(_GIF))
        story.append(Paragraph( "Here is an Image flowable obtained from a utf8 filename.", styleSheet['Italic']))
        story.append(platypus.Image(_GIF.encode('utf8')))
        story.append(Paragraph("Here is an Image flowable obtained from a string file url.",styleSheet['Italic']))
        story.append(platypus.Image(getFurl(_GIF)))
        story.append(Paragraph("Here is an Image flowable obtained from an open file.",styleSheet['Italic']))
        story.append(platypus.Image(open_for_read(_GIF,'b')))
        story.append(FrameBreak())
        try:
            img = platypus.Image('http://www.reportlab.com/rsrc/encryption.gif')
            story.append(Paragraph("Here is an Image flowable obtained from a string http url.",styleSheet['Italic']))
            story.append(img)
        except:
            story.append(Paragraph("The image could not be obtained from a string http url.",styleSheet['Italic']))
        story.append(FrameBreak())

    if _JPG:
        img = platypus.Image(_JPG)
        story.append(Paragraph("Here is an JPEG Image flowable obtained from a filename.",styleSheet['Italic']))
        story.append(img)
        story.append(Paragraph("Here is an JPEG Image flowable obtained from an open file.",styleSheet['Italic']))
        img = platypus.Image(open_for_read(_JPG,'b'))
        story.append(img)
        story.append(FrameBreak())


    return story