Example #1
0
def renderGerber(f_copper, f_overlay, canv):
    global gerberExtents

    canv.setLineWidth(0.0)
    gm = GerberMachine("", canv)
    gm.Initialize()
    ResetExtents()
    gm.setColors(colors.Color(0.85, 0.85, 0.85), colors.Color(0, 0, 0))
    gm.ProcessFile(f_copper)
    gm.setColors(colors.Color(0.5, 0.5, 0.5), colors.Color(0, 0, 0))
    return gm.ProcessFile(f_overlay)
Example #2
0
def parseColor(color):
    """
    Convert SVG color to reportlab color
    """
    if color == 'none':
        return None

    elif color == 'currentColor':
        return "currentColor"

    elif color == 'transparent':
        return colors.Color(0.,0.,0.,0.)

    match = color_match(color)
    if match is None:
        raise SVGError("Not a valid color definition: '%s'" % color)

    info = match.groupdict()

    if info['named'] is not None:
        if not color in NAMEDCOLOURS:
            raise SVGError("Not a valid named color: '%s'" % color)

        return NAMEDCOLOURS[color]

    elif info['hex'] is not None:
        return colors.HexColor(color)

    elif info['hexshort'] is not None:
        r = 2*info['hexshort_r']
        g = 2*info['hexshort_g']
        b = 2*info['hexshort_b']

        return colors.HexColor('#%s%s%s' % (r,g,b))

    elif info['rgbint'] is not None:
        r = int(info['rgbint_r'])
        g = int(info['rgbint_g'])
        b = int(info['rgbint_b'])

        if r > 255 or g > 255 or b > 255:
            raise SVGError("RGB value outside range: '%s'" % color)

        return colors.Color(r/255., g/255., b/255.)

    elif info['rgb'] is not None:
        r = float(info['rgb_r'])
        g = float(info['rgb_g'])
        b = float(info['rgb_b'])

        if r > 100 or g > 100 or b > 100:
            raise SVGError("RGB value outside range: '%s'" % color)

        return colors.Color(r/100., g/100., b/100.)
Example #3
0
    def __init__(self, fname):
        print("Load")
        f = open(fname, 'r')
        rows = []
        for line in f:
            rows.append(line.split())

        self.col_map = [
            colors.Color(1, 0, 0),
            colors.Color(1, 1, 0),
            colors.Color(0, 1, 0),
            colors.Color(0, 1, 1),
            colors.Color(1, 0, 1),
            colors.Color(0, 0, 1),
            colors.Color(0, 0, 0),
            colors.Color(0.80392, 0.52157, 0.24706),
            colors.Color(0.48627, 0.65098, 0.34902),
            colors.Color(0.58431, 0.62353, 0.87059)
        ]

        #	Ref    Val                  Package         PosX       PosY        Rot     Side

        i_dsg = rows[0].index("Ref")
        i_desc = rows[0].index("Val")
        i_cx = rows[0].index("PosX")
        i_cy = rows[0].index("PosY")
        i_layer = rows[0].index("Side")

        self.layers = {}
        self.layers["Top"] = {}
        self.layers["Bottom"] = {}

        print(i_dsg, i_desc, i_cx, i_cy)
        for i in rows[1:]:
            if (len(i) > 0):
                print(i[i_dsg], i[i_cx])
                cx = float(i[i_cx]) * mm
                cy = float(i[i_cy]) * mm

                w = 1 * mm
                h = 1 * mm
                l = i[i_layer]
                if l == "top":
                    layer = "Top"
                else:
                    layer = "Bottom"
                ref = i[i_desc]
                #                print(ref,cy, py)
                if (not ref in self.layers[layer]):
                    self.layers[layer][ref] = []
                self.layers[layer][ref].append(
                    PPComponent(cx, cy, w, h, i[i_dsg], i[i_desc], ref))
