当前位置: 首页>>代码示例>>Python>>正文


Python utils.getStringIO函数代码示例

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


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

示例1: get_templated_HTML

def get_templated_HTML( src_template=DUMB_FMT_HTML, title=None, heading=None, body=None):
	from reportlab.lib.utils import getStringIO
	p = DocStyle0HTML()
	D = p.processfile( getStringIO(body), None )
	if title is not None: D['title'] = title
	if heading is not None: D['heading'] = '<center><h1>%s</h1></center>' % heading
	return get_templated_pagedata( find_template(TEMPLATE_FN), src_template % D)
开发者ID:AndyKovv,项目名称:hostel,代码行数:7,代码来源:simple_doc.py

示例2: PIL_imagedata

    def PIL_imagedata(self):
        self.source = 'PIL'
        zlib = import_zlib()
        if not zlib: return
        image = self.image
        myimage = image.convert('RGB')
        imgwidth, imgheight = myimage.size

        # this describes what is in the image itself
        # *NB* according to the spec you can only use the short form in inline images
        #imagedata=['BI /Width %d /Height /BitsPerComponent 8 /ColorSpace /%s /Filter [/Filter [ /ASCII85Decode /FlateDecode] ID]' % (imgwidth, imgheight,'RGB')]
        imagedata=['BI /W %d /H %d /BPC 8 /CS /RGB /F [/A85 /Fl] ID' % (imgwidth, imgheight)]

        #use a flate filter and Ascii Base 85 to compress
        raw = myimage.tostring()
        assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image")
        compressed = zlib.compress(raw)   #this bit is very fast...
        encoded = pdfutils._AsciiBase85Encode(compressed) #...sadly this isn't
        #write in blocks of (??) 60 characters per line to a list
        outstream = getStringIO(encoded)
        dataline = outstream.read(60)
        while dataline <> "":
            imagedata.append(dataline)
            self.binaryData.append(dataline)
            dataline = outstream.read(60)
        imagedata.append('EI')
        return (imagedata, imgwidth, imgheight)
开发者ID:broodjeaap,项目名称:project-78-hr-2011-groep1,代码行数:27,代码来源:pdfimages.py

示例3: saveAsHandout

    def saveAsHandout(self):
        """Write the PDF document, multiple slides per page."""

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet["Heading1"]
        bt = styleSheet["BodyText"]

        if self.sourceFilename:
            filename = os.path.splitext(self.sourceFilename)[0] + ".pdf"

        outfile = getStringIO()
        doc = SimpleDocTemplate(outfile, pagesize=rl_config.defaultPageSize, showBoundary=0)
        doc.leftMargin = 1 * cm
        doc.rightMargin = 1 * cm
        doc.topMargin = 2 * cm
        doc.bottomMargin = 2 * cm
        multiPageWidth = rl_config.defaultPageSize[0] - doc.leftMargin - doc.rightMargin - 50

        story = []
        orgFullPageSize = (self.pageWidth, self.pageHeight)
        t = makeSlideTable(self.slides, orgFullPageSize, multiPageWidth, self.cols)
        story.append(t)

        ##        #ensure outline visible by default
        ##        if self.showOutline:
        ##            doc.canv.showOutline()

        doc.build(story)
        return self.savetofile(outfile, filename)
开发者ID:radical-software,项目名称:radicalspam,代码行数:29,代码来源:pythonpoint.py

示例4: jpg_imagedata

 def jpg_imagedata(self):
     #directly process JPEG files
     #open file, needs some error handling!!
     self.source = 'JPEG'
     imageFile = open(self.image, 'rb')
     info = pdfutils.readJPEGInfo(imageFile)
     imgwidth, imgheight = info[0], info[1]
     if info[2] == 1:
         colorSpace = 'DeviceGray'
     elif info[2] == 3:
         colorSpace = 'DeviceRGB'
     else: #maybe should generate an error, is this right for CMYK?
         colorSpace = 'DeviceCMYK'
     imageFile.seek(0) #reset file pointer
     imagedata = []
     #imagedata.append('BI /Width %d /Height /BitsPerComponent 8 /ColorSpace /%s /Filter [/Filter [ /ASCII85Decode /DCTDecode] ID' % (info[0], info[1], colorSpace))
     imagedata.append('BI /W %d /H %d /BPC 8 /CS /%s /F [/A85 /DCT] ID' % (imgwidth, imgheight, colorSpace))
     #write in blocks of (??) 60 characters per line to a list
     compressed = imageFile.read()
     encoded = pdfutils._AsciiBase85Encode(compressed)
     outstream = getStringIO(encoded)
     dataline = outstream.read(60)
     while dataline <> "":
         imagedata.append(dataline)
         self.binaryData.append(dataline)
         dataline = outstream.read(60)
     imagedata.append('EI')
     return (imagedata, imgwidth, imgheight)
