Beispiel #1
0
    def _draw_textarea(self, canvas: Canvas, op: OrderPosition, order: Order, o: dict):
        font = o['fontfamily']
        if o['bold']:
            font += ' B'
        if o['italic']:
            font += ' I'

        align_map = {
            'left': TA_LEFT,
            'center': TA_CENTER,
            'right': TA_RIGHT
        }
        style = ParagraphStyle(
            name=uuid.uuid4().hex,
            fontName=font,
            fontSize=float(o['fontsize']),
            leading=float(o['fontsize']),
            autoLeading="max",
            textColor=Color(o['color'][0] / 255, o['color'][1] / 255, o['color'][2] / 255),
            alignment=align_map[o['align']]
        )
        text = re.sub(
            "<br[^>]*>", "<br/>",
            bleach.clean(
                self._get_text_content(op, order, o) or "",
                tags=["br"], attributes={}, styles=[], strip=True
            )
        )
        p = Paragraph(text, style=style)
        p.wrapOn(canvas, float(o['width']) * mm, 1000 * mm)
        # p_size = p.wrap(float(o['width']) * mm, 1000 * mm)
        ad = getAscentDescent(font, float(o['fontsize']))
        p.drawOn(canvas, float(o['left']) * mm, float(o['bottom']) * mm - ad[1])
Beispiel #2
0
 def draw(self):
     sx = 0.5
     fillColor = self.fillColor
     strokeColor = self.strokeColor
     shadow = Color(fillColor.red * sx, fillColor.green * sx,
                    fillColor.blue * sx)
     g = Group()
     g2 = Group()
     g.add(
         Rect(fillColor=fillColor,
              strokeColor=fillColor,
              x=0,
              y=0,
              width=self._w,
              height=self._h))
     sx = (self._w - 2) / self._sw()
     g2.scale(sx, 1)
     self._addPage(g2, strokeWidth=3, dx=2, dy=-2.5, color=shadow)
     self._addPage(g2, strokeWidth=3, color=strokeColor)
     g2.scale(1 / sx, 1)
     g2.add(self._getText(x=1, y=0, color=shadow))
     g2.add(self._getText(x=0, y=1, color=strokeColor))
     g2.scale(sx, 1)
     g2.skew(kx=10, ky=0)
     g2.shift(0, 38)
     g.add(g2)
     g.scale(self.width / self._w, self.height / self._h)
     g.shift(self.x, self.y)
     return g
def _colour_no_print_areas_of_page_in_red(page, is_first_page):
    """
    Overlays the non-printable areas onto a single page. It adds red areas (if `is_first_page` is set, then it'll add
    red areas around the address window too) and returns a new page object that you can then merge .

    :param PageObject page: A page, as returned by PdfFileReader.getPage. Note: This is modified by this function.
    :param bool is_first_page: true if we should overlay the address block red area too.
    :return: None. It modifies the page object instead
    """
    red_transparent = Color(100, 0, 0, alpha=0.2)

    # Overlay the areas where the service can't print as per the template
    can = NotifyCanvas(red_transparent)

    # Each page of content
    # left margin:
    pt1 = 0, 0
    pt2 = BORDER_LEFT_FROM_LEFT_OF_PAGE, A4_HEIGHT
    can.rect(pt1, pt2)
    # top margin:
    pt1 = BORDER_LEFT_FROM_LEFT_OF_PAGE, 0
    pt2 = BORDER_RIGHT_FROM_LEFT_OF_PAGE, BORDER_TOP_FROM_TOP_OF_PAGE
    can.rect(pt1, pt2)
    # right margin:
    pt1 = BORDER_RIGHT_FROM_LEFT_OF_PAGE, 0
    pt2 = A4_WIDTH, A4_HEIGHT
    can.rect(pt1, pt2)
    # bottom margin:
    pt1 = BORDER_LEFT_FROM_LEFT_OF_PAGE, BORDER_BOTTOM_FROM_TOP_OF_PAGE
    pt2 = BORDER_RIGHT_FROM_LEFT_OF_PAGE, A4_HEIGHT
    can.rect(pt1, pt2)

    # The first page is more varied because of address blocks etc subsequent pages are more simple
    if is_first_page:
        # left from address block (from logo area all the way to body)
        pt1 = BORDER_LEFT_FROM_LEFT_OF_PAGE, LOGO_BOTTOM_FROM_TOP_OF_PAGE
        pt2 = ADDRESS_LEFT_FROM_LEFT_OF_PAGE, BODY_TOP_FROM_TOP_OF_PAGE
        can.rect(pt1, pt2)

        # directly above address block
        pt1 = ADDRESS_LEFT_FROM_LEFT_OF_PAGE, LOGO_BOTTOM_FROM_TOP_OF_PAGE
        pt2 = ADDRESS_RIGHT_FROM_LEFT_OF_PAGE, ADDRESS_TOP_FROM_TOP_OF_PAGE
        can.rect(pt1, pt2)

        # right from address block (from logo area all the way to body)
        pt1 = ADDRESS_RIGHT_FROM_LEFT_OF_PAGE, LOGO_BOTTOM_FROM_TOP_OF_PAGE
        pt2 = SERVICE_ADDRESS_LEFT_FROM_LEFT_OF_PAGE, BODY_TOP_FROM_TOP_OF_PAGE
        can.rect(pt1, pt2)

        # below address block
        pt1 = ADDRESS_LEFT_FROM_LEFT_OF_PAGE, ADDRESS_BOTTOM_FROM_TOP_OF_PAGE
        pt2 = ADDRESS_RIGHT_FROM_LEFT_OF_PAGE, BODY_TOP_FROM_TOP_OF_PAGE
        can.rect(pt1, pt2)

    # move to the beginning of the StringIO buffer
    new_pdf = PdfFileReader(can.get_bytes())

    # note that the original page object is modified. I don't know if the original underlying src_pdf buffer is affected
    # but i assume not.
    page.mergePage(new_pdf.getPage(0))