Example #4
0
 def prime_bunnies(self, **kwargs):
     # number line with prime bunny hops as bezier
     size = kwargs.get('size', 12)
     width = kwargs.get('width', self.width +
                        self.margin)  # go all the way to right edge
     height = kwargs.get('height', self.height + self.margin)
     hop = (1. * height / size)
     alpha = .5
     self.can.setFont(self.header_font, self.header_size)
     self.can.rotate(90)
     self.can.drawCentredString(height / 2, -2 * self.header_size,
                                "The Prime Bunnies")
     y = -2 * self.header_size - 10
     self.can.setFillColor(colors.Color(0, 0, 0, .2))
     start = 10 + 1 * hop
     self.can.circle(start,
                     -width + 2 * self.header_size,
                     hop / 2,
                     stroke=0,
                     fill=1)
     self.can.setStrokeColor(colors.Color(0, 0, 0, .1))
     # bottom circles for filling in prime numbers / prime factors
     for i in range(0, size + 10):
         self.can.circle(i * hop + start,
                         -width + 2 * self.header_size,
                         hop / 2,
                         stroke=1,
                         fill=0)
     self.can.setLineWidth(1)
     self.can.setStrokeColor(colors.Color(0, 0, 0, alpha))
     for p in [
             2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
             61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
             131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191,
             193, 197, 199
     ]:
         if p > size * 2:
             break
         self.can.setDash([1, 2])
         #  dash breaks down for large p
         #  self.can.setDash([1,1]*p+[p,1])
         phop = p * hop
         for i in range(0, size + 1):
             self.can.bezier(
                 i * phop + start, -width + 2 * self.header_size + hop / 2,
                 (i + .25) * phop + start,
                 -width + 2 * self.header_size + hop / 2 + phop * .9,
                 (i + .75) * phop + start,
                 -width + 2 * self.header_size + hop / 2 + phop * .9,
                 (i + 1) * phop + start,
                 -width + 2 * self.header_size + hop / 2)
Example #5
0
    def counting_table(self, **kwargs):
        size = kwargs.get('size', 10)
        base = kwargs.get('base', 10)
        width = kwargs.get('width', self.width)
        height = kwargs.get('height', self.height)
        height = kwargs.get('height', self.height)
        font_alpha = kwargs.get(
            'font_alpha',
            1)  # set to between 0-1 for stroke alpha in the numbers
        font_alpha_top = kwargs.get(
            'font_alpha_top',
            1)  # set to between 0-1 for stroke alpha in top numbers
        x = 0
        y = height - self.header_size
        self.can.setFont(self.header_font, self.header_size)
        self.can.drawCentredString(width / 2, y, "Counting Numbers")
        y -= self.header_size * 1 / 2.

        font_size = 240 / size
        font_size = max(12, font_size * base / 10)
        #if base == 2: font_size/=2

        self.can.setFont(self.header_font, font_size)
        dx = dy = width / (size + 1)
        x += dx
        xlist = [x - dx / 2]
        for c in range(1, size + 1):
            cx = x + (c - 1) * dx
            ylist = [y - dy / 2 + font_size / 2 - 2]
            xlist.append(cx + dx / 2)
            for r in range(0, size):
                cy = y - (r + 1) * dy
                p = size * r + c
                if base != 10:
                    if not Bases:
                        raise Exception(
                            "`pip install bases.py` to use a base other than 10."
                        )
                    p = Bases.toBase(p, base)
                if r == 0:
                    self.can.setFillColor(colors.Color(0, 0, 0,
                                                       font_alpha_top))
                else:
                    self.can.setFillColor(colors.Color(0, 0, 0, font_alpha))

                self.can.drawCentredString(cx, cy, "%s" % (p, ))
                ylist.append(cy - dy / 2 + font_size / 2 - 2)

        self.can.setStrokeColor(
            colors.Color(21 / 255., 21 / 255., 21 / 255., 0.1))
        self.can.grid(xlist, ylist)
Example #6
0
    def standardRCGTableStyle(fontSize=7, padding=0.5):

        font = 'Times-Roman'
        rcgblue2 = colors.Color(0.33, 0.30, 0.55)
        lightgrey = colors.Color(0.7, 0.7, 0.7)
        return [('FONT', (0, 0), (-1, -1), font, fontSize),
                ('TOPPADDING', (0, 0), (-1, -1), padding),
                ('BOTTOMPADDING', (0, 0), (-1, -1), padding),
                ('ALIGN', (1, 0), (-1, -1), 'CENTER'),
                ('ALIGN', (1, 1), (1, -1), 'RIGHT'),
                ('LINEABOVE', (0, 1), (-1, 1), 1, rcgblue2),
                ('FONT', (0, 0), (-1, 0), font),
                ('ROWBACKGROUNDS', (0, 1), (-1, -1), [lightgrey, None]),
                ('FONT', (0, -1), (-1, -1), font)]
    def get_table_style():
        return TableStyle([
            ('SPAN', (0, 0), (3, 0)),  # Baseline
            ('BACKGROUND', (0, 0), (3, 0),
             colors.Color(224 / 255, 236 / 255, 244 / 255)),

            # Title bar
            ('LINEBELOW', (0, 1), (3, 1), 0.5,
             colors.Color(0 / 255, 133 / 255, 183 / 255)),
            ('LINEBELOW', (0, 2), (3, 2), 0.5,
             colors.Color(0 / 255, 133 / 255, 183 / 255)),

            # Entire table
            # ('GRID', (0, 0), (-1, -1), 0.5, colors.Color(91/255, 91/255, 93/255)),
        ])
    def test_1(self):
        "Test color attribute conversion to CMYK"

        mapping = (
            ("red", force_cmyk(colors.red)),
            ("#ff0000", force_cmyk(colors.red)),
            ("#f00", force_cmyk(colors.red)),
            ("rgb(100%,0%,0%)", force_cmyk(colors.red)),
            ("rgb(255, 0, 0)", force_cmyk(colors.red)),
            ("rgb(0,255, 0)", force_cmyk(colors.Color(0, 1, 0))),
            ("rgb(0, 0, 255)", force_cmyk(colors.Color(0, 0, 1))),
        )
        ac = svglib.Svg2RlgAttributeConverter(color_converter=force_cmyk)
        failed = _testit(ac.convertColor, mapping)
        assert len(failed) == 0
