当前位置: 首页>>代码示例>>Python>>正文


Python Canvas.setFillColorRGB方法代码示例

本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.setFillColorRGB方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.setFillColorRGB方法的具体用法?Python Canvas.setFillColorRGB怎么用?Python Canvas.setFillColorRGB使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在reportlab.pdfgen.canvas.Canvas的用法示例。


在下文中一共展示了Canvas.setFillColorRGB方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: createMarkedPDF

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
def createMarkedPDF(filenameOrFH, opts):
    """
    """
    # setup lengths
    length = opts.paperSize[1] / inch
    if opts.style == 'default':
        boxParamsMid = [0, 4, length, 0.5]
    if opts.style == 'trim':
        opts.drawTopCrop = True
        opts.drawBottomCrop = True
        boxParamsTop = [0, 0, length, 0.2]
        boxParamsMid = [0, 3.85, length, 0.8]
        boxParamsBot = [0, 8.3, length, 0.2]
    # with PDF files that have been converted from PS files via the command
    # line tool pstopdf, we've found that we need to invert the crop box
    # dimensions
    if opts.flip:
        boxParamsMid = _invertBoxParams(boxParamsMid)
        if opts.drawTopCrop:
            boxParamsTop = _invertBoxParams(boxParamsTop)
        if opts.drawBottomCrop:
            boxParamsBot = _invertBoxParams(boxParamsBot)
    # now create the PDF page
    canvas = Canvas(filenameOrFH, pagesize=landscape(opts.paperSize))
    canvas.setStrokeColorRGB(*opts.shade)
    canvas.setFillColorRGB(*opts.shade)
    canvas.rect(*[inch*x for x in boxParamsMid], **{'fill': 1})
    if opts.drawTopCrop:
        canvas.rect(*[inch*x for x in boxParamsTop], **{'fill': 1})
    if opts.drawBottomCrop:
        canvas.rect(*[inch*x for x in boxParamsBot], **{'fill': 1})
    canvas.showPage()
    canvas.save()
    return (filenameOrFH, canvas)
开发者ID:oubiwann,项目名称:tibetan-scripts,代码行数:36,代码来源:assembler.py

示例2: fattura_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
def fattura_pdf(request, id_fattura):
    fattura = Fatture.objects.get(id_fattura=id_fattura)
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    file_name= '%s %s %s' % (fattura.cliente_id.ragione_sociale, fattura.numero_fattura, fattura.data_fattura.isoformat())
    response['Content-Disposition'] = 'filename="%s"' % file_name

    # Create the PDF object, using the response object as its "file."
    canvas = Canvas(response, pagesize=A4)
    canvas.translate(0, 29.7 * cm)
    canvas.setStrokeColorRGB(0.2, 0.2, 0.2)
    canvas.setFillColorRGB(0.2, 0.2, 0.2)
    canvas.setFont('Helvetica', 10)

    draw_header(canvas, fattura)
    draw_invoice_detail(canvas, fattura)
    draw_description(canvas, fattura)
    draw_invoice(canvas, fattura)
    draw_footer(canvas)

    #pdf.restoreState()
    # Close the PDF object cleanly, and we're done.
    canvas.showPage()
    canvas.save()
    return response
开发者ID:MicheleRB,项目名称:studio,代码行数:27,代码来源:views.py

示例3: test_03_draw

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
 def test_03_draw(self):
     from reportlab.lib.pagesizes import A4
     from reportlab.pdfgen.canvas import Canvas
     from reportlab.lib.units import inch
     c = Canvas('demo.pdf', pagesize=A4)
     c.translate(inch,inch)
     c.setFont("Helvetica", 14)
     c.setStrokeColorRGB(0.2,0.5,0.3)
     c.setFillColorRGB(1,0,1)
     c.line(0,0,0,1.7*inch)
     c.line(0,0,1*inch,0)
     c.rect(0.2*inch, 0.2*inch, 1*inch, 1.5*inch,fill=1)
     c.rotate(90)
     c.setFillColorRGB(0,0,0.77)
     c.drawString(0.3*inch, -inch, "Hello World")
     c.showPage()
     c.save()
开发者ID:zenist,项目名称:ZLib,代码行数:19,代码来源:test_pdf.py

示例4: make_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
def make_pdf(name, nome_musica, letra):
    '''
    str -> none

    Takes in a string text and creates a pdf file named file_name
    containing the file.

    >>> make_pdf("Hello world!")
    >>>
    >>>a = "Meu coracao nao sei porque, bate feliz quando te ve"
    >>>make_pdf(a)
    >>>

    '''
    
    pdf = Canvas(nome_musica+".pdf")
 
    pdf.setFillColorRGB(1, 0, 0)
    pdf.setStrokeColorRGB(1, 0, 0)
    
    ## An important thing to note here is that when specifying coordinates,the 
    ## origin  is in the lower left hand corner of the page, rather than the
    ## top left. The default unit of measurement is a point, equal to one
    ## seventy-second of an inch.
    pdf.setFont("Courier", 45)
    pdf.drawString(cm * 5, cm * 25, name)
    
    pdf.setFont("Courier", 30)
    text = pdf.beginText(cm * 5, cm * 20)
 
    for each in range(letra.count("\n")):
        text.textLine(letra.split("\n")[each])

    pdf.drawText(text)
    

    ## Close the page. The showPage method closes the current page.
    ## Any further drawing will occur on the next page

    pdf.showPage()

    ## The ReportLab Toolkit saves our page
    pdf.save()
开发者ID:Jbaumotte,项目名称:web2py,代码行数:45,代码来源:pdf.py

