Example #1
0
 def _path(self, node):
     self.path = self.canvas.beginPath()
     self.path.moveTo(**utils.attr_get(node, ['x', 'y']))
     for child_node in node.childNodes:
         if child_node.nodeType == node.ELEMENT_NODE:
             if child_node.localName == 'moveto':
                 vals = utils.text_get(child_node).split()
                 self.path.moveTo(utils.unit_get(vals[0]),
                                 utils.unit_get(vals[1]))
             elif child_node.localName == 'curvesto':
                 vals = utils.text_get(child_node).split()
                 while len(vals) > 5:
                     pos = []
                     while len(pos) < 6:
                         pos.append(utils.unit_get(vals.pop(0)))
                     self.path.curveTo(*pos)
         elif (child_node.nodeType == node.TEXT_NODE):
             # Not sure if I must merge all TEXT_NODE ?
             data = child_node.data.split()
             while len(data) > 1:
                 x = utils.unit_get(data.pop(0))
                 y = utils.unit_get(data.pop(0))
                 self.path.lineTo(x, y)
     if (not node.hasAttribute('close')) or \
                 utils.bool_get(node.getAttribute('close')):
         self.path.close()
     self.canvas.drawPath(self.path, **utils.attr_get(node, [],
                                     {'fill': 'bool', 'stroke': 'bool'}))
Example #2
0
 def __init__(self, out, node, doc):
     if not node.hasAttribute('pageSize'):
         page_size = (utils.unit_get('21cm'), utils.unit_get('29.7cm'))
     else:
         ps = map(lambda x: x.strip(), node.getAttribute('pageSize') \
                                          .replace(')', '') \
                                          .replace('(', '') \
                                          .split(', '))
         page_size = (utils.unit_get(ps[0]), utils.unit_get(ps[1]))
     self.doc_tmpl = platypus.BaseDocTemplate(out, pagesize=page_size,
                                              **utils.attr_get(node, ['leftMargin', 'rightMargin', 'topMargin', 'bottomMargin'],
                                             {'allowSplitting': 'int', 'showBoundary': 'bool', 'title': 'str', 'author': 'str'}))
     self.page_templates = []
     self.styles = doc.styles
     self.doc = doc
     pts = node.getElementsByTagName('pageTemplate')
     for pt in pts:
         frames = []
         for frame_el in pt.getElementsByTagName('frame'):
             frame = platypus.Frame(**(utils.attr_get(frame_el, ['x1', 'y1', 'width', 'height', 'leftPadding',
                                                                 'rightPadding', 'bottomPadding', 'topPadding'],
                                                                 {'id': 'text', 'showBoundary': 'bool'})))
             frames.append(frame)
         gr = pt.getElementsByTagName('pageGraphics')
         if len(gr):
             drw = Draw(gr[0], self.doc)
             self.page_templates.append(platypus.PageTemplate(frames=frames,
                                         onPage=drw.render, **utils.attr_get(pt, [], {'id': 'str'})))
         else:
             self.page_templates.append(platypus.PageTemplate(frames=frames,
                                         **utils.attr_get(pt, [], {'id': 'str'})))
     self.doc_tmpl.addPageTemplates(self.page_templates)
Example #3
0
 def _rect(self, node):
     if node.hasAttribute('round'):
         kwargs = utils.attr_get(node, ['x', 'y', 'width', 'height'],
                               {'fill': 'bool', 'stroke': 'bool'})
         radius = utils.unit_get(node.getAttribute('round'))
         self.canvas.roundRect(radius=radius,
                                 **kwargs)
     else:
         self.canvas.rect(**utils.attr_get(node,
                         ['x', 'y', 'width', 'height'],
                         {'fill': 'bool', 'stroke': 'bool'}))
Example #4
0
    def draw(self):
        "Read attribs and draw barcode"

        units = ("strokeWidth", "barWidth", "barStrokeWidth", "barHeight",
                 "fontSize", "isoScale")
        colors = ("barFillColor", "background", "strokeColor",
                  "barStrokeColor", "fillColor", "textColor")
        bools = ("humanReadable", "debug", "lquiet", "rquiet", "quiet",
                 "checksum")
        names = ("fontName", "routing")

        kwargs = utils.attr_get(
            self.node,
            units,
            self.encoding,
            dict(
                zip(names, ["str"] * len(names)) +
                zip(colors, ["color"] * len(colors)) +
                zip(bools, ["bool"] * len(bools))),
            {"barStrokeWidth": 0.00001}  # defaults
        )
        bcd = createBarcodeDrawing(self.code_name,
                                   value=self.value,
                                   width=self.width,
                                   height=self.height,
                                   **kwargs)
        renderPDF.draw(bcd,
                       self.canv,
                       self.xpos,
                       self.ypos,
                       showBoundary=self.node.getAttribute("showBoundary"))
