Exemplo n.º 1
0
    def addObjects(self, doc):
        """Makes and returns one or more PDF objects to be added
        to the document.  The caller supplies the internal name
        to be used (typically F1, F2... in sequence) """
        # avoid circular imports - this cannot go at module level
        from reportlab.pdfbase import pdfdoc

        # construct a Type 1 Font internal object
        internalName = 'F' + repr(len(doc.fontMapping)+1)
        pdfFont = pdfdoc.PDFType1Font()
        pdfFont.Name = internalName
        pdfFont.BaseFont = self.face.name
        pdfFont.__Comment__ = 'Font %s' % self.fontName
        e = self.encoding.makePDFObject()
        if not isStr(e) or e in ('/MacRomanEncoding','/MacExpertEncoding','/WinAnsiEncoding'):
            #https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf page 255
            pdfFont.Encoding = e

        # is it a built-in one?  if not, need more stuff.
        if not self.face.name in standardFonts:
            pdfFont.FirstChar = 0
            pdfFont.LastChar = 255
            pdfFont.Widths = pdfdoc.PDFArray(self.widths)
            pdfFont.FontDescriptor = self.face.addObjects(doc)
        # now link it in
        ref = doc.Reference(pdfFont, internalName)

        # also refer to it in the BasicFonts dictionary
        fontDict = doc.idToObject['BasicFonts'].dict
        fontDict[internalName] = pdfFont

        # and in the font mappings
        doc.fontMapping[self.fontName] = '/' + internalName
Exemplo n.º 2
0
    def __call__(self,arg,default=None):
        '''try to map an arbitrary arg to a color instance
        '''
        if isinstance(arg,Color): return arg
        if isinstance(arg,(tuple,list)):
            assert 3<=len(arg)<=4, 'Can only convert 3 and 4 sequences to color'
            assert 0<=min(arg) and max(arg)<=1
            return len(arg)==3 and Color(arg[0],arg[1],arg[2]) or CMYKColor(arg[0],arg[1],arg[2],arg[3])
        elif isStr(arg):
            arg = asNative(arg)
            C = cssParse(arg)
            if C: return C
            if arg in self.extraColorsNS: return self.extraColorsNS[arg]
            C = getAllNamedColors()
            s = arg.lower()
            if s in C: return C[s]
            try:
                return toColor(eval(arg))
            except:
                pass

        try:
            return HexColor(arg)
        except:
            default = '#FFFFFF'
            # default = '#000000'
            logging.warning("(colors.py) defaulting color to #000000...")
            if default is None:
                raise ValueError('Invalid color value %r' % arg)
            return HexColor(default)
Exemplo n.º 3
0
def findTags(tt, tname, tags=None):
    '''looks for a named tag in a pyRXP tuple tree (t)
    returns R where R is  a list of items (X) where items are either tuple 
    trees (t) where the tag is found or the items can be a list of t[X]
    R = [X*]
    X = t | [t[X]]
    '''
    if tags is None: tags=[]
    if isStr(tt) or tt is None:
        return tags
    if isinstance(tt, tuple):
        if tt[0]==tname:
            T1 = findTags(tt[2],tname,[])
            if T1:
                tags.append([tt,T1])
            else:
                tags.append(tt)
            return tags
        else:
            return findTags(tt[2],tname,tags)
    if isinstance(tt, list):
        for x in tt:
            findTags(x, tname, tags)
        return tags
    raise ValueError('invalid argument for tt=%r' % tt)
Exemplo n.º 4
0
    def __call__(self, arg, default=None):
        '''try to map an arbitrary arg to a color instance
        '''
        if isinstance(arg, Color): return arg
        if isinstance(arg, (tuple, list)):
            assert 3 <= len(
                arg) <= 4, 'Can only convert 3 and 4 sequences to color'
            assert 0 <= min(arg) and max(arg) <= 1
            return len(arg) == 3 and Color(arg[0], arg[1],
                                           arg[2]) or CMYKColor(
                                               arg[0], arg[1], arg[2], arg[3])
        elif isStr(arg):
            arg = asNative(arg)
            C = cssParse(arg)
            if C: return C
            if arg in self.extraColorsNS: return self.extraColorsNS[arg]
            C = getAllNamedColors()
            s = arg.lower()
            if s in C: return C[s]
            parsedColor = parseColorClassFromString(arg)
            if (parsedColor): return parsedColor

        try:
            return HexColor(arg)
        except:
            if default is None:
                raise ValueError('Invalid color value %r' % arg)
            return default
    def draw(self):
        # general widget bits
        s = float(self.size)  # abbreviate as we will use this a lot
        g = shapes.Group()
        ig = self.innerGap

        x = self.x + self.dx
        y = self.y + self.dy
        hsize = 0.5 * self.size
        if not ig:
            L = [(x - hsize, y, x + hsize, y), (x, y - hsize, x, y + hsize)]
        else:
            if isStr(ig):
                ig = asUnicode(ig)
                if ig.endswith(u'%'):
                    gs = hsize * float(ig[:-1]) / 100.0
                else:
                    gs = float(ig) * 0.5
            else:
                gs = ig * 0.5
            L = [(x - hsize, y, x - gs, y), (x + gs, y, x + hsize, y),
                 (x, y - hsize, x, y - gs), (x, y + gs, x, y + hsize)]
        P = shapes.Path(strokeWidth=self.strokeWidth,
                        strokeColor=self.strokeColor)
        for x0, y0, x1, y1 in L:
            P.moveTo(x0, y0)
            P.lineTo(x1, y1)
        g.add(P)
        return g
    def getImageData(self,preserveAspectRatio=False):
        "Gets data, height, width - whatever type of image"
        image = self.image

        if isStr(image):
            self.filename = image
            if os.path.splitext(image)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
                try:
                    imagedata, imgwidth, imgheight = self.jpg_imagedata()
                except:
                    imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image)  #try for normal kind of image
            else:
                imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image)
        else:
            import sys
            if sys.platform[0:4] == 'java':
                #jython, PIL not available
                imagedata, imgwidth, imgheight = self.JAVA_imagedata()
            else:
                imagedata, imgwidth, imgheight = self.PIL_imagedata()
        self.imageData = imagedata
        self.imgwidth = imgwidth
        self.imgheight = imgheight
        self.width = self.width or imgwidth
        self.height = self.height or imgheight