示例5: add_QRcode

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
def add_QRcode(request):
    # add a new set of QRcode, each QR is one sample.
    # date and time is also included in this QRcode.

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="QRcodes.pdf"'

    #this is not a real QRList, just storing all text information for QRcode generation.
    QRList = []

    time = datetime.now().strftime("%I:%M%p on %B %d, %Y")

    for index in range(3182, 3198):
        # make a list of MICU, each element is either a sink or pTrap,
        # the time of QRcode generation was also included.
        dict = [time, 'MICU', str(index)]

        dict1 = dict+['sink']
        QRList.append(dict1)

        dict2 = dict+['pTrap']
        QRList.append(dict2)

    for index in range(5185, 5199):
        # make a list for SICU.
        dict = [time, 'SICU', str(index)]

        dict1 = dict+['sink']
        QRList.append(dict1)

        dict2 = dict+['pTrap']
        QRList.append(dict2)

        '''Generates book labels using the barcodes passed in. Each code should be
  an integer, and will be printed using 9 digits (padded with zeroes if necessary).
  Up to 30 labels will be generated per page for compatibility with Avery form
  5160/8160 or most other address label forms containing 30 per sheet. The text
  of a PDF document is returned (to be sent back to the browser).'''

    #using reportlab library, produce a canvas like pdf for drawing.
    pdf = Canvas(response, pagesize=letter)
    pdf.setFillColorRGB(0, 0, 0)

    # These 2 initial value was originally from labelgen.py from google code,
    # The value has been changed due to the use of Avery5160
    # The original value was 45 and 71.
    imgX = startX = 25
    imgY = startY = letter[1] - 101

    for singleQRCode in QRList:
        if imgX > 600:
            # Start a new page
            imgX = startX
            imgY = startY
            pdf.showPage()

        # Generate and draw the barcode
        curDate = singleQRCode[0]
        curUnit = singleQRCode[1]
        curRoom = singleQRCode[2]
        curLocation = singleQRCode[3]
        text = curDate+','+curUnit+','+curRoom+','+curLocation

        # QRPureImg is just the QRcode, not on canvas yet,
        # QRImage is canvas produced by reportlab
        QRPureImg = QrCodeWidget(text)
        bounds = QRPureImg.getBounds()
        width = bounds[2] - bounds[0]
        height = bounds[3] - bounds[1]
        QRImage = Drawing(45, 45, transform=[45. / width, 0, 0, 45. / height, 0, 0])
        QRImage.add(QRPureImg)
        renderPDF.draw(QRImage, pdf, imgX, imgY)

        #add text label for QRcode, the original value was for barcode, which his here
        # pdf.setFont("Courier", 12)
        # pdf.drawCentredString(imgX + 64.5, imgY - 10, txt)
        # pdf.setFont("Courier", 10)
        # pdf.drawCentredString(imgX + 64.5, imgY - 20, res['title'].upper()[:20].strip())

        pdf.setFont("Courier", 6)
        pdf.drawString(imgX + 60, imgY + 35, curDate)

        pdf.setFont("Courier", 12)
        pdf.drawString(imgX + 60, imgY + 20, curUnit+' '+curRoom)

        pdf.setFont("Courier", 12)
        pdf.drawString(imgX + 60, imgY + 5, curLocation)

        imgY -= 71  # Move down to the next label location

        if imgY < 50:
            # Start a new column
            imgY = startY
            imgX += 200

    pdf.showPage()
    pdf.save()

    return response
开发者ID:fernisoites,项目名称:environmentDB_site,代码行数:101,代码来源:views.py

示例6: get

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="{0}-{1}.pdf"'.format(self.object.registru.serie, self.object.numar_inregistrare)

        pdf = Canvas(response, pagesize = A4)

        import os
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.platypus import Paragraph

        pdfmetrics.registerFont(TTFont("DejaVuSans-Bold", "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf"))
        pdfmetrics.registerFont(TTFont("DejaVuSans", "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf"))

        if self.object.registru.centru_local.antet:
            antet_path = os.path.join(settings.MEDIA_ROOT, "%s" % self.object.registru.centru_local.antet)
            pdf.drawInlineImage(antet_path, 2.5 * cm, 10.8 * cm, width=16. * cm, height=2.66 * cm)
            pdf.drawInlineImage(antet_path, 2.5 * cm, 24.5 * cm, width=16. * cm, height=2.66 * cm)
        pdf.setStrokeColorRGB(0, 0, 0)
        pdf.rect(2. * cm, 2. * cm, 17. * cm, 12. * cm)
        pdf.rect(2. * cm, 15.7 * cm, 17. * cm, 12 * cm)

        pdf.setStrokeColorRGB(0.5, 0.5, 0.5)
        pdf.setDash(1, 2)
        pdf.line(0 * cm, 14.85 * cm, 21. * cm, 14.85 * cm)

        pdf.setFont("DejaVuSans-Bold", 0.5 * cm, leading=None)
        pdf.drawCentredString(10.5 * cm, 9.5 * cm, u"Chitanță")
        pdf.drawCentredString(10.5 * cm, 23.2 * cm, u"Chitanță")

        text_serie = u"seria {0}, nr. {1} / {2}".format(self.object.registru.serie, self.object.numar_inregistrare,
                                                       self.object.data_inregistrare.strftime("%d.%m.%Y"))

        pdf.setFont("DejaVuSans-Bold", 4. * cm, leading=None)
        pdf.setFillColorRGB(0.95, 0.95, 0.95)
        pdf.rotate(15)
        pdf.drawString(4.5 * cm, 2. * cm, u"COPIE")
        pdf.rotate(-15)

        pdf.setFillColorRGB(0, 0, 0)
        pdf.setFont("DejaVuSans", 0.35 * cm, leading=None)
        pdf.drawCentredString(10.5 * cm, 8.9 * cm, text_serie)
        pdf.drawCentredString(10.5 * cm, 22.6 * cm, text_serie)

        reprezinta = self.object.descriere
        if hasattr(self.object, "chitantacotizatie"):
            reprezinta = []
            for p in self.object.chitantacotizatie.platacotizatietrimestru_set.all().order_by("index"):
                date_reprezinta = (p.trimestru.__unicode__(), p.suma, u"- parțial" if p.partial else "")
                reprezinta.append("{0} ({1} RON{2})".format(*date_reprezinta))
            reprezinta = ", ".join(reprezinta)
            reprezinta = u"cotizație membru pentru {0}".format(reprezinta)
        date_chitanta = (self.object.platitor().__unicode__(), self.object.suma, suma2text(self.object.suma).strip(), reprezinta)
        text_chitanta = u"Am primit de la <strong>{0}</strong> suma de {1} lei, adică {2}, reprezentând {3}.".format(*date_chitanta)

        style_sheet = getSampleStyleSheet()
        style = style_sheet['Normal']
        style.alignment = TA_JUSTIFY
        style.fontName = "DejaVuSans"
        style.leading = 0.85 * cm

        paragraph = Paragraph(text_chitanta, style)
        w, h  = paragraph.wrap(15. * cm, 5. * cm)
        # print w, h

        paragraph.drawOn(pdf, 3. * cm, 5.5 * cm)
        paragraph.drawOn(pdf, 3. * cm, 19.2 * cm)

        pdf.drawString(12.5 * cm, 4.5 * cm, u"Casier,")
        pdf.drawString(12.5 * cm, 18.2 * cm, u"Casier, ")

        trezorier = self.object.registru.centru_local.ocupant_functie(u"Trezorier Centru Local")
        pdf.drawString(12.5 * cm, 3.8 * cm, trezorier.__unicode__())
        pdf.drawString(12.5 * cm, 17.5 * cm, trezorier.__unicode__())


        pdf.showPage()
        pdf.save()

        return response
开发者ID:andreiavram,项目名称:scoutfile,代码行数:83,代码来源:views.py

示例7: to_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
    def to_pdf(self, outFileName, imageFileName=None, showBoundingboxes=False,
               fontname="Helvetica", invisibleText=False):
        """
        Creates a PDF file with an image superimposed on top of the text.
        Text is positioned according to the bounding box of the lines in
        the hOCR file.
        The image need not be identical to the image used to create the hOCR
        file.
        It can have a lower resolution, different color mode, etc.
        """
        # create the PDF file
        # page size in points (1/72 in.)
        pdf = Canvas(
            outFileName, pagesize=(self.width, self.height), pageCompression=1)

        # draw bounding box for each paragraph
        # light blue for bounding box of paragraph
        pdf.setStrokeColorRGB(0, 1, 1)
        # light blue for bounding box of paragraph
        pdf.setFillColorRGB(0, 1, 1)
        pdf.setLineWidth(0)		# no line for bounding box
        for elem in self.hocr.findall(
                ".//%sp[@class='%s']" % (self.xmlns, "ocr_par")):

            elemtxt = self._get_element_text(elem).rstrip()
            if len(elemtxt) == 0:
                continue

            pxl_coords = self.element_coordinates(elem)
            pt = self.pt_from_pixel(pxl_coords)

            # draw the bbox border
            if showBoundingboxes:
                pdf.rect(
                    pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1,
                    fill=1)

        # check if element with class 'ocrx_word' are available
        # otherwise use 'ocr_line' as fallback
        elemclass = "ocr_line"
        if self.hocr.find(
                ".//%sspan[@class='ocrx_word']" % (self.xmlns)) is not None:
            elemclass = "ocrx_word"

        # itterate all text elements
        # light green for bounding box of word/line
        pdf.setStrokeColorRGB(1, 0, 0)
        pdf.setLineWidth(0.5)		# bounding box line width
        pdf.setDash(6, 3)		# bounding box is dashed
        pdf.setFillColorRGB(0, 0, 0)  # text in black
        for elem in self.hocr.findall(
                ".//%sspan[@class='%s']" % (self.xmlns, elemclass)):

            elemtxt = self._get_element_text(elem).rstrip()

            elemtxt = self.replace_unsupported_chars(elemtxt)

            if len(elemtxt) == 0:
                continue

            pxl_coords = self.element_coordinates(elem)
            pt = self.pt_from_pixel(pxl_coords)

            # draw the bbox border
            if showBoundingboxes:
                pdf.rect(
                    pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1,
                    fill=0)

            text = pdf.beginText()
            fontsize = pt.y2 - pt.y1
            text.setFont(fontname, fontsize)
            if invisibleText:
                text.setTextRenderMode(3)  # Invisible (indicates OCR text)

            # set cursor to bottom left corner of bbox (adjust for dpi)
            text.setTextOrigin(pt.x1, self.height - pt.y2)

            # scale the width of the text to fill the width of the bbox
            text.setHorizScale(
                100 * (pt.x2 - pt.x1) / pdf.stringWidth(
                    elemtxt, fontname, fontsize))

            # write the text to the page
            text.textLine(elemtxt)
            pdf.drawText(text)

        # put the image on the page, scaled to fill the page
        if imageFileName is not None:
            pdf.drawImage(imageFileName, 0, 0,
                          width=self.width, height=self.height)

        # finish up the page and save it
        pdf.showPage()
        pdf.save()
开发者ID:stweil,项目名称:OCRmyPDF,代码行数:97,代码来源:hocrtransform.py

示例8: render

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]

#.........这里部分代码省略.........
    r = g / k
    q = n + r
    v = (g * (-1 + k)) / k

    theta = asin((2.0 * g - 2.0 * g * k + k * s) /
        (2.0 * g - g * k + k * s)) * 180 / pi

    delta = theta - 90

    for j, row in enumerate(grid):
        # upper/lower rows
        for i, cell in enumerate(row):

            x_offset = left_margin + i * s
            y_offset = top_margin + j * s

            c.translate(x_offset, y_offset)
            p = c.beginPath()

            a = g
            b = s - g

            # mark start and end
            start = False
            end = False
            if (i == 0 and j == height - 1):
                start = True

            if (i == width - 1 and j == 0):
                end = True

            if start or end:
                c.setStrokeColorRGB(0.9, 0.1, 0.1)
                c.setFillColorRGB(0.9, 0.1, 0.1)
                p.circle(s / 2.0, s / 2.0, g / 1.5)
                c.drawPath(p, fill=True)
                p = c.beginPath()
                c.setStrokeColorRGB(0.0, 0.0, 0.0)

            if cell == 3:

                '│ │'
                '│ │'

                p.moveTo(a, s)
                p.lineTo(a, 0)
                p.moveTo(b, s)
                p.lineTo(b, 0)

            if cell == 1:

                '│ │'
                '└─┘'

                p.moveTo(b, 0)
                if draw_with_curves:

                    p.lineTo(b, q)
                    x = s - v - r
                    y = n
                    p.arcTo(x, y, x + 2 * r, y + 2 * r, 180, delta)

                    p.arcTo(g / 2,
                            g / 2,
                            s - g / 2,
                            s - g / 2, theta - 90, 360 - 2 * theta)
开发者ID:dennisjameslyons,项目名称:maze,代码行数:70,代码来源:pdf.py

示例9: InvoiceTemplate

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
class InvoiceTemplate(object):
    def __init__(self, filename, logo_filename=LOGO_FILENAME,
                 from_address=Address(**settings.INVOICE_FROM_ADDRESS),
                 to_address=None, project_name='',
                 invoice_date=None, invoice_number='',
                 terms=settings.INVOICE_TERMS,
                 due_date=None, date_start=None, date_end=None,
                 bank_name=settings.BANK_NAME,
                 bank_address=Address(**settings.BANK_ADDRESS),
                 account_number=settings.BANK_ACCOUNT_NUMBER,
                 routing_number=settings.BANK_ROUTING_NUMBER,
                 swift_code=settings.BANK_SWIFT_CODE,
                 applied_credit=None,
                 subtotal=None, tax_rate=None, applied_tax=None, total=None):
        self.canvas = Canvas(filename)
        self.canvas.setFontSize(DEFAULT_FONT_SIZE)
        self.logo_filename = os.path.join(os.getcwd(), logo_filename)
        self.from_address = from_address
        self.to_address = to_address
        self.project_name = project_name
        self.invoice_date = invoice_date
        self.invoice_number = invoice_number
        self.terms = terms
        self.due_date = due_date
        self.date_start = date_start
        self.date_end = date_end
        self.bank_name = bank_name
        self.bank_address = bank_address
        self.account_number = account_number
        self.routing_number = routing_number
        self.swift_code = swift_code
        self.applied_credit = applied_credit
        self.subtotal = subtotal
        self.tax_rate = tax_rate
        self.applied_tax = applied_tax
        self.total = total

        self.items = []

    def add_item(self, description, quantity, unit_cost, subtotal, credits, total):
        self.items.append(PdfLineItem(description, quantity, unit_cost,
                                      subtotal, credits, total))

    def get_pdf(self):
        self.draw_logo()
        self.draw_from_address()
        self.draw_to_address()
        self.draw_project_name()
        self.draw_statement_period()
        self.draw_invoice_label()
        self.draw_details()
        self.draw_table()
        self.draw_footer()

        self.canvas.showPage()
        self.canvas.save()

    def draw_logo(self):
        self.canvas.drawImage(self.logo_filename, inches(0.5), inches(2.5),
                              width=inches(1.5), preserveAspectRatio=True)

    def draw_text(self, string, x, y):
        text = self.canvas.beginText()
        text.setTextOrigin(x, y)
        for line in string.split('\n'):
            text.textLine(line)
        self.canvas.drawText(text)

    def draw_from_address(self):
        if self.from_address is not None:
            self.draw_text(unicode(self.from_address), inches(3), inches(11))

    def draw_to_address(self):
        origin_x = inches(1)
        origin_y = inches(9.2)
        self.canvas.translate(origin_x, origin_y)

        left = inches(0)
        right = inches(4.5)
        top = inches(0.3)
        middle_horizational = inches(0)
        bottom = inches(-1.7)
        self.canvas.rect(left, bottom, right - left, top - bottom)

        self.canvas.setFillColorRGB(*LIGHT_GRAY)
        self.canvas.rect(left, middle_horizational, right - left,
                         top - middle_horizational, fill=1)

        self.canvas.setFillColorRGB(*BLACK)
        self.draw_text("Bill To", left + inches(0.2),
                       middle_horizational + inches(0.1))

        if self.to_address is not None:
            self.draw_text(unicode(self.to_address), inches(0.1), inches(-0.2))

        self.canvas.translate(-origin_x, -origin_y)

    def draw_project_name(self):
        origin_x = inches(1)
        origin_y = inches(7.4)