Beispiel #4
0
class Style(dict):
    """
    Style.

    Single place for style definitions: Paragraphs and Fragments. The
    naming follows the convention of CSS written in camelCase letters.
    """

    DEFAULT = {
        "textAlign": TA_LEFT,
        "textIndent": 0.0,
        "width": None,
        "height": None,
        "fontName": "Times-Roman",
        "fontSize": 10.0,
        "color": Color(0, 0, 0),
        "lineHeight": 1.5,
        "lineHeightAbsolute": None,
        "pdfLineSpacing": 0,
        "link": None,
    }

    def __init__(self, **kw):
        self.update(self.DEFAULT)
        self.update(kw)
        self.spaceBefore = 0
        self.spaceAfter = 0
        self.keepWithNext = False
Beispiel #5
0
def report_table(data):
    report_table_data = [
        ("Question\nNo.", "Time spent \n on question \n (sec)",
         'Score if\n correct', 'Score if\n incorrect', 'Attempt '
         '\nStatus', 'What you \nmarked', 'Correct \nAnswer',
         'Outcome \n(Correct\n/Incorrect/\nNot Attempted)', 'Your \nScore'),
    ]
    for row in data:
        report_table_data.append(
            (f'{row[0]}', f'{row[1]}', f'{row[2]}', f'{row[3]}', f'{row[4]}',
             f'{row[5]}', f'{row[6]}', f'{row[7]}', f'{row[8]}'))
    report_table_style = (('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                          ('TEXTCOLOR', (0, 0), (-1, 0), (1, 1, 1)),
                          ('ROWBACKGROUNDS', (0, 0), (-1, -1),
                           (Color(0.33, 0.75, 0.80, 1), Color(1, 1, 1, 0))))
    return Table(report_table_data, style=report_table_style)
Beispiel #6
0
    def drawHorizontalGrid(self):
        from reportlab.lib.colors import Color
        self.c.setStrokeColor(Color(0.7, 0.4, 1, alpha=0.4))
        self.c.setFillColor(Color(0.7, 0.4, 1, alpha=0.4))
        self.c.setLineWidth(0.4)
        self.c.setFont("Helvetica", 2.5 * fontscale)
        date = ephem.localtime(self.observer.date).strftime('%d-%m-%Y %H:%M')
        #zenit
        ra, dec = self.observer.radec_of(0, '90')
        x, y = self.p(ra * 180 / pi, dec * 180 / pi)
        self.c.circle(x, y, 5, stroke=1, fill=0)
        self.c.circle(x, y, 2, stroke=1, fill=0)
        self.c.drawString(x, y, 'ZENIT' + date)

        #North
        ra, dec = self.observer.radec_of('0', '20')
        x, y = self.p(ra * 180 / pi, dec * 180 / pi)
        self.c.circle(x, y, 2, stroke=1, fill=0)
        self.c.drawString(x, y, 'N' + date)

        #Sud
        ra, dec = self.observer.radec_of('180', '20')
        x, y = self.p(ra * 180 / pi, dec * 180 / pi)
        self.c.circle(x, y, 2, stroke=1, fill=0)
        self.c.drawString(x, y, 'S' + date)

        #EAST
        ra, dec = self.observer.radec_of('90', '20')
        x, y = self.p(ra * 180 / pi, dec * 180 / pi)
        self.c.circle(x, y, 2, stroke=1, fill=0)
        self.c.drawString(x, y, 'E' + date)

        #WEST
        ra, dec = self.observer.radec_of('270', '20')
        x, y = self.p(ra * 180 / pi, dec * 180 / pi)
        self.c.circle(x, y, 2, stroke=1, fill=0)
        self.c.drawString(x, y, '0' + date)

        #horizon
        for k in (0, 20):
            ra, dec = self.observer.radec_of(1, str(k))
            x, y = self.p(ra * 180 / pi, dec * 180 / pi)
            self.c.drawString(x, y, 'Horizonte:' + str(k) + ' º' + date)
            for i in range(0, 360):
                ra, dec = self.observer.radec_of(str(i), str(k))
                x, y = self.p(ra * 180 / pi, dec * 180 / pi)
                self.c.circle(x, y, 0.4, stroke=1, fill=0)
Beispiel #7
0
 def __init__(self, width=400, height=200, *args, **kw):
     Drawing.__init__(self, width, height, *args, **kw)
     # Width and height of chart.
     self.width = 772
     self.height = 280
     # Add title.
     self._add(self, Label(), name='title', validate=None, desc=None)
     self.title._text = 'Simple Line Chart'
     self.title.fontSize = 24
     self.title.fontName = "Calibri"
     # Position Title.
     self.title.x = 386
     self.title.y = 220
     # Add Line chart to the Drawing.
     self._add(self,
               SimpleTimeSeriesPlot(),
               name='chart',
               validate=None,
               desc=None)
     # Line Chart Position.
     self.chart.x = 150
     self.chart.y = 20
     # Line Chart Dimensions.
     self.chart.width = 400
     self.chart.height = 150
     # Color the lines.
     self.chart.lines[0].strokeColor = Color(.19, .49, 1, 1)
     self.chart.lines[1].strokeColor = Color(.2, .199, .199, 1)
     # Line thickness
     self.chart.lines.strokeWidth = 1.5
     # Format Labels on X-Axis
     self.chart.xValueAxis.xLabelFormat = '{dd}/{mm}/{yy}'
     # Grid Lines Visible on Graph.
     self.chart.yValueAxis.visibleGrid = 1
     # Format labels on Y-Axis
     self.chart.yValueAxis.labelTextFormat = '%.1f%%'
     # Avoid assuming lowest value as origin
     self.chart.yValueAxis.avoidBoundSpace = (10, 0)
     # Add legends to the graph
     self._add(self, Legend(), name='legend', validate=None, desc=None)
     # Initialize Color vs Desc text
     self.legend.colorNamePairs = [(Color(.19, .49, 1, 1), 'Data1'),
                                   (Color(.2, .199, .199, 1), 'Data2')]
     # Position Legend
     self.legend.x = 600
     self.legend.y = 100
Beispiel #8
0
    def createPDF(id, forename, surname, category):
        #Creating file
        canvas = Canvas(f"reconocimiento-{id}.pdf", pagesize=letter)
        width, height = letter

        #Background image and rectangle for information
        bg_im = ImageReader("assets/bg_image.jpg")
        logo = ImageReader("assets/logo.png")
        canvas.drawImage(image=bg_im, x=0, y=0, width=width, height=height)
        canvas.drawImage(image=logo,
                         x=inch / 2,
                         y=height - 1.5 * inch,
                         width=inch,
                         height=inch)
        gray50transparent = Color(160, 160, 160, alpha=0.75)
        canvas.setFillColor(gray50transparent)
        canvas.rect(0.5 * inch,
                    2 * inch,
                    width - inch,
                    height - 4 * inch,
                    fill=True,
                    stroke=False)

        #Text
        canvas.setFont('Helvetica', 20)
        canvas.setFillColor(Color(0, 0, 0, alpha=1))  #Black

        canvas.drawCentredString(width / 2, 8 * inch,
                                 "Torneo de Programación Competitiva")
        canvas.drawCentredString(width / 2, 7.5 * inch,
                                 "Copa Guadalajara 2021")
        canvas.drawCentredString(width / 2, 6 * inch,
                                 "Se otorga el reconocimiento a:")
        canvas.setFont('Helvetica-Bold', 20)
        canvas.drawCentredString(width / 2, 5.5 * inch,
                                 f'{forename} {surname}')
        canvas.setFont('Helvetica', 20)
        canvas.drawCentredString(
            width / 2, 4 * inch,
            f"Por su participación en la categoría {category}")
        canvas.drawCentredString(width / 2, 3.5 * inch,
                                 'en la copa de programación competitiva')
        canvas.drawCentredString(width / 2, 3 * inch, 'Guadalajara 2021.')

        #Closing file
        canvas.save()
Beispiel #9
0
 def Mark(self, c, x, y):
     print x, y
     c.saveState()
     c.setStrokeColor(Color(1, 0., 0., alpha=0.8))
     c.setFillColor(Color(1, 0.0, 0.0, alpha=0.01))
     c.setLineWidth(0.05)
     c.setFont("Helvetica", 2.5 * fontscale)
     c.translate(x, y)
     c.scale(4, 4)
     c.circle(0, 0, r=1, stroke=1, fill=1)
     p = c.beginPath()
     p.moveTo(0, 1)
     p.lineTo(0, -1)
     p.moveTo(1, 0)
     p.lineTo(-1, 0)
     c.drawPath(p, stroke=1, fill=0)
     c.restoreState()
Beispiel #10
0
def _create_whitemark(width: int, height: int, alpha: float):
    PATH = '.watermark.pdf'
    c = canvas.Canvas(PATH)
    c.setFillColor(Color(255, 255, 255, alpha=alpha))
    c.rect(0, 0, width, height, fill=True, stroke=False)
    c.save()
    whitemark = PdfFileReader(PATH).getPage(0)
    os.remove(PATH)
    return whitemark
Beispiel #11
0
 def draw_line_simple(self, c):
     strc = self.linex
     if self.islight:
         strc = self.linex * self.contrast + ProjectedShape.write * (
             1 - self.contrast)
     c.setStrokeColor(Color(*list(strc / 255.0)))
     c.setLineWidth(0.3)
     c.setLineCap(1)
     c.line(*(list(self.coords[0, :2]) + list(self.coords[1, :2])))
Beispiel #12
0
 def drawMarks(self, fichero):
     self.c.setFont("Helvetica", 2.5 * fontscale)
     self.c.setFillColor(Color(1, 0.0, 0.0, alpha=0.4))
     se = sesame.sesame()
     se.fromFile(fichero)
     for o in se.obj_data:
         x, y = self.p(o[1], o[2])
         self.brocha.Mark(self.c, x, y)
         self.c.drawString(x + 1, y - 8, o[0])
Beispiel #13
0
 def __init__(self, width=400, height=200, *args, **kw):
     Drawing.__init__(self, width, height, *args, **kw)
     self.transform = (1, 0, 0, 1, 0, 0)
     self.add(
         String(34,
                34,
                'Hello World',
                textAnchor='start',
                fontName='Times-Roman',
                fontSize=12,
                fillColor=Color(0, 0, 0, 1)))
     self.add(
         String(42,
                42,
                'Hello World',
                textAnchor='start',
                fontName='Times-Roman',
                fontSize=16,
                fillColor=Color(0, 0, 0, 1)))
     self.add(
         String(50,
                50,
                'Hello World',
                textAnchor='start',
                fontName='Times-Roman',
                fontSize=20,
                fillColor=Color(0, 0, 0, 1)))
     self.add(
         String(58,
                58,
                'Hello World',
                textAnchor='start',
                fontName='Times-Roman',
                fontSize=24,
                fillColor=Color(0, 0, 0, 1)))
     self.add(
         String(66,
                66,
                'Hello World',
                textAnchor='start',
                fontName='Times-Roman',
                fontSize=28,
                fillColor=Color(0, 0, 0, 1)))
     self.add(
         String(74,
                74,
                'Hello World',
                textAnchor='start',
                fontName='Times-Roman',
                fontSize=32,
                fillColor=Color(0, 0, 0, 1)))
     self.add(
         String(150,
                150,
                'Hello World',
                textAnchor='start',
                fontName='Vera',
                fontSize=36,
                fillColor=Color(0, 0, 0, 1)))
Beispiel #14
0
    def performer_color(self):
        """Returns the equivalent reportlab Color object from the artist color."""

        import struct
        from reportlab.lib.colors import Color

        rgb = struct.unpack('4B', struct.pack('>I',
                                              self.song.performer.color))[1:]
        pdf = [k / 255.0 for k in rgb] + [1.0]
        return Color(*pdf)
Beispiel #15
0
 def drawCostellationsLimits(self):
     from reportlab.lib.colors import Color
     self.c.setStrokeColor(Color(0.2, 0.2, 0.4, alpha=0.2))
     self.c.setLineWidth(0.2)
     bounds = catalogues.CostellationBounds()
     costellations = set(map(lambda x: x[2], bounds))
     for costellation in costellations:
         l = filter(lambda x: x[2] == costellation, bounds)
         l = map(lambda x: [x[0], x[1]], l)
         self.drawLine(l)
Beispiel #16
0
 def _drawBorderLine(bstyle, width, color, x1, y1, x2, y2):
     # We need width and border style to be able to draw a border
     if width and bstyle:
         # If no color for border is given, the text color is used (like defined by W3C)
         if color is None:
             color = self.get("textColor", Color(0, 0, 0))
         if color is not None:
             canvas.setStrokeColor(color)
             canvas.setLineWidth(width)
             canvas.line(x1, y1, x2, y2)
Beispiel #17
0
def build_inner_table(sections, on_left, padding, width):
    if not sections:
        return None

    data = [[s.as_flow(on_left, width)] for s in sections]
    style_commands = [('VALIGN', (0, 0), (-1, -1), 'TOP'),
                      ('LEFTPADDING', (0, 0), (-1, -1), 0),
                      ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                      ('TOPPADDING', (0, 0), (-1, -1), 0),
                      ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                      ('TOPPADDING', (0, 1), (-1, -1), padding)]

    if DEBUG:
        style_commands.append(
            ('BACKGROUND', (0, 0), (-1, -1), Color(0.5, 0.5, 0, 0.1)))
        style_commands.append(
            ('GRID', (0, 0), (-1, -1), 1, Color(0.5, 0.5, 0, 0.5)))

    return make_table(data, style_commands, colWidths=None)
Beispiel #18
0
    def _draw_textarea(self, canvas: Canvas, op: OrderPosition, order: Order,
                       o: dict):
        font = o['fontfamily']
        if o['bold']:
            font += ' B'
        if o['italic']:
            font += ' I'

        align_map = {'left': TA_LEFT, 'center': TA_CENTER, 'right': TA_RIGHT}
        style = ParagraphStyle(name=uuid.uuid4().hex,
                               fontName=font,
                               fontSize=float(o['fontsize']),
                               leading=float(o['fontsize']),
                               autoLeading="max",
                               textColor=Color(o['color'][0] / 255,
                                               o['color'][1] / 255,
                                               o['color'][2] / 255),
                               alignment=align_map[o['align']])
        text = conditional_escape(
            self._get_text_content(op, order, o)
            or "", ).replace("\n", "<br/>\n")

        # reportlab does not support RTL, ligature-heavy scripts like Arabic. Therefore, we use ArabicReshaper
        # to resolve all ligatures and python-bidi to switch RTL texts.
        configuration = {
            'delete_harakat': True,
            'support_ligatures': False,
        }
        reshaper = ArabicReshaper(configuration=configuration)
        try:
            text = "<br/>".join(
                get_display(reshaper.reshape(l)) for l in text.split("<br/>"))
        except:
            logger.exception('Reshaping/Bidi fixes failed on string {}'.format(
                repr(text)))

        p = Paragraph(text, style=style)
        w, h = p.wrapOn(canvas, float(o['width']) * mm, 1000 * mm)
        # p_size = p.wrap(float(o['width']) * mm, 1000 * mm)
        ad = getAscentDescent(font, float(o['fontsize']))
        canvas.saveState()
        # The ascent/descent offsets here are not really proven to be correct, they're just empirical values to get
        # reportlab render similarly to browser canvas.
        if o.get('downward', False):
            canvas.translate(float(o['left']) * mm, float(o['bottom']) * mm)
            canvas.rotate(o.get('rotation', 0) * -1)
            p.drawOn(canvas, 0, -h - ad[1] / 2)
        else:
            canvas.translate(
                float(o['left']) * mm,
                float(o['bottom']) * mm + h)
            canvas.rotate(o.get('rotation', 0) * -1)
            p.drawOn(canvas, 0, -h - ad[1])
        canvas.restoreState()
Beispiel #19
0
def _render_quote_items(c, height, quote):
    data = [['Description', 'PU HT', 'Quantité', 'Total HT', 'TVA']]
    for item in quote.quoteitem_set.all():
        row = [Paragraph(item.description, styles['Normal']), str(item.unit_price), str(item.quantity), str(item.total_price), "0,00%"]
        data.append(row)

    header_style = TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), Color(60/255,61/255,58/255)),
        ('TEXTCOLOR', (0, 0), (-1, 0), white),
        ('LINEBELOW', (0, 0), (-1, -1), 0.1, Color(173/255,173/255,173/255)),
        ('TOPPADDING', (0, 0), (-1, -1), 10),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
        ('VALIGN', (1, 1), (-1, -1), 'TOP'),
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT')
    ])
    width, height = letter
    t = Table(data, colWidths = (105*mm, 20*mm, 20*mm, 20*mm, 20*mm))
    t.setStyle(header_style)
    t.wrapOn(c, width, height)
    t.drawOn(c, 45, height - 380)