Example #9
0
 def __init__(self,
              a,
              b,
              size,
              grid_color=colors.Color(236 / 255., 236 / 255., 236 / 255.,
                                      1),
              stroke_color=colors.Color(20 / 255., 20 / 255., 20 / 255., 1),
              fill_color=colors.Color(255 / 255., 255 / 255., 255 / 255.,
                                      0)):
     self.a = a
     self.b = b
     self.size = size
     self.grid_color = grid_color
     self.stroke_color = stroke_color
     self.fill_color = fill_color
Example #10
0
def create_diagram(probe_pset, seg_pset, threshold, outfname, male_reference):
    """Create the diagram."""
    if probe_pset and seg_pset:
        is_seg = False
        do_both = True
    else:
        probe_pset = probe_pset or seg_pset
        if not probe_pset:
            raise ValueError("Must specify a filename as an argument or with "
                             "the '-s' option, or both. You did neither.")
        is_seg = bool(seg_pset)
        do_both = False

    # Consolidate genes & coverage values as chromsomal features
    features = collections.defaultdict(list)
    no_name = ('Background', 'CGH', '-', '.')
    strand = 1 if do_both else None
    probe_rows = core.shift_xx(probe_pset, male_reference)
    if not is_seg:
        probe_rows = probe_rows.squash_genes()
    for row in probe_rows:
        p_chrom, p_start, p_end, p_gene, p_coverage = tuple(row)[:5]
        if ((not is_seg) and (p_gene not in no_name)
                and abs(p_coverage) >= threshold):
            feat_name = p_gene
        else:
            feat_name = None
        features[p_chrom].append(
            (p_start - 1, p_end, strand, feat_name,
             colors.Color(*plots.cvg2rgb(p_coverage, not is_seg))))
    if do_both:
        for chrom, segrows in core.shift_xx(seg_pset,
                                            male_reference).by_chromosome():
            features[chrom].extend(
                (srow['start'] - 1, srow['end'], -1, None,
                 colors.Color(*plots.cvg2rgb(srow['coverage'], False)))
                for srow in segrows)

    # Generate the diagram PDF
    if not outfname:
        outfname = probe_pset.sample_id + '-diagram.pdf'
    chrom_sizes = plots.chromosome_sizes(probe_pset)
    drawing = build_chrom_diagram(features, chrom_sizes, probe_pset.sample_id)
    cvs = canvas.Canvas(outfname, pagesize=PAGE_SIZE)
    renderPDF.draw(drawing, cvs, 0, 0)
    cvs.showPage()
    cvs.save()
    return outfname
    def get_stock_out_table_style(row_len):
        return TableStyle(
            [('SPAN', (0, 0), (7, 0)),  # SCM

             ('LINEBELOW', (0, 0), (7, 0), 0.5,
              colors.Color(0/255, 133/255, 183/255)),
             ('LINEBELOW', (0, 1), (7, 1), 0.5,
              colors.Color(0/255, 133/255, 183/255)),
             ('LINEBELOW', (0, row_len-1), (7, row_len-1), 0.5,
              colors.Color(0/255, 133/255, 183/255)),

             # Entire table
             ('TOPPADDING', (0, 2), (-1, -1), 0.2),
             ('BOTTOMPADDING', (0, 2), (-1, -1), 0.2),
             # ('GRID', (0, 0), (-1, -1), 0.5, colors.Color(91/255, 91/255, 93/255))
             ])