Example #5
0
 def _ellipse(self, node):
     x1 = utils.unit_get(node.getAttribute('x'))
     x2 = utils.unit_get(node.getAttribute('width'))
     y1 = utils.unit_get(node.getAttribute('y'))
     y2 = utils.unit_get(node.getAttribute('height'))
     self.canvas.ellipse(x1, y1, x2, y2,
                         **utils.attr_get(node, [],
                             {'fill': 'bool', 'stroke': 'bool'}))
Example #6
0
    def _table(self, node):
        length = 0
        colwidths = None
        rowheights = None
        horizonal_align = None
        vertical_align = None

        data = []
        for tr in _child_get(node, 'tr'):
            data2 = []
            for td in _child_get(tr, 'td'):
                flow = []
                for n in td.childNodes:
                    if n.nodeType == node.ELEMENT_NODE:
                        flow.append(self._flowable(n))
                if not len(flow):
                    flow = self._textual(td)
                data2.append(flow)
            if len(data2) > length:
                length = len(data2)
                for ab in data:
                    while len(ab) < length:
                        ab.append('')
            while len(data2) < length:
                data2.append('')
            data.append(data2)

        if not data:
            raise ParserError("Empty Table")

        if node.hasAttribute('colWidths'):
            colwidths = [utils.unit_get(f.strip()) for f in node.getAttribute('colWidths').split(', ')]
            if len(colwidths) == 1 and length > 1:
                colwidth = colwidths[0]
                colwidths = [colwidth for x in xrange(1, length + 1)]
        if node.hasAttribute('rowHeights'):
            rowheights = [utils.unit_get(f.strip()) for f in node.getAttribute('rowHeights').split(', ')]
            if len(rowheights) == 1 and len(data) > 1:
                rowheight = rowheights[0]
                rowheights = [rowheight for x in xrange(1, len(data) + 1)]
        if node.hasAttribute("hAlign"):
            horizonal_align = node.getAttribute('hAlign')
        if node.hasAttribute("vAlign"):
            vertical_align = node.getAttribute('vAlign')
        table = platypus.Table(data=data, colWidths=colwidths,
                                rowHeights=rowheights, hAlign=horizonal_align,
                                vAlign=vertical_align,
                               **(utils.attr_get(node, ['splitByRow'],
                                                {'repeatRows': 'int', 'repeatCols': 'int'})))
        if node.hasAttribute('style'):
            table.setStyle(self.styles.table_styles[node.getAttribute('style')])
        return table
Example #7
0
    def _place(self, node):
        flows = Flowable(self.doc).render(node)
        infos = utils.attr_get(node, ['x', 'y', 'width', 'height'])

        infos['y'] += infos['height']
        for flow in flows:
            width, height = flow.wrap(infos['width'], infos['height'])
            if width <= infos['width'] and height <= infos['height']:
                infos['y'] -= height
                flow.drawOn(self.canvas,
                            infos['x'],
                            infos['y'])
                infos['height'] -= height
            else:
                raise ValueError("Not enough space")
Example #8
0
    def draw(self):
        "Read attribs and draw barcode"

        units = ("strokeWidth", "barWidth", "barStrokeWidth", "barHeight",
                 "fontSize", "isoScale")
        colors = ("barFillColor", "background", "strokeColor", "barStrokeColor",
                  "fillColor", "textColor")
        bools = ("humanReadable", "debug", "lquiet", "rquiet", "quiet",
                 "checksum")
        names = ("fontName", "routing")

        kwargs = utils.attr_get(self.node, units,
                                self.encoding,
                                dict(zip(names, ["str"] * len(names)) +
                                     zip(colors, ["color"] * len(colors)) +
                                     zip(bools, ["bool"] * len(bools))),
                                {"barStrokeWidth": 0.00001} # defaults
                    )
        bcd = createBarcodeDrawing(self.code_name, value=self.value,
                                   width=self.width, height=self.height,
                                   **kwargs)
        renderPDF.draw(bcd, self.canv, self.xpos, self.ypos,
                       showBoundary=self.node.getAttribute("showBoundary"))
