• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.open_for_read函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中reportlab.lib.utils.open_for_read函数的典型用法代码示例。如果您正苦于以下问题:Python open_for_read函数的具体用法?Python open_for_read怎么用?Python open_for_read使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了open_for_read函数的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

 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)
开发者ID:ShaulBarkan,项目名称:PRION,代码行数:29,代码来源:flowables.py


示例2: __init__

 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)
开发者ID:halimath,项目名称:taskcardmaker,代码行数:32,代码来源:flowables.py


示例3: TTFOpenFile

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)
开发者ID:Dongminator,项目名称:CV-Management-tool,代码行数:17,代码来源:ttfonts.py


示例4: cacheImageFile

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
开发者ID:broodjeaap,项目名称:project-78-hr-2011-groep1,代码行数:44,代码来源:pdfutils.py


示例5: readFields

 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
开发者ID:AndyKovv,项目名称:hostel,代码行数:10,代码来源:fieldreader.py


示例6: read

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
开发者ID:AndyKovv,项目名称:hostel,代码行数:15,代码来源:csv.py


示例7: test0

    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)
开发者ID:Jbaumotte,项目名称:web2py,代码行数:16,代码来源:test_tools_pythonpoint.py


示例8: cacheImageFile

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
开发者ID:DDRBoxman,项目名称:Spherebot-Host-GUI,代码行数:20,代码来源:pdfutils.py


示例9: cacheImageFile

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
开发者ID:tschalch,项目名称:pyTray,代码行数:41,代码来源:pdfutils.py


示例10: __init__

 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
开发者ID:deepcell,项目名称:xhtml2pdf,代码行数:67,代码来源:xhtml2pdf_reportlab.py


示例11: getExamples


#.........这里部分代码省略.........
    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
开发者ID:roytest001,项目名称:PythonCode,代码行数:101,代码来源:test_platypus_general.py



注:本文中的reportlab.lib.utils.open_for_read函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.recursiveImport函数代码示例发布时间:2022-05-26
下一篇:
Python utils.open_and_read函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap