def test_pdf(self):
        canvas = GeoCanvas(StringIO())

        registration = PDFArray([
            PDFArray(map(PDFString, ['200', '400', '-180', '-90'])),
            PDFArray(map(PDFString, ['200', '600', '-180', '90'])),
            PDFArray(map(PDFString, ['400', '600', '180', '90'])),
            PDFArray(map(PDFString, ['400', '400', '180', '-90']))
        ])
        canvas.rect(200, 400, 200, 200, stroke=1)
        canvas.addGeo(Registration=registration)

        self.assertTrue('LGIDict' in canvas.getpdfdata())

        canvas.save()
Ejemplo n.º 2
0
def SelectField(title,
                value,
                options,
                xmin,
                ymin,
                xmax,
                ymax,
                page,
                font="Helvetica-Bold",
                fontsize=9,
                R=0,
                G=0,
                B=0.627):
    #print "ARGS", (title, value, options, xmin, ymin, xmax, ymax, page, font, fontsize, R, G, B)
    from reportlab.pdfbase.pdfdoc import PDFString, PDFName, PDFArray
    if value not in options:
        raise ValueError("value %s must be one of options %s" %
                         (repr(value), repr(options)))
    fontname = FORMFONTNAMES[font]
    optionstrings = list(map(PDFString, options))
    optionarray = PDFArray(optionstrings)
    return PDFPattern(SelectFieldPattern,
                      Options=optionarray,
                      Selected=PDFString(value),
                      Page=page,
                      Name=PDFString(title),
                      xmin=xmin,
                      ymin=ymin,
                      xmax=xmax,
                      ymax=ymax,
                      fontname=PDFName(fontname),
                      fontsize=fontsize,
                      R=R,
                      G=G,
                      B=B)
