本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.rect方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.rect方法的具体用法?Python Canvas.rect怎么用?Python Canvas.rect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.rect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SquareTest
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
class SquareTest(unittest.TestCase):
""" Construct and draw image with ColorSpiral colours placed in a
square, with jitter
"""
def setUp(self):
""" Set up canvas for drawing"""
output_filename = os.path.join("Graphics", "square_test.pdf")
self.c = Canvas(output_filename, pagesize=(500, 500))
def test_colorspiral(self):
""" Set of 625 colours, with jitter, using get_colors()."""
boxedge = 20
boxes_per_row = 25
rows = 0
for i, c in enumerate(get_colors(625)):
self.c.setFillColor(c)
x1 = boxedge * (i % boxes_per_row)
y1 = rows * boxedge
self.c.rect(x1, y1, boxedge, boxedge, fill=1, stroke=0)
if not (i+1) % boxes_per_row:
rows += 1
self.finish()
def finish(self):
""" Clean up and save image."""
self.c.save()
示例2: generateNumberedPages
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def generateNumberedPages(numPages, pageSize, orientation, bgColor, outPath):
"Generate a 10 page document with one big number per page."
if orientation == "landscape":
pageSize = landscape(pageSize)
canv = Canvas(outPath, pagesize=pageSize)
for i in range(numPages):
canv.setFont("Helvetica", 500)
text = u"%s" % i
if i % 2 == 0:
canv.setStrokeColor(bgColor)
canv.setFillColor(bgColor)
canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True)
canv.setFillColor(black)
elif i % 2 == 1:
canv.setStrokeColor(black)
canv.setFillColor(black)
canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True)
canv.setFillColor(bgColor)
if orientation == "portrait":
canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.3, u"%s" % i)
elif orientation == "landscape":
canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.21, u"%s" % i)
canv.showPage()
canv.save()
示例3: test3
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [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)
示例4: generateOfficePDF
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [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.
示例5: generateEntrancePDF
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [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.
示例6: rect
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def rect(path, width, height, radius=None, margin=0.1*inch):
canvas = Canvas(path, pagesize=(width + 2*margin, height + 2*margin))
set_vector_cut(canvas)
if radius:
canvas.roundRect(margin, margin, width, height, radius)
else:
canvas.rect(margin, margin, width, height)
canvas.showPage()
canvas.save()
示例7: badge
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def badge():
name = request.form['name'][:MAX_CHARS_PER_LINE] if 'name' in request.form else ''
name2 = request.form['name2'][:MAX_CHARS_PER_LINE] if 'name2' in request.form else ''
nick = request.form['nick'][:MAX_CHARS_PER_LINE] if 'nick' in request.form else ''
community = request.form['community'][:MAX_CHARS_PER_LINE] if 'community' in request.form else ''
pdf = BytesIO()
c = Canvas(pdf, pagesize=(BADGE_W, BADGE_H))
c.translate(ORIGIN_X, ORIGIN_Y)
ico_center = 7*mm
offset = HEIGHT+2*mm
c.setFillGray(0.66)
c.setFont('Awesome', 42)
c.drawCentredString(ico_center, offset-42*pica/12, '\uf007')
c.setFont('Awesome', 38)
c.drawCentredString(ico_center, offset-(2*42+40)*pica/12, '\uf1fa')
c.drawCentredString(ico_center, offset-(2*42+2*40)*pica/12, '\uf041')
txt_start = 15*mm
c.setFillGray(0.0)
c.setFont('LeagueGothic', 42)
c.drawString(txt_start, offset-42*pica/12, name)
c.drawString(txt_start, offset-2*42*pica/12, name2)
c.setFont('LeagueGothic', 38)
c.drawString(txt_start, offset-(2*42+40)*pica/12, nick)
c.drawString(txt_start, offset-(2*42+2*40)*pica/12, community)
evt_width = 38*pica/12
evt_start = WIDTH - evt_width
img_width = 20*mm
img_start = evt_start - img_width
c.drawImage(path.join(path.dirname(__file__), 'images/ffrhein_logo_claim_line_rot.png'), img_start, 0, img_width, HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')
c.rotate(90)
c.rect(0, -WIDTH, HEIGHT, evt_width, 0, 1)
c.setFillGray(1.0)
c.drawCentredString(HEIGHT/2, -WIDTH+MARGIN_R, 'routing days')
c.showPage()
c.save()
_print(pdf.getvalue())
pdf.close()
# response = make_response('Meh')
# response.headers['Content-Type'] = 'text/plain'
# return response
return redirect('/badge/printing.html')
示例8: test_03_draw
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [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()
示例9: _build_omr_layer
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def _build_omr_layer(marks):
padding_x = 4.2 * mm
padding_y = 8.5 * mm
top_mark_x = 7 * mm
top_mark_y = 220 * mm
mark_y_spacing = 4 * mm
mark_width = 6.5 * mm
marks_height = (len(marks) - 1) * mark_y_spacing
logger.info('Mailer DS-75i OMR Settings: 1={} 2={}'.format(
(297 * mm - top_mark_y) / mm,
(top_mark_x + mark_width / 2) / mm + 0.5
))
omr_buffer = StringIO.StringIO()
omr_canvas = Canvas(omr_buffer)
omr_canvas.setLineWidth(0.2 * mm)
# add a white background for the omr code
omr_canvas.setFillColor(white)
omr_canvas.rect(
x=top_mark_x - padding_x,
y=top_mark_y - marks_height - padding_y,
width=mark_width + 2 * padding_x,
height=marks_height + 2 * padding_y,
fill=True,
stroke=False
)
for offset, mark in enumerate(marks):
mark_y = top_mark_y - offset * mark_y_spacing
if mark:
omr_canvas.line(top_mark_x, mark_y,
top_mark_x + mark_width, mark_y)
# Close the PDF object cleanly.
omr_canvas.showPage()
omr_canvas.save()
# move to the beginning of the StringIO buffer
omr_buffer.seek(0)
omr_pdf = PdfFileReader(omr_buffer)
return omr_pdf.getPage(0)
示例10: test_05_coordinates
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def test_05_coordinates(self):
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import inch
from reportlab.lib.colors import pink, black, red, blue, green
c = Canvas('demo.pdf', pagesize=A4)
c.translate(inch,inch)
c.setStrokeColor(pink)
c.grid([1*inch,2*inch,3*inch,4*inch],[0.5*inch, 1*inch, .5*inch, 2*inch, 2.5*inch])
c.setFont("Times-Roman", 20)
c.drawString(0,0, "(0,0) the Origin")
c.drawString(2.5*inch, 1*inch, "(2.5,1) in inches")
c.drawString(4*inch, 2.5*inch, "(4,2.5)")
c.setFillColor(red)
c.rect(0,2*inch,0.2*inch, 0.3*inch, fill=1)
c.setFillColor(green)
c.circle(4.5*inch, 0.4*inch, 0.2*inch, fill=1)
c.showPage()
c.save()
示例11: genTestFile
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def genTestFile(path, numPages):
"Generate a PDF doc with *very* big page numbers on all pages."
size = landscape(A4)
canv = Canvas(path, pagesize=size)
for i in range(numPages):
canv.setFont("Helvetica", size[1]*1.2)
x, y = size[0]/2.0, size[1]*0.1
text = u"%s" % i
if i % 2 == 1:
canv.setStrokeColor(black)
canv.setFillColor(black)
canv.rect(0, 0, size[0], size[1], fill=True)
if i % 2 == 1:
canv.setFillColor(white)
else:
canv.setFillColor(black)
canv.drawCentredString(x, y, text)
canv.showPage()
canv.save()
示例12: createMarkedPDF
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [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)
示例13: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def test0(self):
"This should open in full screen mode."
import os
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.colors import PCMYKColor, PCMYKColorSep
filename = 'test_pdfgen_overprint.pdf'
desc = "Overprint/knockout tests for ReportLab library"
black = PCMYKColor(0,0,0,100)
cyan = PCMYKColorSep(100,0,0,0,spotName='myCyan')
magenta = PCMYKColorSep(0,100,0,0,spotName='myMagenta')
c = Canvas(filename)
c.setFillColor(black)
c.setFont('Helvetica', 20)
c.drawString(100, 700, desc)
c.setFont('Helvetica', 10)
c.drawString(100, 670, "To view is page properly you probably need to enable 'overprint preview' in Acrobat Reader")
c.drawString(100, 658, "or use a tool like Illustrator, Quark or Acrobat to view separated plates. Starting in")
c.drawString(100, 646, "Acrobat Reader 9 there is a setting that lets you turn on the overprint preview, although")
c.drawString(100, 634, "it's not on by default (Preferences > Page Display > Use Overprint Preview: Always).")
c.drawString(100, 616, "In the top example, the magenta rectangle overprints the cyan one. In the lower one, it")
c.drawString(100, 604, "'knocks out' the cyan underneath which is the default in PDF. This means that the overlap")
c.drawString(100, 592, "area of the first example should show blue, because the two colours merge. However, in many")
c.drawString(100, 580, "PDF viewers and cheap printers, both examples will probably look the same - magenta")
c.drawString(100, 568, "rectangle knocks out part of the cyan one.")
c.drawString(100, 550, "If you can view the separated CMYK plates in a tool like Illustrator, on the cyan plate")
c.drawString(100, 538, "you should see the top rectangle as complete and the bottom one has a chunk knocked out of")
c.drawString(100, 526, "the top right corner.")
c.setFillOverprint(True)
c.setFillColor(cyan)
c.rect(100, 300, 200, 100, fill=True, stroke=False)
c.setFillColor(magenta)
c.rect(200, 350, 200, 100, fill=True, stroke=False)
c.setFillOverprint(False)
c.setFillColor(cyan)
c.rect(100, 100, 200, 100, fill=True, stroke=False)
c.setFillColor(magenta)
c.rect(200, 150, 200, 100, fill=True, stroke=False)
c.save()
assert os.path.exists(filename)
示例14: Address
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
#.........这里部分代码省略.........
# drawing.add(qrw)
# renderPDF.draw(drawing, self.pdf, self.TOP+25, self.LEFT+710)
# qrw.drawOn(self.pdf,self.TOP+45,(self.LEFT+735))
self.drawProvider(self.TOP-8,self.LEFT+3)
# self.drawClient(self.TOP-30,self.LEFT+91)
self.drawPayment(self.TOP-26,self.LEFT+3)
self.drawItems(self.TOP-45,self.LEFT)
self.drawDates(self.TOP-10,self.LEFT+91)
self.drawWatermark()
#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, "Invoice No.: %s" % self.vs)
# Rámečky
self.pdf.rect((self.LEFT)*mm, (self.TOP-38)*mm, (self.LEFT+156)*mm, 35*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-20)*mm)
self.pdf.drawPath(path, True, True)
path = self.pdf.beginPath()
path.moveTo((self.LEFT)*mm, (self.TOP-20)*mm)
path.lineTo((self.LEFT+88)*mm, (self.TOP-20)*mm)
self.pdf.drawPath(path, True, True)
path = self.pdf.beginPath()
path.moveTo((self.LEFT+88)*mm, (self.TOP-26)*mm)
path.lineTo((self.LEFT+176)*mm, (self.TOP-26)*mm)
self.pdf.drawPath(path, True, True)
path = self.pdf.beginPath()
path.moveTo((self.LEFT+88)*mm, (self.TOP-26)*mm)
path.lineTo((self.LEFT+88)*mm, (self.TOP-20)*mm)
self.pdf.drawPath(path, True, True)
def drawWatermark(self):
pass
def drawClient(self,TOP,LEFT):
self.pdf.setFont("DejaVu", 12)
self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Odběratel")
self.pdf.setFont("DejaVu", 8)
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)
示例15: __init__
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import rect [as 别名]
def __init__(self,
IDmodele=None,
taillePage=(210, 297),
listeValeurs=[],
margeHaut=10,
margeGauche=10,
margeBas = 10,
margeDroite=10,
espaceVertical=5,
espaceHorizontal=5,
nbre_copies=1,
AfficherContourEtiquette=True,
AfficherReperesDecoupe=True,
):
# ----------------------------------------------------------------------------------------------------------------------------------------
def AfficheReperesDecoupe():
if AfficherReperesDecoupe == True :
canvas.setStrokeColor( (0.9, 0.9, 0.9) )
canvas.setLineWidth(0.25)
# Repères de colonnes
for y1, y2 in [(hauteurPage*mm-4*mm, hauteurPage*mm-margeHaut*mm+2*mm), (4*mm, margeBas-2*mm)] :
x = margeGauche*mm
for numColonne in range(0, nbreColonnes):
canvas.line(x, y1, x, y2)
x += largeurEtiquette*mm
canvas.line(x, y1, x, y2)
x += espaceHorizontal*mm
# Repères de lignes
for x1, x2 in [(4*mm, margeGauche*mm-2*mm), (largeurPage*mm-4*mm, largeurPage*mm-margeDroite*mm+2*mm)] :
y = hauteurPage*mm - margeHaut*mm
for numLigne in range(0, nbreLignes):
canvas.line(x1, y, x2, y)
y -= hauteurEtiquette*mm
canvas.line(x1, y, x2, y)
y -= espaceVertical*mm
# -----------------------------------------------------------------------------------------------------------------------------------------
largeurPage = taillePage[0]
hauteurPage = taillePage[1]
# Initialisation du modèle de document
modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
largeurEtiquette = modeleDoc.dictInfosModele["largeur"]
hauteurEtiquette = modeleDoc.dictInfosModele["hauteur"]
# Calcul du nbre de colonnes et de lignes
nbreColonnes = (largeurPage - margeGauche - margeDroite + espaceHorizontal) / (largeurEtiquette + espaceHorizontal)
nbreLignes = (hauteurPage - margeHaut - margeBas + espaceVertical) / (hauteurEtiquette + espaceVertical)
# Initialisation du PDF
nomDoc = FonctionsPerso.GenerationNomDoc("ETIQUETTES", "pdf")
canvas = Canvas(nomDoc, pagesize=(largeurPage*mm, hauteurPage*mm))
# Création des étiquettes
numColonne = 0
numLigne = 0
for dictValeurs in listeValeurs :
for num_copie in range(0, nbre_copies) :
x = margeGauche + ((largeurEtiquette + espaceHorizontal) * numColonne)
y = hauteurPage - margeHaut - hauteurEtiquette - ((hauteurEtiquette + espaceVertical) * numLigne)
# Positionnement sur la feuille
canvas.saveState()
canvas.translate(x*mm, y*mm)
# Création du clipping
p = canvas.beginPath()
canvas.setStrokeColor( (1, 1, 1) )
canvas.setLineWidth(0.25)
p.rect(0, 0, largeurEtiquette*mm, hauteurEtiquette*mm)
canvas.clipPath(p)
# Dessin de l'étiquette
modeleDoc.DessineFond(canvas, dictChamps=dictValeurs)
etat = modeleDoc.DessineTousObjets(canvas, dictChamps=dictValeurs)
if etat == False :
return
# Dessin du contour de l'étiquette
if AfficherContourEtiquette == True :
canvas.setStrokeColor( (0, 0, 0) )
canvas.setLineWidth(0.25)
canvas.rect(0, 0, largeurEtiquette*mm, hauteurEtiquette*mm)
canvas.restoreState()
# Saut de colonne
numColonne += 1
# Saut de ligne
if numColonne > nbreColonnes - 1 :
numLigne += 1
numColonne = 0
# Saut de page
if numLigne > nbreLignes - 1 :
AfficheReperesDecoupe()
canvas.showPage()
numLigne = 0
#.........这里部分代码省略.........