Beispiel #20
0
    def print_atenciones(self):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=inch / 4,
                                leftMargin=inch / 4,
                                topMargin=80,
                                bottomMargin=inch / 4,
                                pagesize=self.pagesize)
        elements = []
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))
        separador = Table([''], colWidths=[doc.width])
        separador.setStyle(
            TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                        ('TOPPADDING', (0, 0), (-1, -1), 0)]))
        table_style = [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOTTOMPADDING', (0, 0), (-1, -1), 0.025),
                       ('TOPPADDING', (0, 0), (-1, -1), 0.025)]

        # TABLE INFORMACION ATENCIONES
        data_table = [[
            getParagraphText('TIPO', 10, 'center', True),
            getParagraphText('DNI', 10, 'center', True),
            getParagraphText('FECHA', 10, 'center', True),
            getParagraphText('HORA INICIO', 10, 'center', True),
            getParagraphText('HORA FIN', 10, 'center', True)
        ]]
        for atencion in self.atenciones:
            data_table.append([
                getParagraphText(to_lower(atencion.tipo.descripcion), 10,
                                 'center', False),
                getParagraphText(to_lower(atencion.dni), 10, 'center', False),
                getParagraphText(str(atencion.fecha), 10, 'center', False),
                getParagraphText(str(atencion.hora_inicio), 10, 'center',
                                 False),
                getParagraphText(str(atencion.hora_fin), 10, 'center', False)
            ])
        table_style_with_background = table_style[:]
        table_style_with_background.append(
            ('BACKGROUND', (0, 0), (4, 0), Color(0, 0, 0, alpha=0.1)))
        content_table = Table(data_table, colWidths=[doc.width / 5.0] * 5)
        content_table.setStyle(TableStyle(table_style_with_background))
        elements.append(content_table)

        doc.build(elements,
                  onFirstPage=self._header_footer,
                  onLaterPages=self._header_footer,
                  canvasmaker=NumberedCanvas)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
Beispiel #21
0
    def addTextFooter(self, str=None):
        if str is None:
            str = self.description()

        self.drawing.add(
            String(self.margins[0],
                   self.margins[1] / 2,
                   str,
                   fontName=self.fontName,
                   fontSize=self.fontSize,
                   fillColor=Color(0.6, 0.6, 0.6)))
Beispiel #22
0
def rl_colour_hex(hexstr, alpha=1.0):
    if len(hexstr) < 6:
        return 0, 0, 0
    hs = hexstr.lstrip("#")
    if not all(c in string.hexdigits for c in hs):
        return 0, 0, 0
    [rd, gd, bd] = tuple(int(hs[i:i + 2], 16) for i in (0, 2, 4))
    r = float(rd) / 255.0
    g = float(gd) / 255.0
    b = float(bd) / 255.0
    return Color(r, g, b, alpha=alpha)
Beispiel #23
0
 def _draw_border(cv, x, y, width, height, color, stroke_width=1):
     d = Drawing(width, height)
     r = Rect(0,
              0,
              width,
              height,
              strokeWidth=stroke_width,
              strokeColor=color,
              fillColor=Color(0, 0, 0, 0))
     d.add(r)
     d.drawOn(cv, x, y)
Beispiel #24
0
def build_outer_table(top_flow, middle_flow, bottom_flow, padding, colWidths):
    data = []
    style_commands = [
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('LEFTPADDING', (0, 0), (-1, -1), 0),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
        ('LEFTPADDING', (1, 0), (-1, -1), padding),
        ('TOPPADDING', (0, 1), (-1, -1), padding),
    ]

    cols = max(1, len(middle_flow))
    row = 0

    # Add top section, ensuring span is good
    if top_flow:
        data.append([top_flow])
        if cols > 1:
            style_commands.append(('SPAN', (0, row), (-1, row)))
        row += 1

    # Add center sections
    if middle_flow:
        data.append(middle_flow)
        row += 1

    # Add bottom section, ensuring span is good
    if bottom_flow:
        data.append([bottom_flow])
        if cols > 1:
            style_commands.append(('SPAN', (0, row), (-1, row)))
        row += 1

    if DEBUG:
        style_commands.append(
            ('BACKGROUND', (0, 0), (-1, -1), Color(0, 0, 1, 0.1)))
        style_commands.append(
            ('GRID', (0, 0), (-1, -1), 1, Color(0, 0, 1, 0.25)))

    return make_table(data, style_commands, colWidths)