#.........这里部分代码省略.........
开发者ID:NoahCarnahan,项目名称:commcare-hq,代码行数:103,代码来源:invoice_pdf.py

示例10: Address

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]

#.........这里部分代码省略.........
        text.textLines("\n".join(self.client.getContactLines()))
        self.pdf.drawText(text)
 
    def drawProvider(self,TOP,LEFT):
        LEFT += 90
        self.pdf.setFont("DejaVu", 12)
        self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Address")
        self.pdf.setFont("DejaVu", 9)
        text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm)
        text.textLines("\n".join(self.provider.getAddressLines()))
        self.pdf.drawText(text)
        text = self.pdf.beginText((LEFT+40)*mm, (TOP-6)*mm)
        text.textLines("\n".join(self.provider.getContactLines()))
        self.pdf.drawText(text)
        if self.provider.note:
            self.pdf.drawString((LEFT+2)*mm, (TOP-26)*mm, self.provider.note)
 
    def drawPayment(self,TOP,LEFT):
        self.pdf.setFont("DejaVu", 11)
        self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Patient Name")
        self.pdf.drawString((LEFT+50)*mm, (TOP)*mm, "Date")
        self.pdf.setFont("DejaVu", 9)
        text = self.pdf.beginText((LEFT+50)*mm, (TOP-6)*mm)
        text.textLines(self.date)
        self.pdf.drawText(text)
        
        text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm)
        text.textLines("\n".join(self.client.getAddressLines()))
        self.pdf.drawText(text)
        text = self.pdf.beginText((LEFT+2)*mm, (TOP-28)*mm)
        text.textLines("\n".join(self.client.getContactLines()))
        self.pdf.drawText(text)
 
        self.pdf.drawText(text)
        
    def drawItems(self,TOP,LEFT):
        # Items
        #path = self.pdf.beginPath()
        #path.moveTo((LEFT)*mm, (TOP-4)*mm)
        #path.lineTo((LEFT+176)*mm, (TOP-4)*mm)
        #self.pdf.drawPath(path, True, True)
 
        self.pdf.setFont("DejaVu", 11)
        i=1
        self.pdf.drawString((LEFT+1)*mm, (TOP-i)*mm, "Description")
        self.pdf.drawString((LEFT+98)*mm, (TOP-i)*mm, "Quantity")
        self.pdf.drawString((LEFT+121)*mm, (TOP-i)*mm, "Unit Price")
        self.pdf.drawString((LEFT+149)*mm, (TOP-i)*mm, "Amount")
        i+=7
        self.pdf.setFont("DejaVu", 9)
        # List
        total=0.0

        for x in self.items:
            self.pdf.drawString((LEFT+1)*mm, (TOP-i)*mm, x.name)
            i+=0
            self.pdf.drawString((LEFT+100)*mm, (TOP-i)*mm, "%d" % x.count)
            self.pdf.drawString((LEFT+122)*mm, (TOP-i)*mm, "Rs. %.2f" % x.price)
            self.pdf.drawString((LEFT+150)*mm, (TOP-i)*mm, "Rs. %.2f" % (x.total()))
            i+=5
            total += x.total()
        self.items = []
        path = self.pdf.beginPath()
        path.moveTo((LEFT)*mm, (TOP-i)*mm)
        path.lineTo((LEFT+176)*mm, (TOP-i)*mm)
        self.pdf.drawPath(path, True, True)
        total = round(total,2)
        self.pdf.setFont("DejaVu", 10)
        self.pdf.drawString((LEFT+1)*mm, (TOP-i-8)*mm, self.p.number_to_words(total).title() + " Rupees Only.")
        self.pdf.setFont("DejaVu", 12)
        self.pdf.drawString((LEFT+130)*mm, (TOP-i-8)*mm, "Total: Rs. %s" % total)
        self.pdf.setFont("Helvetica-Bold", 40)
        self.pdf.setStrokeGray(0.25)
        self.pdf.setFillColorRGB(0.95, 0.95, 0.95)
        self.pdf.drawString((LEFT+60)*mm, (TOP-i)*mm, 'PAID')
        self.pdf.setFillColorRGB(0, 0, 0)
      
 
        self.pdf.rect((LEFT)*mm, (TOP-i-12)*mm, (LEFT+156)*mm, (i+19)*mm, stroke=True, fill=False) #140,142
 
        if self.sign_image:
            self.pdf.drawImage(self.sign_image, (LEFT+98)*mm, (TOP-i-72)*mm)
 
        # if self.creator: 
        #     path = self.pdf.beginPath()
        #     path.moveTo((LEFT+110)*mm, (TOP-i-70)*mm)
        #     path.lineTo((LEFT+164)*mm, (TOP-i-70)*mm)
        #     self.pdf.drawPath(path, True, True)
 
        #     self.pdf.drawString((LEFT+112)*mm, (TOP-i-75)*mm, "Authorized Signatory")
 
 
    def drawDates(self,TOP,LEFT):
        LEFT -= 90
        today = datetime.datetime.today()
        payback = today+datetime.timedelta(self.payment_days)
        
        self.pdf.setFont("DejaVu", 10)
        self.pdf.drawString((LEFT)*mm, (TOP+1)*mm, "TIN: %s" % self.TIN)
        self.pdf.drawString((LEFT)*mm, (TOP-4)*mm, "DL: %s" % self.CAN)
开发者ID:anandpratap,项目名称:pymedical,代码行数:104,代码来源:invoicepdf.py