Exemplo n.º 7
0
    def addObjects(self, doc):
        """Makes and returns one or more PDF objects to be added
        to the document.  The caller supplies the internal name
        to be used (typically F1, F2... in sequence) """
        # avoid circular imports - this cannot go at module level
        from reportlab.pdfbase import pdfdoc

        # construct a Type 1 Font internal object
        internalName = 'F' + repr(len(doc.fontMapping)+1)
        pdfFont = pdfdoc.PDFType1Font()
        pdfFont.Name = internalName
        pdfFont.BaseFont = self.face.name
        pdfFont.__Comment__ = 'Font %s' % self.fontName
        e = self.encoding.makePDFObject()
        if not isStr(e) or e in ('/MacRomanEncoding','/MacExpertEncoding','/WinAnsiEncoding'):
            #https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf page 255
            pdfFont.Encoding = e

        # is it a built-in one?  if not, need more stuff.
        if not self.face.name in standardFonts:
            pdfFont.FirstChar = 0
            pdfFont.LastChar = 255
            pdfFont.Widths = pdfdoc.PDFArray(self.widths)
            pdfFont.FontDescriptor = self.face.addObjects(doc)
        # now link it in
        ref = doc.Reference(pdfFont, internalName)

        # also refer to it in the BasicFonts dictionary
        fontDict = doc.idToObject['BasicFonts'].dict
        fontDict[internalName] = pdfFont

        # and in the font mappings
        doc.fontMapping[self.fontName] = '/' + internalName
Exemplo n.º 8
0
 def setFillColor(self, aColor, alpha=None):
     """Takes a color object, allowing colors to be referred to by name"""
     if self._enforceColorSpace:
         aColor = self._enforceColorSpace(aColor)
     if isinstance(aColor, CMYKColor):
         d = aColor.density
         c,m,y,k = (d*aColor.cyan, d*aColor.magenta, d*aColor.yellow, d*aColor.black)
         self._fillColorObj = aColor
         name = self._checkSeparation(aColor)
         if name:
             self._code.append('/%s cs %s scn' % (name,fp_str(d)))
         else:
             self._code.append('%s k' % fp_str(c, m, y, k))
     elif isinstance(aColor, Color):
         rgb = (aColor.red, aColor.green, aColor.blue)
         self._fillColorObj = aColor
         self._code.append('%s rg' % fp_str(rgb) )
     elif isinstance(aColor,(tuple,list)):
         l = len(aColor)
         if l==3:
             self._fillColorObj = aColor
             self._code.append('%s rg' % fp_str(aColor) )
         elif l==4:
             self._fillColorObj = aColor
             self._code.append('%s k' % fp_str(aColor))
         else:
             raise ValueError('Unknown color %r' % aColor)
     elif isStr(aColor):
         self.setFillColor(toColor(aColor))
     else:
         raise ValueError('Unknown color %r' % aColor)
     if alpha is not None:
         self.setFillAlpha(alpha)
     elif getattr(aColor, 'alpha', None) is not None:
         self.setFillAlpha(aColor.alpha)
Exemplo n.º 9
0
    def getImageData(self, preserveAspectRatio=False):
        "Gets data, height, width - whatever type of image"
        image = self.image

        if isStr(image):
            self.filename = image
            if os.path.splitext(image)[1] in [
                    '.jpg', '.JPG', '.jpeg', '.JPEG'
            ]:
                try:
                    imagedata, imgwidth, imgheight = self.jpg_imagedata()
                except:
                    imagedata, imgwidth, imgheight = self.non_jpg_imagedata(
                        image)  #try for normal kind of image
            else:
                imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image)
        else:
            import sys
            if sys.platform[0:4] == 'java':
                #jython, PIL not available
                imagedata, imgwidth, imgheight = self.JAVA_imagedata()
            else:
                imagedata, imgwidth, imgheight = self.PIL_imagedata()
        self.imageData = imagedata
        self.imgwidth = imgwidth
        self.imgheight = imgheight
        self.width = self.width or imgwidth
        self.height = self.height or imgheight