Example #12
0
    def __init__(self,
                 x, y, width, height, cat_names, data,
                 step_count=4, legend_names=None, legend_position="top-right", legend_adjust_x=0, legend_adjust_y=0,
                 main_title="", main_title_font_name=None, main_title_font_size=None, main_title_font_color=None,
                 x_desc=None, y_desc=None, cat_label_angle=30, cat_label_all=False):
        LegendedHorizontalLineChart.__init__(self)

        self.categoryAxis = XCategoryAxisWithDesc(desc=x_desc)
        self.valueAxis = YValueAxisWithDesc(desc=y_desc)

        self.valueAxis.visibleGrid = 1
        self.valueAxis.gridStrokeColor = colors.Color(0.5, 0.5, 0.5, 0.5)
        self.valueAxis.gridStrokeWidth = 1

        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.data = data

        if cat_label_all is False:
            cat_names_num = len(cat_names)
            show_cat_num = 7
            if cat_names_num > show_cat_num:
                gap_num = int(cat_names_num / show_cat_num)
                for i in range(cat_names_num):
                    if i % gap_num != 0:
                        cat_names[i] = ""

        self.categoryAxis.categoryNames = cat_names
        self.categoryAxis.labels.boxAnchor = 'n'

        min_value, max_value, step = self.get_limit_value(step_count)
        self.valueAxis.valueMin = min_value
        self.valueAxis.valueMax = max_value
        self.valueAxis.valueStep = step

        self.joinedLines = 1
        self.lines.strokeWidth = 2

        if legend_names is not None and isListOfStrings(legend_names) is True:
            self.drawLegend = True
            self.legendCategoryNames = legend_names
        self.legendPositionType = legend_position

        self.legendAdjustX = legend_adjust_x
        self.legendAdjustY = legend_adjust_y

        self.titleMain = main_title
        if main_title_font_name is not None:
            self.titleMainFontName = main_title_font_name
        if main_title_font_size is not None:
            self.titleMainFontSize = main_title_font_size
        self.titleMainFontColor = colors.black
        if main_title_font_color is not None:
            self.titleMainFontColor = main_title_font_color

        self.categoryAxis.labels.boxAnchor = 'ne'
        self.categoryAxis.labels.dx = 0
        self.categoryAxis.labels.angle = cat_label_angle
Example #13
0
def get_color(col):
    if isinstance(col, str):
        return colors.getAllNamedColors().get(col)
    elif isinstance(col, list):
        return colors.Color(*[x / 255.0 for x in col])
    else:
        raise Exception("Unknown color defintion type")
Example #14
0
def convertColour(abstractColour):
    if abstractColour is None:
        abstractColour = colours.transparent
    return colors.Color(abstractColour.red / 255.0,
                        abstractColour.green / 255.0,
                        abstractColour.blue / 255.0,
                        alpha = abstractColour.alpha / 255.0)
    def get_dx_hc_table_style(row_len):
        return TableStyle([
            ('SPAN', (0, 0), (3, 0)),  # Malaria diagnosis method used by HCs

            # Title bar
            ('LINEBELOW', (0, 1), (3, 1), 0.5,
             colors.Color(0 / 255, 133 / 255, 183 / 255)),
            # Last line
            ('LINEBELOW', (0, row_len - 1), (3, row_len - 1), 0.5,
             colors.Color(0 / 255, 133 / 255, 183 / 255)),

            # Entire table
            ('TOPPADDING', (0, 2), (-1, -1), 0.2),
            ('BOTTOMPADDING', (0, 2), (-1, -1), 0.2),
            # ('GRID', (0, 0), (-1, -1), 0.5, colors.Color(91/255, 91/255, 93/255))
        ])
Example #16
0
def styles():
    """ Specifies style guidelines for pdf report and column formatting

    @return: dict, style guidelines
    """
    page_height = defaultPageSize[1]
    page_width = defaultPageSize[0]
    squidink = rcolors.Color(red=(35.0 / 255),
                             green=(47.0 / 255),
                             blue=(62.0 / 255))

    columns = {
        'Measure': 'measure_type',
        'User': '******',
        'Service Class': 'service_class',
        'Queue': 'queue',
        'Aborted Count': 'aborted',
        'Query Count': 'query_count',
        'P25(s)': 'p25_s',
        'P50(s)': 'p50_s',
        'P75(s)': 'p75_s',
        'P90(s)': 'p90_s',
        'P95(s)': 'p95_s',
        'P99(s)': 'p99_s',
        'Max(s)': 'max_s',
        'Avg(s)': 'avg_s',
        'Std Dev(s)': 'std_s',
        'Statement Type': 'statement_type',
        'Burst Count': 'count_cs',
        'Total Count': 'total_count'
    }

    # styling definitions for pdf
    table_style = TableStyle([
        ('LINEABOVE', (0, 1), (-1, -1), 0.25, rcolors.black),
        ('LINEBELOW', (0, -1), (-1, -1), .25, rcolors.black),
        ('GRID', (0, 0), (-1, -1), 0.5, rcolors.black),
        ('BACKGROUND', (0, 0), (-1, 0), squidink),
        ('TEXTCOLOR', (0, 0), (-1, 0), rcolors.white),
        ('FONTSIZE', (0, 1), (-1, -1), 9)
    ])
    style = getSampleStyleSheet()
    style['Heading4'].fontName = 'Helvetica-Bold'
    style['Heading4'].spaceAfter = 1
    style['Normal'].spaceAfter = 1.5
    style['Normal'].textSize = 8
    style['Normal'].borderPadding = 4
    style.add(
        ParagraphStyle(name='incomplete',
                       fontFamily='Helvetica',
                       fontSize=10,
                       textColor='red'))

    return {
        'page_height': page_height,
        'page_width': page_width,
        'columns': columns,
        'table_style': table_style,
        'styles': style
    }