示例11: render

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
    def render(self, outfile, font_name, font_size):
        """
        Render the binary heat map as a PDF to the file-like object or filename
        ``outfile``.  All text will be typeset in the font named ``font_name``
        at size ``font_size``.
        """
        c = Canvas(outfile)
        c.setFont(font_name, font_size)
        leftlen = max(map(c.stringWidth, self.row_labels)) + LABEL_PAD * 2
        toplen  = max(map(c.stringWidth, self.column_labels)) + LABEL_PAD * 2
        miny = self.rows * font_size * 1.2
        maxx = self.columns * font_size * 1.2
        c.setPageSize((leftlen + maxx + PADDING*2, miny + toplen + PADDING*2))
        # Set coordinates so that LL corner has coord (-leftlen-PADDING,
        # -miny-PADDING) and the origin is at the point where the borders of the
        # row & column labels meet:
        c.translate(leftlen+PADDING, miny+PADDING)

        lineheight = font_size * 1.2
        radius = lineheight / 3

        c.setFillColorRGB(*COL_BG_COLOR)
        for i in range(0, self.columns, 2):
            c.rect(
                i * lineheight,
                -miny,
                lineheight,
                miny + toplen,
                stroke=0,
                fill=1,
            )

        c.setFillColorRGB(*ROW_BG_COLOR)
        for i in range(2, self.rows+1, 2):
            # Yes, it starts at 2, so that the positive rectangle height will
            # make it fill row 1.
            c.rect(
                -leftlen,
                -i * lineheight,
                leftlen + maxx,
                lineheight,
                stroke=0,
                fill=1,
            )

        c.setFillColorRGB(0, 0, 0)
        c.line(0, toplen, 0, -miny)
        c.line(-leftlen, 0, maxx, 0)

        for i, label in enumerate(self.row_labels):
            c.drawRightString(
                -LABEL_PAD,
                -(i+1) * lineheight + font_size / 3,
                label,
            )

        for i, label in enumerate(self.column_labels):
            c.saveState()
            c.translate((i+1) * lineheight, 0)
            c.rotate(90)
            c.drawString(LABEL_PAD, font_size / 3, label)
            c.restoreState()

        for row, col in self.get_indexed_pairs():
            c.circle(
                (col+0.5) * lineheight,
                -(row+0.5) * lineheight,
                radius,
                stroke=0,
                fill=1,
            )

        c.showPage()
        c.save()
开发者ID:jwodder,项目名称:binheat,代码行数:76,代码来源:binheat.py

示例12: to_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
    def to_pdf(
        self,
        outFileName,
        imageFileName=None,
        showBoundingboxes=False,
        fontname="Helvetica",
        invisibleText=False,
        interwordSpaces=False,
    ):
        """
        Creates a PDF file with an image superimposed on top of the text.
        Text is positioned according to the bounding box of the lines in
        the hOCR file.
        The image need not be identical to the image used to create the hOCR
        file.
        It can have a lower resolution, different color mode, etc.
        """
        # create the PDF file
        # page size in points (1/72 in.)
        pdf = Canvas(outFileName, pagesize=(self.width, self.height), pageCompression=1)

        # draw bounding box for each paragraph
        # light blue for bounding box of paragraph
        pdf.setStrokeColorRGB(0, 1, 1)
        # light blue for bounding box of paragraph
        pdf.setFillColorRGB(0, 1, 1)
        pdf.setLineWidth(0)  # no line for bounding box
        for elem in self.hocr.findall(".//%sp[@class='%s']" % (self.xmlns, "ocr_par")):

            elemtxt = self._get_element_text(elem).rstrip()
            if len(elemtxt) == 0:
                continue

            pxl_coords = self.element_coordinates(elem)
            pt = self.pt_from_pixel(pxl_coords)

            # draw the bbox border
            if showBoundingboxes:
                pdf.rect(
                    pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1, fill=1
                )

        found_lines = False
        for line in self.hocr.findall(
            ".//%sspan[@class='%s']" % (self.xmlns, "ocr_line")
        ):
            found_lines = True
            self._do_line(
                pdf,
                line,
                "ocrx_word",
                fontname,
                invisibleText,
                interwordSpaces,
                showBoundingboxes,
            )

        if not found_lines:
            # Tesseract did not report any lines (just words)
            root = self.hocr.find(".//%sdiv[@class='%s']" % (self.xmlns, "ocr_page"))
            self._do_line(
                pdf,
                root,
                "ocrx_word",
                fontname,
                invisibleText,
                interwordSpaces,
                showBoundingboxes,
            )
        # put the image on the page, scaled to fill the page
        if imageFileName is not None:
            pdf.drawImage(imageFileName, 0, 0, width=self.width, height=self.height)

        # finish up the page and save it
        pdf.showPage()
        pdf.save()
开发者ID:jbarlow83,项目名称:OCRmyPDF,代码行数:78,代码来源:hocrtransform.py