Exemplo n.º 10
0
    def _get_label_sum_text(self, row_no, col_no):
        """
        return formatted label text
        :param row_no:
        :param col_no:
        :return:
        """
        len_row = len(self.data)
        if row_no != len_row - 1:
            return None

        text = self._lable_sum[col_no]

        label_fmt = self.barLabelFormat
        if isinstance(label_fmt, (list, tuple)):
            label_fmt = label_fmt[row_no]
            if isinstance(label_fmt, (list, tuple)):
                label_fmt = label_fmt[col_no]

        if label_fmt is None:
            label_text = None
        elif label_fmt == 'values':
            label_text = text
        elif isStr(label_fmt):
            label_text = label_fmt % text
        elif hasattr(label_fmt, '__call__'):
            label_text = label_fmt(text)
        else:
            msg = "Unknown formatter type %s, expected string or function" % label_fmt
            raise Exception(msg)
        return label_text
Exemplo n.º 11
0
 def setFillColor(self, aColor, alpha=None):
     """Takes a color object, allowing colors to be referred to by name"""
     if self._enforceColorSpace:
         aColor = self._enforceColorSpace(aColor)
     if isinstance(aColor, CMYKColor):
         d = aColor.density
         c,m,y,k = (d*aColor.cyan, d*aColor.magenta, d*aColor.yellow, d*aColor.black)
         self._fillColorObj = aColor
         name = self._checkSeparation(aColor)
         if name:
             self._code.append('/%s cs %s scn' % (name,fp_str(d)))
         else:
             self._code.append('%s k' % fp_str(c, m, y, k))
     elif isinstance(aColor, Color):
         rgb = (aColor.red, aColor.green, aColor.blue)
         self._fillColorObj = aColor
         self._code.append('%s rg' % fp_str(rgb) )
     elif isinstance(aColor,(tuple,list)):
         l = len(aColor)
         if l==3:
             self._fillColorObj = aColor
             self._code.append('%s rg' % fp_str(aColor) )
         elif l==4:
             self._fillColorObj = aColor
             self._code.append('%s k' % fp_str(aColor))
         else:
             raise ValueError('Unknown color %r' % aColor)
     elif isStr(aColor):
         self.setFillColor(toColor(aColor))
     else:
         raise ValueError('Unknown color %r' % aColor)
     if alpha is not None:
         self.setFillAlpha(alpha)
     elif getattr(aColor, 'alpha', None) is not None:
         self.setFillAlpha(aColor.alpha)
Exemplo n.º 12
0
 def test(self, x):
     if not isStr(x):
         return False
     try:
         a, b, c, d = codecs.lookup(x)
         return True
     except LookupError:
         return False
Exemplo n.º 13
0
 def test(self,x):
     if not isStr(x):
         return False
     try:
         a,b,c,d = codecs.lookup(x)
         return True
     except LookupError:
         return False