Example #17
0
 def setParagraphStyle(self, style, align):
     self.pStyle = ParagraphStyle(style)
     self.pStyle.alignment = align
     self.pStyle.fontSize = self.settings['textStyles'][style][1] * mm
     self.pStyle.fontName = self.settings['textStyles'][style][0]
     self.pStyle.textColor = colors.Color(*(self.settings['textStyles'][style][2]))
     self.pStyle.leading = 1.2 * self.settings['textStyles'][style][1] * mm
Example #18
0
def color_to_reportlab(color):
    """Returns the passed color in Reportlab Color format.

    We allow colors to be specified as hex values, tuples, or Reportlab Color
    objects, and with or without an alpha channel. This function acts as a
    Rosetta stone for conversion of those formats to a Reportlab Color
    object, with alpha value.

    Any other color specification is returned directly
    """
    # Reportlab Color objects are in the format we want already
    if isinstance(color, colors.Color):
        return color
    elif isinstance(color, str):  # String implies hex color
        if color.startswith("0x"):  # Standardise to octothorpe
            color.replace("0x", "#")
        if len(color) == 7:
            return colors.HexColor(color)
        else:
            try:
                return colors.HexColor(color, hasAlpha=True)
            except TypeError:  # Catch pre-2.7 Reportlab
                raise RuntimeError(
                    "Your reportlab seems to be too old, try 2.7 onwards")
    elif isinstance(color, tuple):  # Tuple implies RGB(alpha) tuple
        return colors.Color(*color)
    return color
Example #19
0
def add_banner(pdf_stream, text=None, logo=False, thickness=2 * cm):
    """ Add a banner on a PDF in the upper right corner, with Odoo's logo (optionally).

    :param pdf_stream (BytesIO):    The PDF stream where the banner will be applied.
    :param text (str):              The text to be displayed.
    :param logo (bool):             Whether to display Odoo's logo in the banner.
    :param thickness (float):       The thickness of the banner in pixels.
    :return (BytesIO):              The modified PDF stream.
    """

    old_pdf = PdfFileReader(pdf_stream, strict=False, overwriteWarnings=False)
    packet = io.BytesIO()
    can = canvas.Canvas(packet)
    odoo_logo = Image.open(file_open('base/static/img/main_partner-image.png', mode='rb'))
    odoo_color = colors.Color(113 / 255, 75 / 255, 103 / 255, 0.8)

    for p in range(old_pdf.getNumPages()):
        page = old_pdf.getPage(p)
        width = float(abs(page.mediaBox.getWidth()))
        height = float(abs(page.mediaBox.getHeight()))

        can.translate(width, height)
        can.rotate(-45)

        # Draw banner
        path = can.beginPath()
        path.moveTo(-width, -thickness)
        path.lineTo(-width, -2 * thickness)
        path.lineTo(width, -2 * thickness)
        path.lineTo(width, -thickness)
        can.setFillColor(odoo_color)
        can.drawPath(path, fill=1, stroke=False)

        # Insert text (and logo) inside the banner
        can.setFontSize(10)
        can.setFillColor(colors.white)
        can.drawRightString(0.75 * thickness, -1.45 * thickness, text)
        logo and can.drawImage(
            ImageReader(odoo_logo), 0.25 * thickness, -2.05 * thickness, 40, 40, mask='auto', preserveAspectRatio=True)

        can.showPage()

    can.save()

    # Merge the old pages with the watermark
    watermark_pdf = PdfFileReader(packet, overwriteWarnings=False)
    new_pdf = PdfFileWriter()
    for p in range(old_pdf.getNumPages()):
        new_page = old_pdf.getPage(p)
        # Remove annotations (if any), to prevent errors in PyPDF2
        if '/Annots' in new_page:
            del new_page['/Annots']
        new_page.mergePage(watermark_pdf.getPage(p))
        new_pdf.addPage(new_page)

    # Write the new pdf into a new output stream
    output = io.BytesIO()
    new_pdf.write(output)

    return output