Beispiel #25
0
    def draw(self):
        fillColor = self.fillColor
        strokeColor = self.strokeColor
        g = Group()
        bg = self.background
        bd = self.border
        bdw = self.borderWidth
        shadow = self.shadow
        x, y = self.x, self.y
        if bg:
            if shadow is not None and 0 <= shadow < 1:
                shadow = Color(bg.red * shadow, bg.green * shadow,
                               bg.blue * shadow)
            self._paintLogo(g, dy=-2.5, dx=2, fillColor=shadow)
        self._paintLogo(g,
                        fillColor=fillColor,
                        strokeColor=strokeColor,
                        _ocolors=getattr(self, '_ocolors', None),
                        _pagecolors=getattr(self, '_pagecolors', None))
        g.skew(kx=self.skewX, ky=self.skewY)
        g.shift(self._dx, self._dy)
        G = Group()
        G.add(g)
        _w, _h = 130, 86
        w, h = self.width, self.height
        if bg or (bd and bdw):
            G.insert(
                0,
                Rect(0,
                     0,
                     _w,
                     _h,
                     fillColor=bg,
                     strokeColor=bd,
                     strokeWidth=bdw))
        if w != _w or h != _h: G.scale(w / float(_w), h / float(_h))

        angle = self.angle
        if self.angle:
            w, h = w / 2., h / 2.
            G.shift(-w, -h)
            G.rotate(angle)
            G.shift(w, h)
        xFlip = getattr(self, 'xFlip', 0) and -1 or 0
        yFlip = getattr(self, 'yFlip', 0) and -1 or 0
        if xFlip or yFlip:
            sx = xFlip or 1
            sy = yFlip or 1
            G.shift(sx * x + w * xFlip, sy * y + yFlip * h)
            G = Group(G, transform=(sx, 0, 0, sy, 0, 0))
        else:
            G.shift(x, y)
        return G