Exemplo n.º 14
0
def HexColor(val, htmlOnly=False, hasAlpha=False):
    """This function converts a hex string, or an actual integer number,
    into the corresponding color.  E.g., in "#AABBCC" or 0xAABBCC,
    AA is the red, BB is the green, and CC is the blue (00-FF).

    An alpha value can also be given in the form #AABBCCDD or 0xAABBCCDD where
    DD is the alpha value if hasAlpha is True.

    For completeness I assume that #aabbcc or 0xaabbcc are hex numbers
    otherwise a pure integer is converted as decimal rgb.  If htmlOnly is true,
    only the #aabbcc form is allowed.

    >>> HexColor('#ffffff')
    Color(1,1,1,1)
    >>> HexColor('#FFFFFF')
    Color(1,1,1,1)
    >>> HexColor('0xffffff')
    Color(1,1,1,1)
    >>> HexColor('16777215')
    Color(1,1,1,1)

    An '0x' or '#' prefix is required for hex (as opposed to decimal):

    >>> HexColor('ffffff')
    Traceback (most recent call last):
    ValueError: invalid literal for int() with base 10: 'ffffff'

    >>> HexColor('#FFFFFF', htmlOnly=True)
    Color(1,1,1,1)
    >>> HexColor('0xffffff', htmlOnly=True)
    Traceback (most recent call last):
    ValueError: not a hex string
    >>> HexColor('16777215', htmlOnly=True)
    Traceback (most recent call last):
    ValueError: not a hex string

    """ #" for emacs

    if isStr(val):
        val = asNative(val)
        b = 10
        if val[:1] == '#':
            val = val[1:]
            b = 16
            if len(val) == 8:
                alpha = True
        else:
            if htmlOnly:
                raise ValueError('not a hex string')
            if val[:2].lower() == '0x':
                b = 16
                val = val[2:]
                if len(val) == 8:
                    alpha = True
        val = int(val,b)
    if hasAlpha:
        return Color(((val>>24)&0xFF)/255.0,((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0)
    return Color(((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0)
Exemplo n.º 15
0
def HexColor(val, htmlOnly=False, hasAlpha=False):
    """This function converts a hex string, or an actual integer number,
    into the corresponding color.  E.g., in "#AABBCC" or 0xAABBCC,
    AA is the red, BB is the green, and CC is the blue (00-FF).

    An alpha value can also be given in the form #AABBCCDD or 0xAABBCCDD where
    DD is the alpha value if hasAlpha is True.

    For completeness I assume that #aabbcc or 0xaabbcc are hex numbers
    otherwise a pure integer is converted as decimal rgb.  If htmlOnly is true,
    only the #aabbcc form is allowed.

    >>> HexColor('#ffffff')
    Color(1,1,1,1)
    >>> HexColor('#FFFFFF')
    Color(1,1,1,1)
    >>> HexColor('0xffffff')
    Color(1,1,1,1)
    >>> HexColor('16777215')
    Color(1,1,1,1)

    An '0x' or '#' prefix is required for hex (as opposed to decimal):

    >>> HexColor('ffffff')
    Traceback (most recent call last):
    ValueError: invalid literal for int() with base 10: 'ffffff'

    >>> HexColor('#FFFFFF', htmlOnly=True)
    Color(1,1,1,1)
    >>> HexColor('0xffffff', htmlOnly=True)
    Traceback (most recent call last):
    ValueError: not a hex string
    >>> HexColor('16777215', htmlOnly=True)
    Traceback (most recent call last):
    ValueError: not a hex string

    """ #" for emacs

    if isStr(val):
        val = asNative(val)
        b = 10
        if val[:1] == '#':
            val = val[1:]
            b = 16
            if len(val) == 8:
                alpha = True
        else:
            if htmlOnly:
                raise ValueError('not a hex string')
            if val[:2].lower() == '0x':
                b = 16
                val = val[2:]
                if len(val) == 8:
                    alpha = True
        val = int(val,b)
    if hasAlpha:
        return Color(((val>>24)&0xFF)/255.0,((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0)
    return Color(((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0)
Exemplo n.º 16
0
def checkColor(col):
    "Converts a color name to an RGB tuple, if possible."

    if isStr(col):
        if col in dir(colors):
            col = getattr(colors, col)
            col = (col.red, col.green, col.blue)

    return col
Exemplo n.º 17
0
def checkColor(col):
    "Converts a color name to an RGB tuple, if possible."

    if isStr(col):
        if col in dir(colors):
            col = getattr(colors, col)
            col = (col.red, col.green, col.blue)

    return col
Exemplo n.º 18
0
 def __call__(self, t, controller, overrides, containerdict):
     tag = t[0]
     c = t[2]
     if c is None or not len(c): return t
     ct = type(c)
     c = list(c)
     if isStr(c[0]):
         c[0] = c[0].lstrip()
     if isStr(c[-1]):
         c[-1] = c[-1].rstrip()
     if len(c) == 1 and not c[0]: return t
     t3 = t[3]
     r = [].append
     for s in c:
         if not isStr(s):
             r(s)
         elif s:
             r(('p', None, [s], t3))
     return (t[0], t[1], r.__self__, t3)
Exemplo n.º 19
0
def _getLength(aL,l):
    try:
        if isStr(l):
            l = l.strip()
            if l.endswith('%'):
                return float(l[:-1])*0.01*aL
            else:
                return float(l)
    except:
        pass
    return aL
Exemplo n.º 20
0
 def normalizeName(self, name):
     if not isUnicode(name):
         for enc in ('utf8', 'latin1'):
             try:
                 name = asUnicode(name, enc)
                 break
             except:
                 pass
         else:
             raise ValueError('Cannot normalize name %r' % name)
     r = name.strip().lower()
     nns = getattr(self, 'normalizeNameSpaces', None)
     if isStr(nns):
         r = nns.join(filter(None, r.split()))
     return r
    def __call__(self, arg, default=None):
        '''try to map an arbitrary arg to a color instance
        '''
        if isinstance(arg, Color): return arg
        if isinstance(arg, (tuple, list)):
            assert 3 <= len(
                arg) <= 4, 'Can only convert 3 and 4 sequences to color'
            assert 0 <= min(arg) and max(arg) <= 1
            return len(arg) == 3 and Color(arg[0], arg[1],
                                           arg[2]) or CMYKColor(
                                               arg[0], arg[1], arg[2], arg[3])
        elif isStr(arg):
            arg = asNative(arg)
            C = cssParse(arg)
            if C: return C
            if arg in self.extraColorsNS: return self.extraColorsNS[arg]
            C = getAllNamedColors()
            s = arg.lower()
            if s in C: return C[s]
            G = C.copy()
            G.update(self.extraColorsNS)
            if not self._G:
                C = globals()
                self._G = {
                    s: C[s]
                    for s in
                    '''Blacker CMYKColor CMYKColorSep Color ColorType HexColor PCMYKColor PCMYKColorSep Whiter
                    _chooseEnforceColorSpace _enforceCMYK _enforceError _enforceRGB _enforceSEP _enforceSEP_BLACK
                    _enforceSEP_CMYK _namedColors _re_css asNative cmyk2rgb cmykDistance color2bw colorDistance
                    cssParse describe fade fp_str getAllNamedColors hsl2rgb hue2rgb isStr linearlyInterpolatedColor
                    literal_eval obj_R_G_B opaqueColor rgb2cmyk setColors toColor toColorOrNone'''
                    .split()
                }
            G.update(self._G)
            try:
                return toColor(rl_safe_eval(arg, g=G, l={}))
            except:
                pass

        try:
            return HexColor(arg)
        except:
            if default is None:
                raise ValueError('Invalid color value %r' % arg)
            return default
Exemplo n.º 22
0
    def textLines(self, stuff, trim=1):
        """prints multi-line or newlined strings, moving down.  One
        comon use is to quote a multi-line block in your Python code;
        since this may be indented, by default it trims whitespace
        off each line and from the beginning; set trim=0 to preserve
        whitespace."""
        if isStr(stuff):
            lines = asUnicode(stuff).strip().split(u'\n')
            if trim == 1:
                lines = [s.strip() for s in lines]
        elif isinstance(stuff, (tuple, list)):
            lines = stuff
        else:
            assert 1 == 0, "argument to textlines must be string,, list or tuple"

        # Output each line one at a time. This used to be a long-hand
        # copy of the textLine code, now called as a method.
        for line in lines:
            self.textLine(line)
Exemplo n.º 23
0
    def textLines(self, stuff, trim=1):
        """prints multi-line or newlined strings, moving down.  One
        comon use is to quote a multi-line block in your Python code;
        since this may be indented, by default it trims whitespace
        off each line and from the beginning; set trim=0 to preserve
        whitespace."""
        if isStr(stuff):
            lines = asUnicode(stuff).strip().split(u'\n')
            if trim==1:
                lines = [s.strip() for s in lines]
        elif isinstance(stuff,(tuple,list)):
            lines = stuff
        else:
            assert 1==0, "argument to textlines must be string,, list or tuple"

        # Output each line one at a time. This used to be a long-hand
        # copy of the textLine code, now called as a method.
        for line in lines:
            self.textLine(line)
 def __init__(self, name, base=None):
     self.name = name
     self.frozen = 0
     if name in standardEncodings:
         assert base is None, "Can't have a base encoding for a standard encoding"
         self.baseEncodingName = name
         self.vector = _fontdata.encodings[name]
     elif base == None:
         # assume based on the usual one
         self.baseEncodingName = defaultEncoding
         self.vector = _fontdata.encodings[defaultEncoding]
     elif isStr(base):
         baseEnc = getEncoding(base)
         self.baseEncodingName = baseEnc.name
         self.vector = baseEnc.vector[:]
     elif isSeq(base):
         self.baseEncodingName = defaultEncoding
         self.vector = base[:]
     elif isinstance(base, Encoding):
         # accept a vector
         self.baseEncodingName = base.name
         self.vector = base.vector[:]
Exemplo n.º 25
0
 def test(self,x):
     return isStr(x)
Exemplo n.º 26
0
 def test(self, x):
     return isStr(x)
Exemplo n.º 27
0
    def _textfield(self,
                value='',
                fillColor=None,
                borderColor=None,
                textColor=None,
                borderWidth=1,
                borderStyle='solid',
                width=120,
                height=36,
                x=0,
                y=0,
                tooltip=None,
                name=None,
                annotationFlags='print',
                fieldFlags='',
                forceBorder=False,
                relative=False,
                maxlen=100,
                fontName=None,
                fontSize=None,
                wkind=None,
                options=None,
                dashLen=3,
                ):
        rFontName, iFontName = self.makeFont(fontName)
        if fontSize is None:
            fontSize = 12
        textColor,borderColor,fillColor=self.stdColors(textColor,borderColor,fillColor)
        canv = self.canv
        if relative:
            x, y = self.canv.absolutePosition(x,y)
        doc = canv._doc
        rFontName = '<</%s %s>>' % (iFontName,rFontName)
        Ff = makeFlags(fieldFlags,fieldFlagValues)
        if wkind!='textfield':
            #options must be a list of pairs (label value)
            #value must be a list of the values
            FT='Ch'
            if wkind=='choice':
                Ff |= fieldFlagValues['combo']  #just in case
            V = []
            Opt = []
            AP = []
            I = []
            TF = []
            if not isinstance(options,(list,tuple)):
                raise TypeError('%s options=%r is wrong type' % (wkind,options))
            for v in options:
                if isStr(v):
                    Opt.append(PDFString(v))
                    l = v
                elif isinstance(v,(list,tuple)):
                    if len(v)==1:
                        v=l=v[0]
                    else:
                        l,v = v
                    Opt.append(PDFArray([PDFString(v),PDFString(l)]))
                else:
                    raise TypeError('%s option %r is wrong type' % (wkind,v))
                AP.append(v)
                TF.append(l)
            Opt = PDFArray(Opt)
            if value:
                if not isinstance(value,(list,tuple)):
                    value = [value]
                for v in value:
                    if v not in AP:
                        if v not in TF:
                            raise ValueError('%s value %r is not in option\nvalues %r\nor labels %r' % (wkind,v,AP,TF))
                        else:
                            v = AP[TF.index(v)]
                    I.append(AP.index(v))
                    V.append(PDFString(v))
                I.sort()
                if not (Ff & fieldFlagValues['multiSelect']) or len(value)==1:
                    if wkind=='choice':
                        value = TF[I[0]]
                    else:
                        value = value[:1]
                    V = V[:1]
                V = V[0] if len(V)==1 else PDFArray(V)
                lbextras = dict(labels=TF,I=I,wkind=wkind)
            else:
                V = PDFString(value)
        else:
            I = Opt = []
            lbextras = {}
            FT='Tx'
            if not isStr(value):
                raise TypeError('textfield value=%r is wrong type' % value)
            V = PDFString(value)
        AP = {}
        for key in 'N':
            tC,bC,fC = self.varyColors(key,textColor,borderColor,fillColor)
            ap = self.txAP(
                            key,
                            value,
                            iFontName,
                            rFontName,
                            fontSize,
                            fillColor=fC,
                            borderColor=bC,
                            textColor=tC,
                            borderWidth=borderWidth,
                            borderStyle=borderStyle,
                            width=width,
                            height=height,
                            dashLen = dashLen,
                            **lbextras
                            )
            if ap._af_refstr in self._refMap:
                ref = self._refMap[ap._af_refstr]
            else:
                ref = self.getRef(ap)
                self._refMap[ap._af_refstr] = ref
            AP[key] = ref

        TF = dict(
                FT = PDFName(FT),
                P = doc.thisPageRef(),
                V = V,
                #AS = PDFName(value),
                DV = V,
                Rect = PDFArray((x,y,x+width,y+height)),
                AP = PDFDictionary(AP),
                Subtype = PDFName('Widget'),
                Type = PDFName('Annot'),
                F = makeFlags(annotationFlags,annotationFlagValues),
                Ff = Ff,
                #H=PDFName('N'),
                DA=PDFString('/%s %d Tf %s' % (iFontName,fontSize, self.streamFillColor(textColor))),
                )
        if Opt: TF['Opt'] = Opt
        if I: TF['I'] = PDFArray(I)
        if maxlen:
            TF['MaxLen'] = maxlen
        if tooltip:
            TF['TU'] = PDFString(tooltip)
        if not name:
            name = 'AFF%03d' % len(self.fields)
        TF['T'] = PDFString(name)
        MK = dict(
                BG=PDFArray(self.colorTuple(fillColor)),
                )
        # Acrobat seems to draw a thin border when BS is defined, so only
        # include this if there actually is a border to draw
        if borderWidth:
            TF['BS'] = bsPDF(borderWidth,borderStyle,dashLen)
            MK['BC'] = PDFArray(self.colorTuple(borderColor))
        TF['MK'] = PDFDictionary(MK)

        TF = PDFDictionary(TF)
        self.canv._addAnnotation(TF)
        self.fields.append(self.getRef(TF))
        self.checkForceBorder(x,y,width,height,forceBorder,'square',borderStyle,borderWidth,borderColor,fillColor)
Exemplo n.º 28
0
    def _textfield(
        self,
        value='',
        fillColor=None,
        borderColor=None,
        textColor=None,
        borderWidth=1,
        borderStyle='solid',
        width=120,
        height=36,
        x=0,
        y=0,
        tooltip=None,
        name=None,
        annotationFlags='print',
        fieldFlags='',
        forceBorder=False,
        relative=False,
        maxlen=100,
        fontName=None,
        fontSize=None,
        wkind=None,
        options=None,
        dashLen=3,
    ):
        rFontName, iFontName = self.makeFont(fontName)
        if fontSize is None:
            fontSize = 12
        textColor, borderColor, fillColor = self.stdColors(
            textColor, borderColor, fillColor)
        canv = self.canv
        if relative:
            x, y = self.canv.absolutePosition(x, y)
        doc = canv._doc
        rFontName = '<</%s %s>>' % (iFontName, rFontName)
        Ff = makeFlags(fieldFlags, fieldFlagValues)
        if wkind != 'textfield':
            #options must be a list of pairs (label value)
            #value must be a list of the values
            FT = 'Ch'
            if wkind == 'choice':
                Ff |= fieldFlagValues['combo']  #just in case
            V = []
            Opt = []
            AP = []
            I = []
            TF = []
            if not isinstance(options, (list, tuple)):
                raise TypeError('%s options=%r is wrong type' %
                                (wkind, options))
            for v in options:
                if isStr(v):
                    Opt.append(PDFString(v))
                    l = v
                elif isinstance(v, (list, tuple)):
                    if len(v) == 1:
                        v = l = v[0]
                    else:
                        l, v = v
                    Opt.append(PDFArray([PDFString(v), PDFString(l)]))
                else:
                    raise TypeError('%s option %r is wrong type' % (wkind, v))
                AP.append(v)
                TF.append(l)
            Opt = PDFArray(Opt)
            if value:
                if not isinstance(value, (list, tuple)):
                    value = [value]
                for v in value:
                    if v not in AP:
                        if v not in TF:
                            raise ValueError(
                                '%s value %r is not in option\nvalues %r\nor labels %r'
                                % (wkind, v, AP, TF))
                        else:
                            v = AP[TF.index(v)]
                    I.append(AP.index(v))
                    V.append(PDFString(v))
                I.sort()
                if not (Ff
                        & fieldFlagValues['multiSelect']) or len(value) == 1:
                    if wkind == 'choice':
                        value = TF[I[0]]
                    else:
                        value = value[:1]
                    V = V[:1]
                V = V[0] if len(V) == 1 else PDFArray(V)
                lbextras = dict(labels=TF, I=I, wkind=wkind)
            else:
                V = PDFString(value)
        else:
            I = Opt = []
            lbextras = {}
            FT = 'Tx'
            if not isStr(value):
                raise TypeError('textfield value=%r is wrong type' % value)
            V = PDFString(value)
        AP = {}
        for key in 'N':
            tC, bC, fC = self.varyColors(key, textColor, borderColor,
                                         fillColor)
            ap = self.txAP(key,
                           value,
                           iFontName,
                           rFontName,
                           fontSize,
                           fillColor=fC,
                           borderColor=bC,
                           textColor=tC,
                           borderWidth=borderWidth,
                           borderStyle=borderStyle,
                           width=width,
                           height=height,
                           dashLen=dashLen,
                           **lbextras)
            if ap._af_refstr in self._refMap:
                ref = self._refMap[ap._af_refstr]
            else:
                ref = self.getRef(ap)
                self._refMap[ap._af_refstr] = ref
            AP[key] = ref

        TF = dict(
            FT=PDFName(FT),
            P=doc.thisPageRef(),
            V=V,
            #AS = PDFName(value),
            DV=V,
            Rect=PDFArray((x, y, x + width, y + height)),
            AP=PDFDictionary(AP),
            Subtype=PDFName('Widget'),
            Type=PDFName('Annot'),
            F=makeFlags(annotationFlags, annotationFlagValues),
            Ff=Ff,
            #H=PDFName('N'),
            DA=PDFString(
                '/%s %d Tf %s' %
                (iFontName, fontSize, self.streamFillColor(textColor))),
        )
        if Opt: TF['Opt'] = Opt
        if I: TF['I'] = PDFArray(I)
        if maxlen:
            TF['MaxLen'] = maxlen
        if tooltip:
            TF['TU'] = PDFString(tooltip)
        if not name:
            name = 'AFF%03d' % len(self.fields)
        TF['T'] = PDFString(name)
        MK = dict(BG=PDFArray(self.colorTuple(fillColor)), )
        # Acrobat seems to draw a thin border when BS is defined, so only
        # include this if there actually is a border to draw
        if borderWidth:
            TF['BS'] = bsPDF(borderWidth, borderStyle, dashLen)
            MK['BC'] = PDFArray(self.colorTuple(borderColor))
        TF['MK'] = PDFDictionary(MK)

        TF = PDFDictionary(TF)
        self.canv._addAnnotation(TF)
        self.fields.append(self.getRef(TF))
        self.checkForceBorder(x, y, width, height, forceBorder, 'square',
                              borderStyle, borderWidth, borderColor, fillColor)
Exemplo n.º 29
0
 def __init__(self, s):
     if not isStr(s):
         raise ValueError('need a unicode/bytes argument not %r' % s)
     self._s = s
Exemplo n.º 30
0
 def test(self, x):
     if not isinstance(x, int) and not isStr(x): return False
     return self.normalizeTest(x)
Exemplo n.º 31
0
 def __init__(self,s):
     if not isStr(s):
         raise ValueError('need a unicode/bytes argument not %r' % s)
     self._s = s
Exemplo n.º 32
0
def includePdfFlowables(fileName,
                        pages=None,
                        dx=0, dy=0, sx=1, sy=1, degrees=0,
                        orientation=None,
                        isdata=False,       #True if this is a preprocessed data file
                        leadingBreak=True,  #True/False or 'notattop'
                        template=None,
                        outlineText=None,
                        outlineLevel=0,
                        outlineClosed=0,
                        pdfBoxType = None,
                        autoCrop = False,
                        pageSize=None,
                        callback=None,
                        user_data=None,
                        ):
    '''
    includePdfFlowables creates a list of story flowables that
                        represents an included PDF.
    Arguments       meaning
    fileName        string name of a .pdf or .data file or an object with a read method
    pages           If None all pages will be used, else this argument can
                    be a string like '1,2,4-6,12-10,15' or an explicit
                    list of integers eg [1,2,7].

    dx,dy,          translation together all these make up a transformation
    sx,sy,          scaling     matrix
    degrees,        rotation

    orientation     None or integer degrees eg 0 90 270 or 'portrait'/'landscape'
    isdata          True if fileName argument refers to a .data file (as
                    produced by pageCatcher)
    leadingBreak    True/False or 'notattop' specifies whether a leading
                    page break should be used; 'notattop' means a page break
                    will not be used if the story is at the top of a frame.
    template        If specified the index or name of a template to be used.
    outlineText     Any outline text to be used (default None)
    outlineLevel    The level of any outline text.
    outlineClosed   True/False if the outline should be closed or open.

    pdfBoxType      which box to use or None or [x0,y0,  x1,y1]

    autoCrop        True/False crop/don't crop with CropBox (default is False)
                    boxname use for cropping
                    [x0,y0,  x1,y1] crop area

    pageSize        default None ie leave page size alone
                    'set' adjust page size to incoming box
                    'fit' scale incoming box to fit page size
                    'orthfit' orthogonally scale incoming box to fit
                    'center' or 'centre' center the incoming box in
                    the existing page size
                    [x0,y0, x1,y1] use this as the page size

    callback        draw time callback with signature

                    callback(canvas,key,obj,pdf_data,user_data)

                    canvas the canvas being drawn on
                    key may be 'raw-pre'|'transformed-pre'|'transformed-post'|'raw-post'
                    obj the flowable calling the callback
                    pdf_data ('fileName',pageNumber)
                    user_data user data passed down to the flowable from
                              IncludePdfFlowable.

    user_data       information to be passed to the callback
    '''
    try:
        orientation=int(orientation)
        orientation = orientation % 360
    except:
        if orientation=='portrait':
            orientation = 0
        elif orientation=='landscape':
            orientation = 90
        elif orientation!='auto' and orientation!=None:
            raise ValueError('Bad value %r for orientation attribute' % orientation)

    iptrans = IPTrans(sx,sy,dx,dy,degrees)
    if iptrans.trivial(): iptrans = None

    pages = expandPageNumbers(pages)

    # this one is unusual in that it returns a list of objects to
    # go into the story.
    output = []
    output_append = output.append

    if template:
        output_append(NextPageTemplate(template))

    try:
        if isdata:
            pickledStuff = pickle.loads(open_and_read(fileName))
            formNames = pickledStuff[None]
        else:
            #read in the PDF file right now and get the pickled object
            # and names
            pdfContent = open_and_read(fileName)
            prefix = fileName2Prefix(fileName if isStr(fileName) else pdfContent)
            (formNames, pickledStuff) = storeFormsInMemory(
                    pdfContent,
                    prefix=prefix,
                    all=1,#if pages else 0 #here is where things go wrong
                    #pagenumbers = pages,
                    BBoxes=0,
                    extractText=0,
                    fformname=None)
    except:
        annotateException('\nerror storing %r in memory\n' % fileName)

    #if explicit pages requested, slim it down.
    if pages: #and isdata:
        newNames = []
        for pgNo in pages:
            newNames.append(formNames[pgNo-1])
        formNames = newNames

    #make object 1 for story
    loader = LoadPdfFlowable(pickledStuff,isdata)
    output_append(loader)

    #now do first page.  This is special as it might
    #have an outline
    formName = formNames[0]
    if leadingBreak:
        output_append((leadingBreak=='notattop' and NotAtTopPageBreak or PageBreak)())
    if outlineText:
        output_append(OutlineEntry(outlineLevel, outlineText, outlineClosed))

    if pageSize=='fit':
        class PageSizeHandler(object):
            '''simple class to allow communications between first and last ShowPdfFlowables'''
            _oldPageSize = [None]
            def __init__(self,first):
                self.first = first

            def oldPageSize(self,v):
                self._oldPageSize[0] = v
            oldPageSize = property(lambda self: self._oldPageSize[0],oldPageSize)
        pageSizeHandler = PageSizeHandler(True)
    else:
        pageSizeHandler = None
    output_append(ShowPdfFlowable(formName,orientation=orientation,iptrans=iptrans,
                        callback=callback,
                        pdf_data=(fileName,pages[0] if pages else 1),
                        user_data=user_data,
                        pdfBoxType=pdfBoxType,
                        autoCrop=autoCrop,
                        pageSize=pageSize,
                        pageSizeHandler=pageSizeHandler,
                        ))

    #now make a shower for each laterpage, and a page break
    for i,formName in enumerate(formNames[1:]):
        i += 1
        output_append(PageBreak())
        output_append(ShowPdfFlowable(formName,orientation=orientation,iptrans=iptrans,
                callback=callback,
                pdf_data=(fileName,pages[i] if pages else i),
                user_data=user_data,
                pdfBoxType=pdfBoxType,
                autoCrop=autoCrop,
                pageSize=pageSize,
                pageSizeHandler=None,
                ))
    if pageSize=='fit':
        output[-1]._pageSizeHandler = PageSizeHandler(False)
    return output
Exemplo n.º 33
0
 def test(self,x):
     if not isinstance(x,int) and not isStr(x): return False
     return self.normalizeTest(x)
Exemplo n.º 34
0
def _objStr(s):
    if isStr(s):
        return asNative(s)
    else:
        return str(s)