Example #9
0
 def _flowable(self, node):
     if node.localName == 'para':
         style = self.styles.para_style_get(node)
         return platypus.Paragraph(self._textual(node), style,
                                     **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == "p":
         # support html <p> for paragraph tags
         style = self.styles.para_style_get(node)
         return platypus.Paragraph(self._textual(node), style,
                                     **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'name':
         self.styles.names[node.getAttribute('id')] = node.getAttribute('value')
         return None
     elif node.localName == 'xpre':
         style = self.styles.para_style_get(node)
         return platypus.XPreformatted(self._textual(node), style, **(utils.attr_get(node, [],
                                     {'bulletText': 'str',
                                         'dedent': 'int',
                                         'frags': 'int'})))
     elif node.localName == 'pre':
         style = self.styles.para_style_get(node)
         return platypus.Preformatted(self._textual(node), style,
                                     **(utils.attr_get(node, [],
                                         {'bulletText': 'str', 'dedent': 'int'})))
     elif node.localName == 'illustration':
         return  self._illustration(node)
     elif node.localName == 'blockTable':
         return  self._table(node)
     elif node.localName == 'title':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         # FIXME: better interface for accessing styles see TODO
         style = self.styles.styles.get('style.Title', styles['Title'])
         return platypus.Paragraph(self._textual(node), style,
                                     **(utils.attr_get(node, [],
                                         {'bulletText': 'str'})))
     elif node.localName == 'h1':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         # although not defined in spec, we assume same as "title" see RML spec
         style = self.styles.styles.get('style.h1', styles['Heading1'])
         return platypus.Paragraph(self._textual(node), style,
                                     **(utils.attr_get(node, [],
                                         {'bulletText': 'str'})))
     elif node.localName == 'h2':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         # although not defined in spec, we assume same as "title" see RML spec
         style = self.styles.styles.get('style.h2', styles['Heading2'])
         return platypus.Paragraph(self._textual(node), style,
                                     **(utils.attr_get(node, [],
                                         {'bulletText': 'str'})))
     elif node.localName == 'h3':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         # although not defined in spec, we assume same as "title" see RML spec
         style = self.styles.styles.get('style.h2', styles['Heading3'])
         return platypus.Paragraph(self._textual(node), style,
                                     **(utils.attr_get(node, [],
                                         {'bulletText': 'str'})))
     elif node.localName == 'image':
         return platypus.Image(node.getAttribute('file'),
                                     mask=(250, 255, 250, 255, 250, 255),
                                     **(utils.attr_get(node, ['width', 'height'])))
     elif node.localName == 'spacer':
         if node.hasAttribute('width'):
             width = utils.unit_get(node.getAttribute('width'))
         else:
             width = utils.unit_get('1cm')
         length = utils.unit_get(node.getAttribute('length'))
         return platypus.Spacer(width=width, height=length)
     elif node.localName == 'pageBreak':
         return platypus.PageBreak()
     elif node.localName == 'condPageBreak':
         return platypus.CondPageBreak(**(utils.attr_get(node, ['height'])))
     elif node.localName == 'setNextTemplate':
         return platypus.NextPageTemplate(str(node.getAttribute('name')))
     elif node.localName == 'nextFrame':
         return platypus.CondPageBreak(1000)           # TODO: change the 1000 !
     elif node.localName=='keepInFrame':
         substory = []
         subnode = node.firstChild
         while subnode:
             if node.nodeType == node.ELEMENT_NODE:
                 subflow = self._flowable(subnode)
                 if subflow:
                     substory.append(subflow)
             subnode = subnode.nextSibling
         return platypus.KeepInFrame(content=substory,
                                     **(utils.attr_get(node, ['maxWidth','maxHeight'],
                                                       {'name':'str','mode':'str'})))
     elif node.localName is None:
         return None
     else:
         raise ParserError('%s Flowable Not Implemented' % node.localName)
         return None
Example #10
0
 def _circle(self, node):
     self.canvas.circle(x_cen=utils.unit_get(node.getAttribute('x')),
                        y_cen=utils.unit_get(node.getAttribute('y')),
                        r=utils.unit_get(node.getAttribute('radius')),
                        **utils.attr_get(node, [], {'fill': 'bool',
                                                    'stroke': 'bool'}))
Example #11
0
 def _draw_right_string(self, node):
     self.canvas.drawRightString(text=self._textual(node),
                                 **utils.attr_get(node, ['x', 'y']))
Example #12
0
 def _draw_centred_string(self, node):
     self.canvas.drawCentredString(text=self._textual(node),
                             **utils.attr_get(node, ['x', 'y']))