Beispiel #26
0
    def __init__(self, boards):
        self.boards = boards

        self.header_style = ParagraphStyle(
            fontName=DEFAULT_FONT,
            fontSize=12,
            name='header',
            spaceAfter=10,
            borderColor=Color(0, 0, 0, 1),
            borderPadding=3,
            borderWidth=1,
        )

        self.body_style = ParagraphStyle(
            fontName=DEFAULT_FONT,
            fontSize=8,
            name='body',
            spaceAfter=4,
            justifyBreaks=1,
            backColor=Color(0, 0, 0, 0.1),
        )
Beispiel #27
0
def main():
    # To do: parse some useful arguments as rendering options here
    # e.g. outline color, page size, etc.
    #
    # For now, put these options into variables here:
    bg_color = Color(1.0, 1.0, 1.0, alpha=1.0)

    # For now just assume a list of files
    # kk: changed how to import pickle files so that they can be merged
    path = 'C:/Users/sawkk/Desktop/CellModeller2/data/Tutorial_1p10-17-06-01-11-24'
    a = os.listdir(path)
    infns = [_ for i in xrange(len(a))]
    for i in xrange(len(a)):
        infns[i] = path + '/' + a[i]  #sys.argv[1:]

    for infn in infns:
        # File names
        if infn[-7:] != '.pickle':
            print 'Ignoring file %s, because its not a pickle...' % (infn)
            continue

        outfn = string.replace(infn, '.pickle', '.pdf')
        #print 'Processing %s to generate %s'%(infn,outfn) #kk: commented the print

        # Import data
        data = importPickle(infn)
        if not data:
            print "Problem importing data!"
            return

        # Create a pdf canvas thing
        pdf = MyPDFGenerator(outfn, data, bg_color)

        # Get the bounding square of the colony to size the image
        # This will resize the image to fit the page...
        # ** alternatively you can specify a fixed world size here
        '''(w,h) = pdf.computeBox()
        sqrt2 = math.sqrt(2)
        world = (w/sqrt2,h/sqrt2)'''
        world = (250, 250)

        # Page setup
        page = (20, 20)
        center = (0, 0)

        # Render pdf
        #print 'Rendering PDF output to %s'%outfn #commented out print
        pdf.draw_frame(outfn, world, page, center)

        #kk: merging pdfs
        append_pdf(PdfFileReader(open(outfn, 'rb')), output)

    output.write(open("merged.pdf", "wb"))