示例13: InvoiceTemplate

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
class InvoiceTemplate(object):

    def __init__(self, filename, logo_filename=LOGO_FILENAME,
                 from_address=Address(**settings.INVOICE_FROM_ADDRESS),
                 to_address=None, project_name='',
                 invoice_date=None, invoice_number='',
                 terms=settings.INVOICE_TERMS,
                 due_date=None, date_start=None, date_end=None,
                 bank_name=settings.BANK_NAME,
                 bank_address=Address(**settings.BANK_ADDRESS),
                 account_number=settings.BANK_ACCOUNT_NUMBER,
                 routing_number_ach=settings.BANK_ROUTING_NUMBER_ACH,
                 routing_number_wire=settings.BANK_ROUTING_NUMBER_WIRE,
                 swift_code=settings.BANK_SWIFT_CODE,
                 applied_credit=None,
                 subtotal=None, tax_rate=None, applied_tax=None, total=None,
                 is_wire=False, is_prepayment=False):
        self.canvas = Canvas(filename)
        self.canvas.setFontSize(DEFAULT_FONT_SIZE)
        self.logo_filename = os.path.join(os.getcwd(), logo_filename)
        self.from_address = from_address
        self.to_address = to_address
        self.project_name = project_name
        self.invoice_date = invoice_date
        self.invoice_number = invoice_number
        self.terms = terms
        self.due_date = due_date
        self.date_start = date_start
        self.date_end = date_end
        self.bank_name = bank_name
        self.bank_address = bank_address
        self.account_number = account_number
        self.routing_number_ach = routing_number_ach
        self.routing_number_wire = routing_number_wire
        self.swift_code = swift_code
        self.applied_credit = applied_credit
        self.subtotal = subtotal
        self.tax_rate = tax_rate
        self.applied_tax = applied_tax
        self.total = total
        self.is_wire = is_wire
        self.is_prepayment = is_prepayment

        self.items = []

    def add_item(self, description, quantity, unit_cost, subtotal, credits, total):
        self.items.append(PdfLineItem(description, quantity, unit_cost,
                                      subtotal, credits, total))

    def get_pdf(self):
        self.draw_logo()
        self.draw_from_address()
        self.draw_to_address()
        self.draw_project_name()
        if not self.is_prepayment:
            self.draw_statement_period()
        self.draw_invoice_label()
        self.draw_details()
        if not self.is_wire or self.is_prepayment:
            self.draw_table()
        self.draw_footer()

        self.canvas.showPage()
        self.canvas.save()

    def draw_logo(self):
        self.canvas.drawImage(self.logo_filename, inches(0.5), inches(2.5),
                              width=inches(1.5), preserveAspectRatio=True)

    def draw_text(self, string, x, y):
        text = self.canvas.beginText()
        text.setTextOrigin(x, y)
        for line in string.split('\n'):
            text.textLine(line)
        self.canvas.drawText(text)

    def draw_from_address(self):
        if self.from_address is not None:
            self.draw_text(unicode(self.from_address), inches(3), inches(11))

    def draw_to_address(self):
        origin_x = inches(1)
        origin_y = inches(9.2)
        self.canvas.translate(origin_x, origin_y)

        left = inches(0)
        right = inches(4.5)
        top = inches(0.3)
        middle_horizational = inches(0)
        bottom = inches(-1.7)
        self.canvas.rect(left, bottom, right - left, top - bottom)

        self.canvas.setFillColorRGB(*LIGHT_GRAY)
        self.canvas.rect(left, middle_horizational, right - left,
                         top - middle_horizational, fill=1)

        self.canvas.setFillColorRGB(*BLACK)
        self.draw_text("Bill To", left + inches(0.2),
                       middle_horizational + inches(0.1))

#.........这里部分代码省略.........
开发者ID:saakaifoundry,项目名称:commcare-hq,代码行数:103,代码来源:invoice_pdf.py

示例14: print_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
def print_pdf(deck, input_filename):
    #card size in mm
    CARD_WIDTH = settings.CARD_WIDTH
    CARD_HEIGHT = settings.CARD_HEIGHT
    CARD_HORIZONTAL_SPACING = settings.CARD_HORIZONTAL_SPACING
    CARD_VERTICAL_SPACING = settings.CARD_VERTICAL_SPACING
    
    padding_left = (settings.SCALED_PAGE[0] - (3*CARD_WIDTH + (4*CARD_HORIZONTAL_SPACING))*mm)/2
    padding_bottom = (settings.SCALED_PAGE[1] - (3*CARD_HEIGHT)*mm)/2
        
    def make_page(cards, canvas):
        canvas.translate(padding_left, padding_bottom)
        col, row = 0, 3
        for card_name in cards:
            image = get_image_full_path(card_name, settings.IMAGES_FULL_PATH)
            if col % 3 == 0:
                row -= 1
                col = 0
            #x and y define the lower left corner of the image you wish to
            #draw (or of its bounding box, if using preserveAspectRation below).            
            canvas.drawImage(image, x=(col*CARD_WIDTH+((2*col)*CARD_HORIZONTAL_SPACING))*mm, y=(row*CARD_HEIGHT+((2*row-2)*CARD_VERTICAL_SPACING))*mm, width=CARD_WIDTH*mm, height=CARD_HEIGHT*mm)
            col += 1
        canvas.showPage()

    output_filename = '%s_print.pdf' % input_filename[:-4]
    output_fullpath = os.path.join(settings.OUTPUT_PATH, output_filename)
    canvas = Canvas(output_fullpath, pagesize=settings.SCALED_PAGE)

    CARDS_ON_PAGE = 9
    def number_of_pages(deck):
        return int(math.ceil(1.0 * len(deck) / CARDS_ON_PAGE))

    for index in range(number_of_pages(deck)):
        cards = deck[(index * CARDS_ON_PAGE):(index * CARDS_ON_PAGE + CARDS_ON_PAGE)]
        canvas.setFillColor(settings.PAGE_FILL_COLOR)
        canvas.rect(x=0,y=0,width=settings.SCALED_PAGE[0],height=settings.SCALED_PAGE[1],fill=True)
        make_page(cards, canvas)
    try:
        canvas.save()
    except IOError:
        print 'Save of the file %s failed. If you have the PDF file opened, close it.' % output_filename
        sys.exit(1)

    print '%s saved.' % output_filename
    
    #sheet for pack quick overview
    
    output_filename = '%s_overview.pdf' % input_filename[:-4]
    output_fullpath = os.path.join(settings.OUTPUT_PATH, output_filename)
    canvas = Canvas(output_fullpath, pagesize=settings.SCALED_PAGE)
    canvas.translate(padding_left, padding_bottom)

    #making list unique but maintain the order
    cards = list(set(deck))
    cards.sort(cmp=lambda x,y: cmp(deck.index(x), deck.index(y))) 
    
    multiplicator = int(math.ceil(math.sqrt(len(cards))))
    
    CARD_WIDTH = 3.0 * CARD_WIDTH / multiplicator
    CARD_HEIGHT = 3.0 * CARD_HEIGHT / multiplicator
    
    x, y = 0, multiplicator
    for card_name in cards:
        image = get_image_full_path(card_name, settings.IMAGES_FULL_PATH)
        if x % multiplicator == 0:
            y -= 1
            x = 0
        #x and y define the lower left corner of the image you wish to
        #draw (or of its bounding box, if using preserveAspectRation below).
        canvas.drawImage(image, 
                         x=x*CARD_WIDTH*mm, 
                         y=y*CARD_HEIGHT*mm, 
                         width=CARD_WIDTH*mm, 
                         height=CARD_HEIGHT*mm)
        canvas.setFillColorRGB(1,1,1)
        canvas.rect(x=x*CARD_WIDTH*mm + CARD_WIDTH*mm/10, 
                    y=y*CARD_HEIGHT*mm + CARD_HEIGHT*mm/1.5, 
                    width=CARD_WIDTH*mm/4, 
                    height=CARD_HEIGHT*mm/6, 
                    stroke=1, fill=1)
        canvas.setFillColorRGB(0,0,0)
        canvas.drawString(x=x*CARD_WIDTH*mm + CARD_WIDTH*mm/10 + CARD_WIDTH*mm/20, 
                          y=y*CARD_HEIGHT*mm + CARD_HEIGHT*mm/1.5 + CARD_HEIGHT*mm/20,
                          text="%dx" % deck.count(card_name))
        x += 1
    canvas.showPage()

    try:
        canvas.save()
    except IOError:
        print 'Save of the file %s failed. If you have the PDF file opened, close it.' % output_filename
        sys.exit(1)

    print '%s saved.' % output_filename