开发者ID:broodjeaap,项目名称:project-78-hr-2011-groep1,代码行数:28,代码来源:pdfimages.py

示例5: handleError

 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()))
开发者ID:luannguyen49,项目名称:OdooPortable,代码行数:7,代码来源:renderPM.py

示例6: _AsciiHexEncode

def _AsciiHexEncode(input):
    """Encodes input using ASCII-Hex coding.

    This is a verbose encoding used for binary data within
    a PDF file.  One byte binary becomes two bytes of ASCII.
    Helper function used by images."""
    output = getStringIO()
    for char in input:
        output.write('%02x' % ord(char))
    output.write('>')
    return output.getvalue()
开发者ID:7o9,项目名称:stdm-plugin,代码行数:11,代码来源:pdfutils.py

示例7: _svn

	def _svn(self,args,fail=1):
		''' do a svn command and return the results '''
		svn = find_exe('svn')
		if type(args) is type([]): args = ' '.join(args)
		self.goWorkingDir()
		fout=getStringIO()
		do_exec(svn + ' ' + args,fout=fout,sys_exit=0,verbose=self.verbose>1,fail=fail)
		self.resetDir()
		T = fout.getvalue()
		T.replace('\r\n','\n')
		T.replace('\r','\n')
		return '\n'.join([x for x in T.split('\n') if not x or x[0]!='?'])
开发者ID:AndyKovv,项目名称:hostel,代码行数:12,代码来源:releaser.py

示例8: saveAsPresentation

    def saveAsPresentation(self):
        """Write the PDF document, one slide per page."""
        if self.verbose:
            print "saving presentation..."
        pageSize = (self.pageWidth, self.pageHeight)
        if self.sourceFilename:
            filename = os.path.splitext(self.sourceFilename)[0] + ".pdf"
        if self.outDir:
            filename = os.path.join(self.outDir, os.path.basename(filename))
        if self.verbose:
            print filename
        # canv = canvas.Canvas(filename, pagesize = pageSize)
        outfile = getStringIO()
        if self.notes:
            # translate the page from landscape to portrait
            pageSize = pageSize[1], pageSize[0]
        canv = canvas.Canvas(outfile, pagesize=pageSize)
        canv.setPageCompression(self.compression)
        canv.setPageDuration(self.pageDuration)
        if self.title:
            canv.setTitle(self.title)
        if self.author:
            canv.setAuthor(self.author)
        if self.subject:
            canv.setSubject(self.subject)

        slideNo = 0
        for slide in self.slides:
            # need diagnostic output if something wrong with XML
            slideNo = slideNo + 1
            if self.verbose:
                print "doing slide %d, id = %s" % (slideNo, slide.id)
            if self.notes:
                # frame and shift the slide
                # canv.scale(0.67, 0.67)
                scale_amt = (min(pageSize) / float(max(pageSize))) * 0.95
                # canv.translate(self.pageWidth / 6.0, self.pageHeight / 3.0)
                # canv.translate(self.pageWidth / 2.0, .025*self.pageHeight)
                canv.translate(0.025 * self.pageHeight, (self.pageWidth / 2.0) + 5)
                # canv.rotate(90)
                canv.scale(scale_amt, scale_amt)
                canv.rect(0, 0, self.pageWidth, self.pageHeight)
            slide.drawOn(canv)
            canv.showPage()

        # ensure outline visible by default
        if self.showOutline:
            canv.showOutline()

        canv.save()
        return self.savetofile(outfile, filename)
开发者ID:radical-software,项目名称:radicalspam,代码行数:51,代码来源:pythonpoint.py

示例9: _AsciiHexDecode

def _AsciiHexDecode(input):
    """Decodes input using ASCII-Hex coding.

    Not used except to provide a test of the inverse function."""

    #strip out all whitespace
    stripped = join(split(input),'')
    assert stripped[-1] == '>', 'Invalid terminator for Ascii Hex Stream'
    stripped = stripped[:-1]  #chop off terminator
    assert len(stripped) % 2 == 0, 'Ascii Hex stream has odd number of bytes'

    i = 0
    output = getStringIO()
    while i < len(stripped):
        twobytes = stripped[i:i+2]
        output.write(chr(eval('0x'+twobytes)))
        i = i + 2
    return output.getvalue()