Beispiel #28
0
    def __init__(self, path):
        self.path = path
        self.styleSheet = getSampleStyleSheet()
        self.elements = []

        # colors - Azul turkeza 367AB3
        self.colorOhkaGreen0 = Color((45.0/255), (166.0/255), (153.0/255), 1)
        self.colorOhkaGreen1 = Color((182.0/255), (227.0/255), (166.0/255), 1)
        self.colorOhkaGreen2 = Color((140.0/255), (222.0/255), (192.0/255), 1)
        #self.colorOhkaGreen2 = Color((140.0/255), (222.0/255), (192.0/255), 1)
        self.colorOhkaBlue0 = Color((54.0/255), (122.0/255), (179.0/255), 1)
        self.colorOhkaBlue1 = Color((122.0/255), (180.0/255), (225.0/255), 1)
        self.colorOhkaGreenLineas = Color((50.0/255), (140.0/255), (140.0/255), 1)

        self.firstPage()
        self.nextPagesHeader(True)
        self.remoteSessionTableMaker()
        self.nextPagesHeader(False)
        self.inSiteSessionTableMaker()
        self.nextPagesHeader(False)
        self.extraActivitiesTableMaker()
        self.nextPagesHeader(False)
        self.summaryTableMaker()
        # Build
        self.doc = SimpleDocTemplate(path, pagesize=LETTER)
        self.doc.multiBuild(self.elements, canvasmaker=FooterCanvas)
	def __init__(self,width=400,height=400,*args,**kw):
		Drawing.__init__(self,width,height,*args,**kw)
		self.transform = (1,0,0,1,0,0)
		self.add(Polygon(points=[108.3032,252.9412,200,288.2353,291.6968,252.9412,306.9796,138.2353,200,58.82353,93.02039,138.2353,108.3032,252.9412],fillColor=Color(1,.972549,.862745,1),fillOpacity=None,strokeColor=None,strokeWidth=0,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None))
		self.add(Polygon(points=[85.37899,266.1765,200,252.9412,261.1312,235.2941,276.414,155.8824,200,94.11765,131.2274,160.2941,85.37899,266.1765],fillColor=Color(0,1,1,1),fillOpacity=None,strokeColor=None,strokeWidth=0,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None))
		self.add(Polygon(points=[138.8688,235.2941,200,261.7647,261.1312,235.2941,329.9038,125,200,164.7059,108.3032,147.0588,138.8688,235.2941],fillColor=Color(.596078,.984314,.596078,1),fillOpacity=None,strokeColor=None,strokeWidth=0,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None))
		self.add(PolyLine(points=[108.3032,252.9412,200,288.2353,291.6968,252.9412,306.9796,138.2353,200,58.82353,93.02039,138.2353,108.3032,252.9412],strokeColor=Color(1,.972549,.862745,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None))
		self.add(PolyLine(points=[85.37899,266.1765,200,252.9412,261.1312,235.2941,276.414,155.8824,200,94.11765,131.2274,160.2941,85.37899,266.1765],strokeColor=Color(0,1,1,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None))
		self.add(PolyLine(points=[138.8688,235.2941,200,261.7647,261.1312,235.2941,329.9038,125,200,164.7059,108.3032,147.0588,138.8688,235.2941],strokeColor=Color(.596078,.984314,.596078,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None))
		self.add(Line(200,200,200,350,strokeColor=Color(0,0,0,1),strokeWidth=.5,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=(2,2),strokeOpacity=None))
		self.add(Line(200,200,329.9038,275,strokeColor=Color(0,0,0,1),strokeWidth=.5,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=(2,2),strokeOpacity=None))
		self.add(Line(200,200,329.9038,125,strokeColor=Color(0,0,0,1),strokeWidth=.5,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=(2,2),strokeOpacity=None))
		self.add(Line(200,200,200,50,strokeColor=Color(0,0,0,1),strokeWidth=.5,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=(2,2),strokeOpacity=None))
		self.add(Line(200,200,70.09619,125,strokeColor=Color(0,0,0,1),strokeWidth=.5,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=(2,2),strokeOpacity=None))
		self.add(Line(200,200,70.09619,275,strokeColor=Color(0,0,0,1),strokeWidth=.5,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=(2,2),strokeOpacity=None))
		v0=self._nn(Group())
		v0.transform = (1,0,0,1,200,357.5)
		v0.add(String(-2.22,-4,'a',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1)))
		v0=self._nn(Group())
		v0.transform = (1,0,0,1,336.399,278.75)
		v0.add(String(-2.5,-4,'b',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1)))
		v0=self._nn(Group())
		v0.transform = (1,0,0,1,336.399,121.25)
		v0.add(String(-2.22,-4,'c',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1)))
		v0=self._nn(Group())
		v0.transform = (1,0,0,1,200,42.5)
		v0.add(String(-2.5,-4,'d',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1)))
		v0=self._nn(Group())
		v0.transform = (1,0,0,1,63.601,121.25)
		v0.add(String(-2.22,-4,'e',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1)))
		v0=self._nn(Group())
		v0.transform = (1,0,0,1,63.601,278.75)
		v0.add(String(-1.665,-4,'f',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1)))
Beispiel #30
0
 def makeBorder(width, style="solid", color=Color(1, 0, 0)):
     return dict(borderLeftColor=color,
                 borderLeftWidth=width,
                 borderLeftStyle=style,
                 borderRightColor=color,
                 borderRightWidth=width,
                 borderRightStyle=style,
                 borderTopColor=color,
                 borderTopWidth=width,
                 borderTopStyle=style,
                 borderBottomColor=color,
                 borderBottomWidth=width,
                 borderBottomStyle=style)