def get_payment_voucher_no_id():
    row = []
    ctr = _total_amount = 0
    _id = db(db.Payment_Voucher_Header.payment_voucher_no == request.args(0)).select().first()
    _row = [['#','Code','Name','Dept.','Type','Ref.No.','Description','Amount']]
    for n in db(db.Payment_Voucher_Transaction.payment_voucher_header_id == _id.id).select():
        ctr += 1
        _ma =  dc(dc.Master_Account.account_code == n.account_debit_code).select().first()
        # _am = dc(dc.Master_Account.account_code == n.account_credit_code).select().first()
        _account_name = 'None'
        if _ma:
            _account_name = _ma.account_name
        _row.append([
            ctr,
            str(n.account_debit_code),
            Paragraph(_account_name, style = _style),
            n.department_code,
            n.transaction_payment_type_id.transaction_payment_type,
            n.account_reference,
            Paragraph(n.description or '',style=_style),
            locale.format('%.2F',n.amount or 0, grouping = True),
            ])
        _row.append(['','',(n.cost_center_category_code) + ': ' + str(n.cost_center_category_id.cost_center_category_name) + ', ' + str(n.cost_center_code)])
        _total_amount += float(n.amount or 0)

    (_whole, _frac) = (int(_total_amount), locale.format('%.2f',_total_amount or 0, grouping = True))
    _amount_in_words = 'QAR ' + string.upper(w.number_to_words(_whole, andword='')) + ' AND ' + str(str(_frac)[-2:]) + '/100 DIRHAMS'

    _row.append(['','','','','','Total Amount (QAR): ','',locale.format('%.2F', _total_amount or 0, grouping = True)])
    _row.append(['AMOUNT IN WORDS: ' + str(_amount_in_words),'','','','','','',''])
    _row_table = Table(_row, colWidths=[20,50,130,40,30,70,130,85])
    _row_table.setStyle(TableStyle([
        # ('GRID',(0,0),(-1,-1),0.5, colors.Color(0, 0, 0, 0.2)),  
        ('FONTNAME', (0, 0), (-1, -1), 'Courier'),
        ('FONTSIZE',(0,0),(-1,-1),10),
        ('FONTSIZE',(0,-1),(-1,-1),9),
        ('ALIGN',(-1,1),(-1,-1),'RIGHT'),
        # ('ALIGN',(6,-1),(-1,-1),'RIGHT'),
        # ('ALIGN',(-2,6),(-2,-6),'RIGHT'),
        ('VALIGN',(0,1),(-1,-3),'TOP'),
        ('FONTNAME', (0, 0), (-1, 0), 'Courier-Bold', 12),
        ('FONTNAME', (6, -2), (-1, -2), 'Courier-Bold', 12),
        ('FONTNAME', (0, -1), (-1, -1), 'Courier-Bold', 12),
        ('TEXTCOLOR',(0,0),(-1,0),colors.white),
        ('BACKGROUND',(0,0),(-1,0), colors.Color(0, 0, 0, 0.4)),
        ('LINEBELOW', (0,0), (-1,0), 0.25,  colors.black,None, (2,2)),
        ('LINEABOVE', (0,-1), (-1,-1), 0.25,  colors.black,None, (2,2)),
        ('LINEBELOW', (0,-1), (-1,-1), 0.25,  colors.black,None, (2,2)),
        ('BOTTOMPADDING',(0,0),(-1,-1),5),
        ('TOPPADDING',(0,0),(-1,-1),5),        
        ('BOX', (0,0), (-1,-3), 0.25, colors.black,None, (2,2)),
    ]))
    row.append(_row_table)
    # doc.build(row)    
    doc.build(row, onFirstPage=get_account_voucher_canvas, onLaterPages = get_account_voucher_canvas, canvasmaker=PageNumCanvas)    

    pdf_data = open(tmpfilename,"rb").read()
    os.unlink(tmpfilename)
    response.headers['Content-Type']='application/pdf'
    return pdf_data