开发者ID:tschalch,项目名称:pyTray,代码行数:18,代码来源:pdfutils.py

示例10: 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

示例11: makeStream

    def makeStream(self):
        "Finishes the generation and returns the TTF file as a string"
        stm = getStringIO()
        write = stm.write

        numTables = len(self.tables)
        searchRange = 1
        entrySelector = 0
        while searchRange * 2 <= numTables:
            searchRange = searchRange * 2
            entrySelector = entrySelector + 1
        searchRange = searchRange * 16
        rangeShift = numTables * 16 - searchRange

        # Header
        write(pack(">lHHHH", 0x00010000, numTables, searchRange,
                                 entrySelector, rangeShift))

        # Table directory
        tables = self.tables.items()
        tables.sort()     # XXX is this the correct order?
        offset = 12 + numTables * 16
        for tag, data in tables:
            if tag == 'head':
                head_start = offset
            checksum = calcChecksum(data)
            write(tag)
            write(pack(">LLL", checksum, offset, len(data)))
            paddedLength = (len(data)+3)&~3
            offset = offset + paddedLength

        # Table data
        for tag, data in tables:
            data += "\0\0\0"
            write(data[:len(data)&~3])

        checksum = calcChecksum(stm.getvalue())
        checksum = add32(0xB1B0AFBAL, -checksum)
        stm.seek(head_start + 8)
        write(pack('>L', checksum))

        return stm.getvalue()
开发者ID:Dongminator,项目名称:CV-Management-tool,代码行数:42,代码来源:ttfonts.py

示例12: encryptPdfInMemory

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 http://developer.reportlab.com''')

    (bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1)
    names = bboxInfo.keys()

    firstPageSize = bboxInfo['PageForms0'][2:]

    #now make a new PDF document
    buf = getStringIO()
    canv = Canvas(buf, pagesize=firstPageSize)

    # set a standard ID while debugging
    if CLOBBERID:
        canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]"
    encryptCanvas(canv,
                  userPassword, ownerPassword,
                  canPrint, canModify, canCopy, canAnnotate,
                  strength=strength)

    formNames = restoreFormsInMemory(pickledForms, canv)
    for formName in formNames:
        #need to extract page size in future
        canv.doForm(formName)
        canv.showPage()
    canv.save()
    return buf.getvalue()
开发者ID:7o9,项目名称:stdm-plugin,代码行数:40,代码来源:pdfencrypt.py

示例13: _showWidgetProperties

    def _showWidgetProperties(self, widget):
        """Dump all properties of a widget."""

        props = widget.getProperties()
        keys = list(props.keys())
        keys.sort()
        lines = []
        for key in keys:
            value = props[key]

            # Method 3
            f = getStringIO()
            pprint.pprint(value, f)
            value = f.getvalue()[:-1]
            valueLines = value.split('\n')
            for i in range(1, len(valueLines)):
                valueLines[i] = ' '*(len(key)+3) + valueLines[i]
            value = '\n'.join(valueLines)

            lines.append('%s = %s' % (key, value))
        text = '\n'.join(lines)
        self.outLines.append('<H3>Properties of Example Widget</H3>')
        self.outLines.append('<PRE>%s</PRE>' % text)
        self.outLines.append('')
开发者ID:Distrotech,项目名称:reportlab,代码行数:24,代码来源:graphdocpy.py

示例14: _showWidgetProperties

    def _showWidgetProperties(self, widget):
        """Dump all properties of a widget."""

        props = widget.getProperties()
        keys = props.keys()
        keys.sort()
        lines = []
        for key in keys:
            value = props[key]

            # Method 3
            f = getStringIO()
            pprint.pprint(value, f)
            value = f.getvalue()[:-1]
            valueLines = string.split(value, "\n")
            for i in range(1, len(valueLines)):
                valueLines[i] = " " * (len(key) + 3) + valueLines[i]
            value = string.join(valueLines, "\n")

            lines.append("%s = %s" % (key, value))
        text = join(lines, "\n")
        self.outLines.append("<H3>Properties of Example Widget</H3>")
        self.outLines.append("<PRE>%s</PRE>" % text)
        self.outLines.append("")
开发者ID:sengupta,项目名称:scilab_cloud,代码行数:24,代码来源:graphdocpy.py

示例15: _AsciiHexEncode

 def _AsciiHexEncode(self, input):  # also based on piddlePDF
     "Helper function used by images"
     output = getStringIO()
     for char in input:
         output.write('%02x' % ord(char))
     return output.getvalue()
开发者ID:ingob,项目名称:mwlib.ext,代码行数:6,代码来源:renderPS.py


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