开发者ID:ssansom,项目名称:mtg-proxy-printer,代码行数:96,代码来源:mtg_proxy_printer.py

示例15: generate_certificate

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setFillColorRGB [as 别名]
def generate_certificate(description_of_items,cost_of_items,amount,cost,qty,raise_for,request ):

    buffer = BytesIO()
    styleSheet = getSampleStyleSheet()
    style = styleSheet['Normal']
    canv = Canvas('my_pdf.pdf')
    canv.setFillColorRGB(0, 0, 255)
    canv.setFont('Helvetica-Bold', 44, leading=None)
    canv.drawCentredString(102, 800, "INVOICE")
    canv.setFont('Helvetica-Bold', 8, leading=None)
    #canv.drawCentredString(38, 824, "From:")
    b = Company_credentials.objects.get(user=request.user)
    canv.setFillColorRGB(0, 0, 255)
    canv.drawCentredString(480, 826, b.company_name)
    canv.drawCentredString(480, 813, b.email)
    canv.drawCentredString(480, 801, b.country + ',' + b.phone_number)
    #canv.drawCentredString(480, 790, b.email)
    canv.setFillColorRGB(0, 0, 0)

    canv.drawCentredString(480, 790, "Raised on:" + str(datetime.date.today()) )
    canv.line(0, 785, 800, 785)
    canv.setFont('Helvetica', 21, leading=None)
    canv.setFillColorRGB(0, 0, 255)
    canv.drawCentredString(68, 760, "Description:")
    canv.setFillColorRGB(0, 0, 0)
    canv.setFont('Helvetica-Bold', 14, leading=None)
    canv.drawCentredString(120, 730, "ITEMS")
    canv.drawCentredString(320, 730, "RATE")
    canv.drawCentredString(410, 730, "QTY")
    canv.drawCentredString(500, 730, "AMOUNT")
    canv.setFont('Helvetica', 8, leading=None)
    y_coordinate = 710
    chaska = 0
    length = len(description_of_items)
    for chaska in range(length):
        canv.drawCentredString(120, y_coordinate,description_of_items[chaska])
        canv.drawCentredString(320, y_coordinate, str(cost_of_items[chaska]))
        canv.drawCentredString(410, y_coordinate, str(qty[chaska]))
        canv.drawCentredString(500, y_coordinate, '$' + str(amount[chaska]))
        y_coordinate = y_coordinate - 15
    y_coordinate = y_coordinate - 25
    canv.line(310, y_coordinate, 580, y_coordinate)
    canv.setFont('Helvetica-Bold', 12, leading=None)
    canv.drawCentredString(410, y_coordinate-16, "Total")
    canv.drawCentredString(500, y_coordinate-16, '$' + str(cost))
    canv.setFillColorRGB(0,0,255)
    canv.setFont('Helvetica', 16, leading=None)
    canv.drawCentredString(55, y_coordinate-16, "Raised For:")
    canv.setFillColorRGB(0, 0, 0)
    P = Paragraph(raise_for, style)
    aW = 180
    aH = y_coordinate-46
    w, h = P.wrap(aW, aH)  # find required space
    if w <= aW and h <= aH:
        P.drawOn(canv, 12, aH)
        aH = aH - h  # reduce the available height
    canv.save()
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
开发者ID:agiliq,项目名称:sleekinvoices,代码行数:62,代码来源:views.py


注:本文中的reportlab.pdfgen.canvas.Canvas.setFillColorRGB方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。