Example #21
0
 def drawOn(self, canvas, x, y):
     """Draws some blocks around the identifier's characters."""
     BaseLTOLabel.drawOn(self, canvas, x, y)
     canvas.saveState()
     canvas.setLineWidth(self.LINEWIDTH)
     canvas.setStrokeColorRGB(0, 0, 0)
     canvas.translate(x, y)
     xblocks = (self.LABELWIDTH - (self.NBBLOCKS * self.BLOCKWIDTH)) / 2.0
     for i in range(self.NBBLOCKS):
         (font, size) = self.LABELFONT
         newfont = self.LABELFONT
         if i == (self.NBBLOCKS - 1):
             part = self.label[i:]
             (font, size) = newfont
             size /= 2.0
             newfont = (font, size)
         else:
             part = self.label[i]
         canvas.saveState()
         canvas.translate(xblocks + (i * self.BLOCKWIDTH), 0)
         if self.colored and part.isdigit():
             canvas.setFillColorRGB(*getattr(colors, self.COLORSCHEME[int(
                 part)], colors.Color(1, 1, 1)).rgb())
         else:
             canvas.setFillColorRGB(1, 1, 1)
         canvas.rect(0, 0, self.BLOCKWIDTH, self.BLOCKHEIGHT, fill=True)
         canvas.translate(
             (self.BLOCKWIDTH + canvas.stringWidth(part, *newfont)) / 2.0,
             (self.BLOCKHEIGHT / 2.0))
         canvas.rotate(90.0)
         canvas.setFont(*newfont)
         canvas.setFillColorRGB(0, 0, 0)
         canvas.drawCentredString(0, 0, part)
         canvas.restoreState()
     canvas.restoreState()
Example #22
0
 def _blast_feature(self, f, c1, c2, features1, features2, evalue,
                    max_rlen):
     trans = Translator(self._abort_event)
     cds = trans.translate(f.extract(c1), 11)
     sixframes = trans.translate_six_frames_single(c2, 11)
     if not sixframes: return [(None, None, None)]
     results = []
     for frame in sixframes:
         res = BlastCLI.s2s_blast(cds,
                                  frame,
                                  evalue,
                                  command='blastp',
                                  task='blastp')
         if res: results.extend(res)
     hsps = BlastCLI.all_hsps(results, max_rlen)
     if not hsps: return [(None, None, None)]
     f1 = []
     f2 = []
     col = []
     c1_name = pretty_rec_name(c1)
     if 'locus_tag' in f.qualifiers:
         fname = f.qualifiers['locus_tag'][0]
     else:
         fname = 'CDS'
     cds_len = len(cds)
     for hsp in hsps:
         color_t = (float(hsp.identities) / hsp.align_length)
         print '%s %s: %5.1f%% (%5.1f%%)' % (c1_name, fname, color_t * 100,
                                             float(hsp.identities) /
                                             cds_len * 100)
         col.append(
             colors.linearlyInterpolatedColor(colors.Color(0, 0, 1, 0.2),
                                              colors.Color(0, 1, 0, 0.2),
                                              0.2, 1, color_t))
         qstart = (hsp.query_start - 1) * 3
         qend = qstart + hsp.align_length * 3
         sstart = (hsp.sbjct_start - 1) * 3
         send = sstart + hsp.align_length * 3
         f1.append(
             SeqFeature(
                 FeatureLocation(f.location.start + qstart,
                                 f.location.start + qend,
                                 strand=hsp.strand[0])))
         f2.append(
             SeqFeature(FeatureLocation(sstart, send,
                                        strand=hsp.strand[1])))
     return zip(f1, f2, col)
Example #23
0
 def add_factors(self, can, x, y, w, h, base):
     fill_color = colors.Color(21 / 255., 21 / 255., 21 / 255., .7)
     can.setFillColor(fill_color)
     can.setFont("Times-Roman", 8)
     s = '%s' % PrimeFactors(x * y, base)
     if len(s) == 1: s = ''
     textWidth = stringWidth(s, fontName="Times-Roman", fontSize=8)
     can.drawString(w - textWidth + self.dx - 1, -h - self.dy, s)  # right
Example #24
0
def renderGerber(path, layer, canv):
    global gerberExtents
    if (layer == "bottom"):
        f_copper = findFileInDir(path, ".GBL")
        f_overlay = findFileInDir(path, ".GBO")
    else:
        f_copper = findFileInDir(path, ".GTL")
        f_overlay = findFileInDir(path, ".GTO")

    canv.setLineWidth(0.0)
    gm = GerberMachine("", canv)
    gm.Initialize()
    ResetExtents()
    gm.setColors(colors.Color(0.85, 0.85, 0.85), colors.Color(0, 0, 0))
    gm.ProcessFile(f_copper)
    gm.setColors(colors.Color(0.5, 0.5, 0.5), colors.Color(0, 0, 0))
    return gm.ProcessFile(f_overlay)