Ejemplo n.º 3
0
    def makeStream(self, width, height, stream, **D):
        D['Matrix'] = PDFArray([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
        D['BBox'] = PDFArray([0, 0, width, height])
        D['Subtype'] = PDFName('Form')
        D['Type'] = PDFName('XObject')
        D['FormType'] = 1

        s = PDFStream(
            PDFDictionary(D),
            stream,
            filters=[PDFStreamFilterZCompress()]
            if self.canv._doc.compression else None,
        )
        #compute a lookup string
        s._af_refstr = stream + '\n'.join(
            ('%s=%r' % (k, _pdfObjToStr(v)) for k, v in sorted(D.items())))
        return s
Ejemplo n.º 4
0
def bsPDF(borderWidth, borderStyle, dashLen):
    d = dict(W=borderWidth, S=PDFName(_bsStyles[borderStyle]))
    if borderStyle == 'dashed':
        if not dashLen:
            dashLen = [3]
        elif not isinstance(dashLen, (list, tuple)):
            dashLen = [dashLen]
        d['D'] = PDFArray(dashLen)
    return PDFDictionary(d)
Ejemplo n.º 5
0
 def format(self, document):
     from reportlab.pdfbase.pdfdoc import PDFArray
     proxy = PDFPattern(FormPattern,
                        Resources=getattr(self, 'resources', None)
                        or FormResources(),
                        NeedAppearances=getattr(self, 'needAppearances',
                                                'false'),
                        fields=PDFArray(self.fields),
                        SigFlags=getattr(self, 'sigFlags', 0))
     return proxy.format(document)
Ejemplo n.º 6
0
 def format(self, doc):
     d = dict(Fields=PDFArray([self.getRef(f) for f in self.fields]), )
     if self.fonts:
         F = [self.fontRef(f) for f in self.fonts]
         d['DA'] = PDFString('/%s 0 Tf 0 g' % list(self.fonts.keys())[0])
         d['DR'] = PDFFromString(
             '<< /Encoding\n<<\n/RLAFencoding\n%s\n>>\n%s\n>>' %
             (self.encRefStr, '\n'.join(F)))
     r = PDFDictionary(d).format(doc)
     return r
Ejemplo n.º 7
0
 def format(self, doc):
     d = dict(Fields=PDFArray([self.getRef(f) for f in self.fields]), )
     if self.sigFlags: d['SigFlags'] = self.sigFlags
     if self.fonts:
         FK = list(sorted(self.fonts.keys()))
         F = [self.fontRef(f) for f in FK]
         d['DA'] = PDFString('/%s 0 Tf 0 g' % FK[0])
         d['DR'] = PDFFromString(
             '<< /Encoding\n<<\n/RLAFencoding\n%s\n>>\n%s\n>>' %
             (self.encRefStr, '\n'.join(F)))
     d.update(self.extras)
     r = PDFDictionary(d).format(doc)
     return r
Ejemplo n.º 8
0
    def format(self,doc):
        kids = self.kids
        d = len(kids)
        if d<2: raise ValueError('RadioGroup:%s has %d < 2 RadioBoxes' % (self.T,d))

        d = dict(
                Ff=self.Ff,
                Kids = PDFArray([k for k in self.kids]),
                FT = PDFName('Btn'),
                T = PDFString(self.T),
                #DA = PDFString('0 g'),
                )
        if self.V: d['V'] = PDFName(self.V)
        if self.TU: d['TU'] =PDFString(self.TU)
        r = PDFDictionary(d).format(doc)
        return r
def convert(point):
"""Convert lat/lon to screen coordinates"""
lon = point[0]
lat = point[1]
x = map_width - ((maxx - lon) * x_ratio)
y = map_height - ((maxy - lat) * y_ratio)
# Python turtle graphics start in the middle of the screen
# so we must offset the points so they are centered
x = x + 100
y = y + 400
return [x, y]
# Set up our map labels
canvas.setFont("Helvetica", 20)
canvas.drawString(250, 500, "COLORADO")
# Use smaller text for cities
canvas.setFont("Helvetica", 8)
# Draw points and label the cities
for city in cities:
pixel = convert(city[POINTS])
print(pixel)
# Place a point for the city
canvas.circle(pixel[0], pixel[1], 5, stroke=1, fill=1) 
# Label the city
canvas.drawString(pixel[0] + 10, pixel[1], city[NAME] + ", Population: " + str(city[POP]))
# A series of registration point pairs (pixel x, pixel y, x, y)
# to spatially enable the PDF. We only need to do the state boundary.
# The cities will be contained with in it.
registration = PDFArray([
PDFArray(map(PDFString, ['100', '400', '{}'.format(minx), '{}'.format(maxy)])),
PDFArray(map(PDFString, ['500', '400', '{}'.format(maxx), '{}'.format(maxy)])),
PDFArray(map(PDFString, ['100', '150', '{}'.format(minx), '{}'.format(miny)])),
PDFArray(map(PDFString, ['500', '150', '{}'.format(maxx), '{}'.format(miny)]))
])
# Add the map registration
canvas.addGeo(Registration=registration)
# Save our geopdf
canvas.save()
Ejemplo n.º 10
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)
Ejemplo n.º 11
0
    def radio(
        self,
        value=None,
        selected=False,
        buttonStyle='circle',
        shape='circle',
        fillColor=None,
        borderColor=None,
        textColor=None,
        borderWidth=1,
        borderStyle='solid',
        size=20,
        x=0,
        y=0,
        tooltip=None,
        name=None,
        annotationFlags='print',
        fieldFlags='noToggleToOff required radio',
        forceBorder=False,
        relative=False,
        dashLen=3,
    ):
        if name not in self._radios:
            group = RadioGroup(name, tooltip=tooltip, fieldFlags=fieldFlags)
            group._ref = self.getRef(group)
            self._radios[name] = group
            self.fields.append(group._ref)
        else:
            group = self._radios[name]
            fieldFlags = makeFlags(fieldFlags, fieldFlagValues)
            if fieldFlags != group.Ff:
                raise ValueError('radio.%s.%s created with different flags' %
                                 (name, value))
        if not value:
            raise ValueError('bad value %r for radio.%s' % (value, name))
        initialValue = value if selected else 'Off'
        textColor, borderColor, fillColor = self.stdColors(
            textColor, borderColor, fillColor)

        if initialValue == value:
            if group.V is not None:
                if group.V != value:
                    raise ValueError(
                        'radio.%s.%s sets initial value conflicting with %s' %
                        (name, value, group.V))
            else:
                group.V = value
        canv = self.canv
        if relative:
            x, y = self.canv.absolutePosition(x, y)
        doc = canv._doc
        AP = {}
        for key in 'NDR':
            APV = {}
            tC, bC, fC = self.varyColors(key, textColor, borderColor,
                                         fillColor)
            for v in (value, 'Off'):
                ap = self.checkboxAP(
                    key,
                    'Yes' if v == value else 'Off',
                    buttonStyle=buttonStyle,
                    shape=shape,
                    fillColor=fC,
                    borderColor=bC,
                    textColor=tC,
                    borderWidth=borderWidth,
                    borderStyle=borderStyle,
                    size=size,
                    dashLen=dashLen,
                )
                if ap._af_refstr in self._refMap:
                    ref = self._refMap[ap._af_refstr]
                else:
                    ref = self.getRef(ap)
                    self._refMap[ap._af_refstr] = ref
                APV[v] = ref
            AP[key] = PDFDictionary(APV)
            del APV
        RB = dict(
            FT=PDFName('Btn'),
            P=doc.thisPageRef(),
            AS=PDFName(initialValue),
            #DV = PDFName(initialValue),
            Rect=PDFArray((x, y, x + size, y + size)),
            AP=PDFDictionary(AP),
            Subtype=PDFName('Widget'),
            Type=PDFName('Annot'),
            F=makeFlags(annotationFlags, annotationFlagValues),
            Parent=group._ref,
            #DA = PDFString('1 g '+(self.streamFillColor(fillColor) if fillColor else '-0.25 0.75 -0.25 rg'))
            H=PDFName('N'),
        )
        #RB['T'] = PDFString(name)
        MK = dict(
            CA='(%s)' % ZDSyms[buttonStyle],
            BC=PDFArray(self.colorTuple(borderColor)),
            BG=PDFArray(self.colorTuple(fillColor)),
        )
        if borderWidth: RB['BS'] = bsPDF(borderWidth, borderStyle, dashLen)
        RB['MK'] = PDFDictionary(MK)
        RB = PDFDictionary(RB)
        self.canv._addAnnotation(RB)
        group.kids.append(self.getRef(RB))
        self.checkForceBorder(x, y, size, size, forceBorder, shape,
                              borderStyle, borderWidth, borderColor, fillColor)
Ejemplo n.º 12
0
 def checkbox(
     self,
     checked=False,
     buttonStyle='check',
     shape='square',
     fillColor=None,
     borderColor=None,
     textColor=None,
     borderWidth=1,
     borderStyle='solid',
     size=20,
     x=0,
     y=0,
     tooltip=None,
     name=None,
     annotationFlags='print',
     fieldFlags='required',
     forceBorder=False,
     relative=False,
     dashLen=3,
 ):
     initialValue = 'Yes' if checked else 'Off'
     textColor, borderColor, fillColor = self.stdColors(
         textColor, borderColor, fillColor)
     canv = self.canv
     if relative:
         x, y = self.canv.absolutePosition(x, y)
     doc = canv._doc
     AP = {}
     for key in 'NDR':
         APV = {}
         tC, bC, fC = self.varyColors(key, textColor, borderColor,
                                      fillColor)
         for value in ('Yes', 'Off'):
             ap = self.checkboxAP(
                 key,
                 value,
                 buttonStyle=buttonStyle,
                 shape=shape,
                 fillColor=fC,
                 borderColor=bC,
                 textColor=tC,
                 borderWidth=borderWidth,
                 borderStyle=borderStyle,
                 size=size,
                 dashLen=dashLen,
             )
             if ap._af_refstr in self._refMap:
                 ref = self._refMap[ap._af_refstr]
             else:
                 ref = self.getRef(ap)
                 self._refMap[ap._af_refstr] = ref
             APV[value] = ref
         AP[key] = PDFDictionary(APV)
         del APV
     CB = dict(
         FT=PDFName('Btn'),
         P=doc.thisPageRef(),
         V=PDFName(initialValue),
         AS=PDFName(initialValue),
         #DV = PDFName(initialValue),
         Rect=PDFArray((x, y, x + size, y + size)),
         AP=PDFDictionary(AP),
         Subtype=PDFName('Widget'),
         Type=PDFName('Annot'),
         F=makeFlags(annotationFlags, annotationFlagValues),
         Ff=makeFlags(fieldFlags, fieldFlagValues),
         H=PDFName('N'),
     )
     if tooltip:
         CB['TU'] = PDFString(tooltip)
     if not name:
         name = 'AFF%03d' % len(self.fields)
     if borderWidth: CB['BS'] = bsPDF(borderWidth, borderStyle, dashLen)
     CB['T'] = PDFString(name)
     MK = dict(
         CA='(%s)' % ZDSyms[buttonStyle],
         BC=PDFArray(self.colorTuple(borderColor)),
         BG=PDFArray(self.colorTuple(fillColor)),
     )
     CB['MK'] = PDFDictionary(MK)
     CB = PDFDictionary(CB)
     self.canv._addAnnotation(CB)
     self.fields.append(self.getRef(CB))
     self.checkForceBorder(x, y, size, size, forceBorder, shape,
                           borderStyle, borderWidth, borderColor, fillColor)
 def format(self, document):
     from reportlab.pdfbase.pdfdoc import PDFArray
     proxy = PDFPattern(FormPattern,
                        Resources=GLOBALRESOURCES,
                        fields=PDFArray(self.fields))
     return proxy.format(document)
Ejemplo n.º 14
0
 def _startPage(self):
     # now get ready for the next one
     super(GeoCanvas, self)._startPage()
     self.LGIDict = PDFArray([])
Ejemplo n.º 15
0
class GeoCanvas(canvas.Canvas):

    LGIDict = PDFArray([])

    def _startPage(self):
        # now get ready for the next one
        super(GeoCanvas, self)._startPage()
        self.LGIDict = PDFArray([])

    def showPage(self):
        """Close the current page and possibly start on a new page."""
        # ensure a space at the end of the stream - Acrobat does
        # not mind, but Ghostscript dislikes 'Qendstream' even if
        # the length marker finishes after 'Q'

        pageWidth = self._pagesize[0]
        pageHeight = self._pagesize[1]
        cM = self._cropMarks
        code = self._code
        if cM:
            bw = max(0, getattr(cM, 'borderWidth', 36))
            if bw:
                markLast = getattr(cM, 'markLast', 1)
                ml = min(bw, max(0, getattr(cM, 'markLength', 18)))
                mw = getattr(cM, 'markWidth', 0.5)
                mc = getattr(cM, 'markColor', black)
                mg = 2 * bw - ml
                cx0 = len(code)
                if ml and mc:
                    self.saveState()
                    self.setStrokeColor(mc)
                    self.setLineWidth(mw)
                    self.lines([
                        (bw, 0, bw, ml),
                        (pageWidth + bw, 0, pageWidth + bw, ml),
                        (bw, pageHeight + mg, bw, pageHeight + 2 * bw),
                        (pageWidth + bw, pageHeight + mg, pageWidth + bw, pageHeight + 2 * bw),
                        (0, bw, ml, bw),
                        (pageWidth + mg, bw, pageWidth + 2 * bw, bw),
                        (0, pageHeight + bw, ml, pageHeight + bw),
                        (pageWidth + mg, pageHeight + bw, pageWidth + 2 * bw, pageHeight + bw)
                    ])
                    self.restoreState()
                    if markLast:
                        # if the marks are to be drawn after the content
                        # save the code we just drew for later use
                        L = code[cx0:]
                        del code[cx0:]
                        cx0 = len(code)

                bleedW = max(0, getattr(cM, 'bleedWidth', 0))
                self.saveState()
                self.translate(bw - bleedW, bw - bleedW)
                if bleedW:
                    # scale everything
                    self.scale(1 + (2.0 * bleedW) / pageWidth, 1 + (2.0 * bleedW) / pageHeight)

                # move our translation/expansion code to the beginning
                C = code[cx0:]
                del code[cx0:]
                code[0:0] = C
                self.restoreState()
                if markLast:
                    code.extend(L)
                pageWidth = 2 * bw + pageWidth
                pageHeight = 2 * bw + pageHeight

        code.append(' ')
        page = pdfdoc.PDFPage()
        page.__NoDefault__ = """Parent
        MediaBox Resources Contents CropBox Rotate Thumb Annots B Dur Hid Trans AA
        PieceInfo LastModified SeparationInfo ArtBox TrimBox BleedBox ID PZ
        Trans LGIDict""".split()
        page.pagewidth = pageWidth
        page.pageheight = pageHeight

        if getattr(self, 'LGIDict', None):
            if len(self.LGIDict.sequence) == 1:
                page.LGIDict = self.LGIDict.sequence[0]
            else:
                page.LGIDict = self.LGIDict

        page.Rotate = self._pageRotation
        page.hasImages = self._currentPageHasImages
        page.setPageTransition(self._pageTransition)
        page.setCompression(self._pageCompression)
        if self._pageDuration is not None:
            page.Dur = self._pageDuration

        strm = self._psCommandsBeforePage + [self._preamble] + code + self._psCommandsAfterPage
        page.setStream(strm)
        self._setColorSpace(page)
        self._setExtGState(page)
        self._setXObjects(page)
        self._setShadingUsed(page)
        self._setAnnotations(page)
        self._doc.addPage(page)

        if self._onPage:
            self._onPage(self._pageNumber)
        self._startPage()

    def addGeo(self, **kwargs):
        """
        Adds the LGIDict to the document.
        :param kwargs: Keyword arguments that are used to update the LGI Dictionary.
        """

        lgi = LGIDict()
        lgi.dict.update(kwargs)

        if not lgi.is_valid():
            return

        pdf_obj = lgi.format(self._doc)
        self.LGIDict.sequence.append(pdf_obj)
        return pdf_obj
canvas.drawString(250, 500, "COLORADO")

# Use smaller text for cities
canvas.setFont("Helvetica", 8)

# Draw points and label the cities
for city in cities:
    pixel = convert(city[POINTS])
    print(pixel)

# Place a point for the city
canvas.circle(pixel[0], pixel[1], 5, stroke=1, fill=1) 

# Label the city
canvas.drawString(pixel[0] + 10, pixel[1], city[NAME] + ", Population: " + str(city[POP]))

# A series of registration point pairs (pixel x, pixel y, x, y)
# to spatially enable the PDF. We only need to do the state boundary.
# The cities will be contained with in it.
registration = PDFArray([
PDFArray(map(PDFString, ['100', '400', '{}'.format(minx), '{}'.format(maxy)])),
PDFArray(map(PDFString, ['500', '400', '{}'.format(maxx), '{}'.format(maxy)])),
PDFArray(map(PDFString, ['100', '150', '{}'.format(minx), '{}'.format(miny)])),
PDFArray(map(PDFString, ['500', '150', '{}'.format(maxx), '{}'.format(miny)]))
])

# Add the map registration
canvas.addGeo(Registration=registration)

# Save our geopdf
canvas.save()