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


Python Canvas.setStrokeColorRGB方法代码示例

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


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

示例1: fattura_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [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

示例2: main

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
def main():
    currpos = PAGESIZE[1] - LINEHEIGHT # start at 1 line from top of page
    pdf = Canvas(OUTPUTFILE, pagesize = ORIENTATION(PAGESIZE))
    pdf.setFillGray(1)
    pdf.setLineWidth(GUIDETHICKNESS_MAIN)
    while currpos > LINEHEIGHT: # Loop until we reach one line from bottom of page
        # Draw tall ascender line
        pdf.setStrokeGray(0.5)
        pdf.line( 0, currpos, PAGESIZE[0], currpos)

        # Draw short ascender line, x-height-line, and baseline
        pdf.setStrokeGray(0.75)
        pdf.setLineWidth(GUIDETHICKNESS_SMALL)        
        pdf.line( 0, currpos - ( LINEHEIGHT/6 ),
                  PAGESIZE[0], currpos - ( LINEHEIGHT/6 ))
        pdf.line( 0, currpos - ( LINEHEIGHT/3 ),
                  PAGESIZE[0], currpos - ( LINEHEIGHT/3 ))
        pdf.line( 0, currpos - ( 2 * LINEHEIGHT/3 ),
                  PAGESIZE[0], currpos - ( 2 * LINEHEIGHT/3 ))

        currpos -= LINEHEIGHT

    # Draw a final line, and draw a margin
    pdf.setStrokeColorRGB(0.5, 0.5, 0.5)
    pdf.setLineWidth(GUIDETHICKNESS_MAIN)
    pdf.line( 0, currpos, PAGESIZE[0], currpos)
    if LEFTMARGIN:
        pdf.line( 2 * LINEHEIGHT, currpos,
                  2 * LINEHEIGHT, PAGESIZE[1] - LINEHEIGHT ) 

    # close up.
    pdf.showPage()
    pdf.save()
开发者ID:ChaseVoid,项目名称:python-play,代码行数:35,代码来源:writingpaper.py

示例3: test3

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
    def test3(self):
        from reportlab.pdfgen.canvas import Canvas

        aW=307
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']
        btj = ParagraphStyle('bodyText1j',parent=bt,alignment=TA_JUSTIFY)
        p=Paragraph("""<a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
                keepTogether attributes.  Generated at 1111. The number in brackets
                at the end of each paragraph is its position in the story. llllllllllllllllllllllllll 
                bbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccc ddddddddddddddddddddd eeeeyyy""",btj)

        w,h=p.wrap(aW,1000)
        canv=Canvas('test_platypus_paragraph_just.pdf',pagesize=(aW,h))
        i=len(canv._code)
        p.drawOn(canv,0,0)
        ParaCode=canv._code[i:]
        canv.saveState()
        canv.setLineWidth(0)
        canv.setStrokeColorRGB(1,0,0)
        canv.rect(0,0,aW,h)
        canv.restoreState()
        canv.showPage()
        canv.save()
        from reportlab import rl_config
        x = rl_config.paraFontSizeHeightOffset and '50' or '53.17'
        good = ['q', '1 0 0 1 0 0 cm', 'q', 'BT 1 0 0 1 0 '+x+' Tm 3.59 Tw 12 TL /F1 10 Tf 0 0 0 rg (Subsequent pages test pageBreakBefore, frameBreakBefore and) Tj T* 0 Tw .23 Tw (keepTogether attributes. Generated at 1111. The number in brackets) Tj T* 0 Tw .299167 Tw (at the end of each paragraph is its position in the story. llllllllllllllllllllllllll) Tj T* 0 Tw 66.9 Tw (bbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccc) Tj T* 0 Tw (ddddddddddddddddddddd eeeeyyy) Tj T* ET', 'Q', 'Q']
        ok= ParaCode==good
        assert ok, "\nParaCode=%r\nexpected=%r" % (ParaCode,good)
开发者ID:FatihZor,项目名称:infernal-twin,代码行数:31,代码来源:test_platypus_breaking.py

示例4: createMarkedPDF

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [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

示例5: generateOfficePDF

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
 def generateOfficePDF(self,response):
     #Attach name.pdf file to responses content disposition
     response['Content-Disposition'] = 'attachment; filename=office.pdf'
     
     #Create empty pdf document, hook pdf with response
     pdf = Canvas(response) 
     
     #Get Todays Events
     brains = sorted(util.gatherTodaysEvents(self), key=attrgetter('location')) #so awesome, sorts on any attribute!
     brains = sorted(brains, key=attrgetter('start')) #even better a secondary sort.
     
     #Header: Title Information and Settings
     pdf.setFont("Helvetica-Bold", 12)
     pdf.setStrokeColorRGB(0, 0, 0) #sets Line/Rectangle Colors
     
     #Header Left Title
     if brains != None and len(brains) > 0:
         pdf.drawString(15, 810, DateTime(brains[0].start).strftime("%A, %B %d, %Y") + " Schedule")
     else:
         pdf.drawString(15, 810, "No Groups scheduled for " + datetime.datetime.now().strftime("%A, %B %d, %Y"))
         
     #Header Right Title
     pdf.drawRightString(575, 810, "GroupFinder")
     
     #Body: List of Groups and Settings
     index = 792 #Pixel Index, starting at the top of the pdf page
     page = 1 #Page Number
     
     for brain in brains:
         pdf.setFont("Helvetica", 12)
         pdf.setStrokeColorRGB(0, 0, 0) #sets Line/Rectangle Colors
         pdf.rect(10, index-20, 575, 30, stroke=1, fill=0) #Rectangle around each Group
         pdf.drawString(15, index-3, brain.Title) #Group Description
         
         l = self.locationLookup(brain.location)
         pdf.drawString(15, index-15, DateTime(brain.start).strftime("%I:%M %p") + 
                                      " - " + DateTime(brain.end).strftime("%I:%M %p") +
                                      " in " + l['Name']) 
         index -= 30 #Move Pixel Index downwards
         
         #Reach Bottom of page?  Creates New Page.
         if index < 30:
             pdf.drawString(15, 5, "Page " + str(page))#add page number pages
             pdf.drawCentredString(300, 5, "Created on " + datetime.datetime.now().strftime("%m/%d/%Y at %I:%M %p"))
             page+=1
             index = 792
             pdf.showPage() #next page
     
     #add page number pages
     pdf.drawString(15, 5, "Page " + str(page))
     
     #add date PDF was created
     pdf.drawCentredString(300, 5, "Created on " + datetime.datetime.now().strftime("%m/%d/%Y at %I:%M %p"))
                     
     pdf.showPage() #next page, finalize last page.
     
     pdf.save() #save the pdf content
     return response #return response with hooked pdf.
开发者ID:uwosh,项目名称:uwosh.librarygroupfinder,代码行数:60,代码来源:print.py

示例6: generateEntrancePDF

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
    def generateEntrancePDF(self,response):
        #Attach name.pdf file to responses content disposition
        response['Content-Disposition'] = 'attachment; filename=entrance.pdf'
        
        #Create empty pdf document, hook pdf with response
        pdf = Canvas(response)



        pdf.setFillColor(colors.black) #sets Line/Rectangle Colors
        pdf.roundRect(10, 755, 575, 75, 10, 1, 0)
        pdf.setFont("Helvetica-Bold", 40)
        pdf.setStrokeColorRGB(0, 0, 0) #sets Line/Rectangle Colors
        pdf.drawCentredString(300, 790, "GroupFinder")
        pdf.setFont("Helvetica-Bold", 20)
        pdf.drawString(15, 765, "The following spaces are reserved during scheduled hours")

        
        pdf.drawCentredString(300,725, datetime.datetime.now().strftime("%A, %B %d, %Y"))

        #Get Todays Events
        brains = sorted(util.gatherTodaysEvents(self), key=attrgetter('start','Title')) 
       
        index = 700
        i = 0
        for brain in brains:
            pdf.rect(45, index-30, 510, 42, stroke=1, fill=0) #Schedule List Rectangles
            if util.isPublic(self,brain.id):
                title = brain.Title
            else:
                title = "Private Group"
                
            pdf.setFont("Helvetica-Bold", 17)
            pdf.drawString(50, index-5, DateTime(brain.start).strftime("%I:%M %p").lower() +
                                        " - " + DateTime(brain.end).strftime("%I:%M %p").lower() +
                                        " : " + title)
            pdf.setFont("Helvetica", 17)
            l = self.locationLookup(brain.location)
            pdf.drawString(50, index-25, "Location: " + l['Name'] + " - " + l['DirectionsShort'])
            
            index -= 42
            i += 1
            if i == 13:
                pdf.setFont("Helvetica", 17)
                pdf.drawCentredString(300, index-5, "See Website For More Study Groups!")
                break
        
        pdf.setFont("Helvetica-Bold", 28)
        pdf.drawCentredString(300, 90, "Use GroupFinder to Reserve a Study Space.")
        pdf.setFont("Helvetica", 24)
        pdf.drawCentredString(300, 60, "http://www.uwosh.edu/library/groupfinder")
        
        pdf = self.tableFooter(pdf)
        
        pdf.showPage() #next page, finalize last page.
        pdf.save() #save the pdf content
        return response #return response with hooked pdf.
开发者ID:uwosh,项目名称:uwosh.librarygroupfinder,代码行数:59,代码来源:print.py

示例7: test_03_draw

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [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

示例8: make_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [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

示例9: CorrectingInvoice

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
class CorrectingInvoice(SimpleInvoice):
    def gen(self, filename):
        self.TOP = 260
        self.LEFT = 20
        self.filename = filename

        pdfmetrics.registerFont(TTFont('DejaVu', FONT_PATH))
        pdfmetrics.registerFont(TTFont('DejaVu-Bold', FONT_BOLD_PATH))

        self.pdf = Canvas(self.filename, pagesize = letter)
        self.addMetaInformation(self.pdf)

        self.pdf.setFont('DejaVu', 15)
        self.pdf.setStrokeColorRGB(0, 0, 0)

        # Texty
        self.drawMain()
        self.drawTitle()
        self.drawProvider(self.TOP - 10,self.LEFT + 3)
        self.drawClient(self.TOP - 35,self.LEFT + 91)
        self.drawPayment(self.TOP - 47,self.LEFT + 3)
        self.drawCorretion(self.TOP - 73,self.LEFT)
        self.drawItems(self.TOP - 82,self.LEFT)
        self.drawDates(self.TOP - 10,self.LEFT + 91)

        #self.pdf.setFillColorRGB(0, 0, 0)

        self.pdf.showPage()
        self.pdf.save()

    def drawTitle(self):
        # Up line
        self.pdf.drawString(self.LEFT*mm, self.TOP*mm, self.invoice.title)
        self.pdf.drawString((self.LEFT + 90) * mm,
            self.TOP*mm,
            _(u'Correcting document: %s') %
            self.invoice.number)


    def drawCorretion(self,TOP,LEFT):
        self.pdf.setFont('DejaVu', 8)
        self.pdf.drawString(LEFT * mm, TOP * mm, _(u'Correction document for invoice: %s') % self.invoice.variable_symbol)
        self.pdf.drawString(LEFT * mm, (TOP - 4) * mm, _(u'Reason to correction: %s') % self.invoice.reason)
开发者ID:bcoding,项目名称:InvoiceGenerator,代码行数:45,代码来源:pdf.py

示例10: Canvas

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
from reportlab.lib.units import mm, cm

c = Canvas("04_03_low_level_pdf_operations_II.pdf", pagesize=(210*mm, 297*mm))
text_file = open("04_02_The_Raven.txt")
text = (l.strip() for l in text_file if l.strip())

c.setFontSize(10)
leading = 14 # line spacing.

c.saveState()

# translate halfway across page
c.translate(105*mm, 0) 

# draw a light grey vertical line 
c.setStrokeColorRGB(255, 0, 0)
c.line(0, 0, 0, 297*mm)

# move up the page
c.translate(0, 260*mm)

c.drawString(-100*mm, 0, "Canvas.drawString")
c.translate(0, -leading)
for i in range(2):
    c.translate(0, -leading)
    c.drawString(0, 0, text.next())

c.translate(0, -20*mm)
c.drawString(-100*mm, 0, "Canvas.drawCentredString")
c.translate(0, -leading)
for i in range(2):
开发者ID:IanWitham,项目名称:NZPUG-Reportlab-Demo-files,代码行数:33,代码来源:04_01_low_level_pdf_operations_II.py

示例11: bid_sheets

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
def bid_sheets ( pieces, output ):

    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    pdfmetrics.registerFont(TTFont(*settings.ARTSHOW_BARCODE_FONT))

    c = Canvas(output,pagesize=letter)

    pdf = PdfReader ( settings.ARTSHOW_BLANK_BID_SHEET )
    xobj = pagexobj ( pdf.pages[0] )
    rlobj = makerl ( c, xobj )
    
    nfs_pdf = PdfReader ( settings.ARTSHOW_BLANK_NFS_SHEET )
    nfs_xobj = pagexobj ( nfs_pdf.pages[0] )
    nfs_rlobj = makerl ( c, nfs_xobj )

    sheet_offsets = [
        (0,5.5),
        (4.25,5.5),
        (0,0),
        (4.25,0),
        ]

    sheets_per_page = len(sheet_offsets)
    sheet_num = 0
    pieceiter = iter(pieces)
    if artshow_settings.ARTSHOW_BID_SHEET_PRECOLLATION:
        pieceiter = precollate_pieces(pieceiter)
    last_artist = None
    
    try:
        piece = pieceiter.next ()
        while True:
            try:
                for sheet_num in range(sheets_per_page):
                    if artshow_settings.ARTSHOW_BID_SHEET_PRECOLLATION:
                        if piece is None:
                            piece = pieceiter.next()
                            continue
                    else:
                        if piece.artist != last_artist and sheet_num != 0:
                            continue
                    c.saveState ()
                    c.translate ( sheet_offsets[sheet_num][0]*inch, sheet_offsets[sheet_num][1]*inch )
                    if piece.not_for_sale:
                        c.doForm ( nfs_rlobj )
                    else:
                        c.doForm ( rlobj )
                    c.saveState ()
                    c.setLineWidth ( 4 )
                    c.setFillColorRGB ( 1, 1, 1 )
                    c.setStrokeColorRGB ( 1, 1, 1 )
                    c.roundRect ( 1.1875*inch, 4.4375*inch, 1.75*inch, 0.5*inch, 0.0675*inch, stroke=True, fill=True )
                    c.restoreState ()
                    text_into_box ( c, u"*A"+unicode(piece.artist.artistid)+u"P"+unicode(piece.pieceid)+u"*", 1.3125, 4.6, 2.8125, 4.875, fontSize=13, style=barcode_style )
                    text_into_box ( c, "Artist "+unicode(piece.artist.artistid), 1.25, 4.4375, 2.0, 4.625 )
                    text_into_box ( c, "Piece "+unicode(piece.pieceid), 2.125, 4.4375, 2.875, 4.625 )
                    text_into_box ( c, piece.artist.artistname(), 1.125, 4.125, 3.875, 4.375 )
                    text_into_box ( c, piece.name, 0.75, 3.8125, 3.875, 4.0625 )
                    if piece.not_for_sale:
                        text_into_box ( c, piece.media, 0.875, 3.5, 2.375, 3.75 )
                    else:
                        text_into_box ( c, piece.media, 0.875, 3.5, 3.875, 3.75 )
                        text_into_box ( c, piece.not_for_sale and "NFS" or unicode(piece.min_bid), 3.25, 2.625, 3.75, 3.0 )
                        text_into_box ( c, piece.buy_now and unicode(piece.buy_now) or "N/A", 3.25, 1.9375, 3.75, 2.3125 )
                        text_into_box ( c, "X", 3.375, 0.375, 3.5625, 0.675, style=left_align_style, fontSize=16 )      
                    c.restoreState ()
                    last_artist = piece.artist
                    piece = pieceiter.next ()
            finally:
                c.showPage ()
    except StopIteration:
        pass

    c.save ()
开发者ID:chmarr,项目名称:artshow-fc2013,代码行数:77,代码来源:preprint.py

示例12: to_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [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

示例13: Address

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [as 别名]
class Invoice:
	client = Address()
	provider = Address()
	items = []
	title = "Faktura"
	vs = "00000000"
	creator = ""
	sign_image = None
	payment_days = 14
	paytype = "Převodem"

	pdffile = None

	def __init__(self):
		self.TOP = 260
		self.LEFT = 20

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

		self.pdffile = NamedTemporaryFile(delete=False)
		
		self.pdf = Canvas(self.pdffile.name, pagesize = letter)
		self.pdf.setFont("DejaVu", 15)
		self.pdf.setStrokeColorRGB(0, 0, 0)

	def __del__(self):
		if os.path.isfile(self.pdffile.name):
			os.unlink(self.pdffile.name)

	#############################################################
	## Setters
	#############################################################
	
	def setClient(self, address):
		self.client = address

	def setProvider(self, address):
		self.provider = address

	def setTitle(self, value):
		self.title = value
		
	def setVS(self, value):
		self.vs = value

	def setCreator(self, value):
		self.creator = value

	def setPaytype(self, value):
		self.paytype = value

	def setPaymentDays(self, value):
		self.payment_days = int(value)

	def addItem(self, item):
		self.items.append(item)

	#############################################################
	## Getters
	#############################################################

	def getContent(self):
		# Texty
		self.drawMain()
		self.drawProvider(self.TOP-10,self.LEFT+3)
		self.drawClient(self.TOP-30,self.LEFT+91)
		self.drawPayment(self.TOP-47,self.LEFT+3)
		self.drawItems(self.TOP-80,self.LEFT)
		self.drawDates(self.TOP-10,self.LEFT+91)

		#self.pdf.setFillColorRGB(0, 0, 0)

		self.pdf.showPage()
		self.pdf.save()

		f = open(self.pdffile.name)
		data = f.read()
		f.close()

		os.unlink(self.pdffile.name)

		return data

	#############################################################
	## Draw methods
	#############################################################

	def drawMain(self):
		# Horní lajna
		self.pdf.drawString(self.LEFT*mm, self.TOP*mm, self.title)
		self.pdf.drawString((self.LEFT+100)*mm, self.TOP*mm, "Variabilní symbol: %s" % self.vs)

		# Rámečky
		self.pdf.rect((self.LEFT)*mm, (self.TOP-68)*mm, (self.LEFT+156)*mm, 65*mm, stroke=True, fill=False)

		path = self.pdf.beginPath()
		path.moveTo((self.LEFT+88)*mm, (self.TOP-3)*mm)
		path.lineTo((self.LEFT+88)*mm, (self.TOP-68)*mm)
		self.pdf.drawPath(path, True, True)

#.........这里部分代码省略.........
开发者ID:MechanisM,项目名称:InvoiceGenerator,代码行数:103,代码来源:generator.py

示例14: get

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [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

示例15: render

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColorRGB [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,
开发者ID:dennisjameslyons,项目名称:maze,代码行数:70,代码来源:pdf.py


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