Example #25
0
    def test_0(self):
        "Test color attribute conversion."

        mapping = (
            ("red", colors.red),
            ("#ff0000", colors.red),
            ("#f00", colors.red),
            ("rgb(100%,0.5%,0.5%)", colors.Color(1, 0.005, 0.005, 1)),
            ("rgb(255, 0, 0)", colors.red),
            ("fuchsia", colors.Color(1, 0, 1, 1)),
            ("slategrey", colors.HexColor(0x708090)),
            ("transparent", colors.Color(0, 0, 0, 0)),
            ("whatever", None),
        )
        ac = svglib.Svg2RlgAttributeConverter()
        failed = _testit(ac.convertColor, mapping)
        assert len(failed) == 0
def create_table_pdf(json_data):
    doc = SimpleDocTemplate("json2pdf_example.pdf", pagesize=A4)
    style_sheet = getSampleStyleSheet()
    # container for the 'Flowable' objects
    elements = []
    # Get headers for table
    t_data = []
    table_headers = sorted(json_data[0].keys())
    t_data.append(table_headers)
    # set table style
    style = [('BACKGROUND', (0, 0), (len(table_headers), 0),
              colors.Color(0.99, 0.84, 0.59)),
             ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
             ('ALIGN', (1, 1), (-2, -2), 'CENTER'),
             ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
             ('LINEABOVE', (0, 0), (-1, -1), 0.05, colors.black),
             ('LINEBELOW', (0, 1), (-1, -1), 0.05, colors.black)]

    for row in range(len(json_data)):
        tmp_row = []
        if row % 2 == 0:
            for header in table_headers:
                value = json_data[row].get(header)
                p = Paragraph('<b><font color=black>%s</font></b>' % value,
                              style_sheet["BodyText"],
                              encoding='utf8')
                tmp_row.append(p)
        else:
            tmp_row = []
            for header in table_headers:
                value = json_data[row].get(header)
                p = Paragraph('<b><font color=black>%s</font></b>' % value,
                              style_sheet["BodyText"],
                              encoding='utf8')
                style.append(
                    ('BACKGROUND', (0, row), (len(table_headers), row),
                     colors.Color(0.97, 0.99, 0.99)))
                tmp_row.append(p)
        t_data.append(tmp_row)

    t = Table(t_data, style=style)
    # t._argW[len(data)] = 1.5 * cm

    elements.append(t)
    # write the document to disk
    doc.build(elements)
Example #27
0
    def _test0(self):
        "Create color ranges."

        c0, c1 = colors.Color(0, 0, 0), colors.Color(1, 1, 1)
        for c in colorRange(c0, c1, 4):
            print c
        print

        c0, c1 = colors.CMYKColor(0, 0, 0, 0), colors.CMYKColor(0, 0, 0, 1)
        for c in colorRange(c0, c1, 4):
            print c
        print

        c0, c1 = colors.PCMYKColor(0, 0, 0, 0), colors.PCMYKColor(0, 0, 0, 100)
        for c in colorRange(c0, c1, 4):
            print c
        print
Example #28
0
 def _generate_gene_colors(self):
     if not self.clusters: return
     full_gene_set = set()
     for c in self.clusters:
         full_gene_set.update(c.genes)
     if 'NONE' in full_gene_set:
         full_gene_set.remove('NONE')
     ngenes = float(len(full_gene_set))-1
     middle = ngenes/2.0
     self.colors = {}
     for i, gene in enumerate(sorted(full_gene_set)):
         t = i/ngenes
         if i < middle:
             c = colors.linearlyInterpolatedColor(colors.Color(1, 0, 0, 1), colors.Color(0, 1, 0, 1), 0, 1, t*2)
         else:
             c = colors.linearlyInterpolatedColor(colors.Color(0, 0.9, 0.1, 1), colors.Color(0, 0, 1, 1), 0, 1, t*2-1)
         self.colors[gene] = c
Example #29
0
def renderGerber(base_name, layer, canv):
    global gerberExtents
    if (layer == "Bottom"):
        f_copper = base_name + ".GBL"
        f_overlay = base_name + ".GBO"
    else:
        f_copper = base_name + ".GTL"
        f_overlay = base_name + ".GTO"

    canv.setLineWidth(0.0)
    gm = GerberMachine("", canv)
    gm.Initialize()
    ResetExtents()
    gm.setColors(colors.Color(0.85, 0.85, 0.85), colors.Color(0, 0, 0))
    gm.ProcessFile(f_copper)
    gm.setColors(colors.Color(0.5, 0.5, 0.5), colors.Color(0, 0, 0))
    return gm.ProcessFile(f_overlay)
 def create_colors(self, num_of_colors):
     """Generates and returns an array of colors"""
     cols = []
     for i in range(num_of_colors):
         r = random.uniform(0, 1)
         g = random.uniform(0, 1)
         b = random.uniform(0, 1)
         cols.append(colors.Color(red=r, green=g, blue=b))
     return cols