本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.restoreState方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.restoreState方法的具体用法?Python Canvas.restoreState怎么用?Python Canvas.restoreState使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.restoreState方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def make_pdf(outfn, xobjpairs):
canvas = Canvas(outfn)
for xobjlist in xobjpairs:
x = y = 0
for xobj in xobjlist:
x += xobj.BBox[2]
y = max(y, xobj.BBox[3])
canvas.setPageSize((x,y))
# Handle blank back page
if len(xobjlist) > 1 and xobjlist[0] == xobjlist[-1]:
xobjlist = xobjlist[:1]
x = xobjlist[0].BBox[2]
else:
x = 0
y = 0
for xobj in xobjlist:
canvas.saveState()
canvas.translate(x, y)
canvas.doForm(makerl(canvas, xobj))
canvas.restoreState()
x += xobj.BBox[2]
canvas.showPage()
canvas.save()
示例2: test_06_fontsize
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def test_06_fontsize(self):
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import inch
from reportlab.lib.colors import red, magenta
c = Canvas('demo.pdf', pagesize=A4)
c.translate(inch, inch)
c.setFont("Times-Roman", 20)
c.setFillColor(red)
c.saveState()
c.drawCentredString(2.75*inch, 2.5*inch,"Font size excmples")
c.setFillColor(magenta)
size = 7
x = 2.3 * inch
y = 1.3 * inch
for line in range(7):
c.setFont("Helvetica", size)
c.drawRightString(x, y, "%s points" % size)
c.drawString(x,y, "test")
y = y-size*1.2
size = size+1.5
c.restoreState()
c.drawString(0,0, "%s" % c.getAvailableFonts())
c.showPage()
c.save()
示例3: piece_stickers
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def piece_stickers ( pieces, output ):
c = Canvas ( output, pagesize=letter )
x_range = range(3)
y_range = range(10)
pieceiter = iter(pieces)
last_artist = None
try:
piece = pieceiter.next ()
while True:
try:
for y in range(10):
for x in range(3):
if piece.artist != last_artist and x != 0:
continue
message = "<b>%s</b><br/><i>%s</i><br/>%s" % ( piece.name, piece.artist.artistname(), piece.media )
c.saveState ()
c.translate ( (3/16.0 + x * (2+3/4.0)) * inch, (9.5 - y) * inch )
text_into_box ( c, message, 0.2, 0.1, 2.475, 0.9, style=piece_sticker_style, escape_text=False, fontSize=12 )
c.restoreState ()
last_artist = piece.artist
piece = pieceiter.next ()
finally:
c.showPage ()
except StopIteration:
pass
c.save ()
示例4: _get_output_page
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def _get_output_page(self, output_infos):
inch = 72
buf = io.BytesIO()
canvas = Canvas(buf, pagesize=(8.5*inch, 11*inch))
for info in output_infos:
canvas.saveState()
x, y = info.translate
# We flip the y coordinate since that's how PDF programs give us
# the number of pixels from the top, not the bottom.
y = 11*inch - y
canvas.translate(x, y)
if info.rotate != 0:
canvas.rotate(info.rotate)
t = canvas.beginText()
t.setFont('Courier', 10)
t.setTextOrigin(0, 0)
t.textLines(info.text)
canvas.drawText(t)
canvas.restoreState()
canvas.save()
return PdfFileReader(buf).getPage(0)
示例5: test3
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [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)
示例6: _on_other_page
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def _on_other_page(self, canvas: Canvas, doc):
canvas.saveState()
canvas.setFont('OpenSans', 8)
canvas.drawRightString(self.pagesize[0] - 20 * mm, 10 * mm, pgettext("invoice", "Page %d") % (doc.page,))
for i, line in enumerate(self.invoice.footer_text.split('\n')[::-1]):
canvas.drawCentredString(self.pagesize[0] / 2, 25 + (3.5 * i) * mm, line.strip())
canvas.restoreState()
示例7: mailing_labels
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def mailing_labels ( artists, output ):
c = Canvas(output,pagesize=letter)
label_number = 0
for artist in artists:
column = label_number%3
row = label_number/3
c.saveState ()
c.translate ( 3/16.0*inch + column*(2+3/4.0)*inch, (9+1/2.0)*inch - row*inch )
text_into_box ( c, artist.person.get_mailing_label(), 0.1, 0.0, 2.5, 0.85, fontSize=14, style=left_align )
c.restoreState ()
label_number += 1
if label_number == 30:
c.showPage ()
label_number = 0
if label_number != 0:
c.showPage ()
c.save ()
示例8: Report
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
#.........这里部分代码省略.........
## Create the page number label; 'Page X of'
self.page_num = Field()
self.page_num.style.horizontal_alignment = alignment.RIGHT
self.page_num.style.vertical_alignment = alignment.TOP
self.page_num.width = self._working_width - 13
#self.page_num.style.color = (.6,.6,.6)
self.page_num.horizontal_padding = 0
self.page_num.style.size = 8
## Create the last page number label
self.last_page = Field()
#self.last_page.style.horizontal_alignment = alignment.LEFT
self.last_page.style.vertical_alignment = alignment.TOP
#self.last_page.width = self._working_width
#self.last_page.style.color = (.6,.6,.6)
self.last_page.horizontal_padding = 0
self.last_page.style.size = 8
## Objects to be drawn
self.draw_list = []
self._page_count = 1
#-----------------------------------------------------------------------Add
def add(self, item):
## Add any object that, duck-typingly, has a 'draw_some' method
self.draw_list.append(item)
#--------------------------------------------------------------------Create
def create(self):
self.canvas.setAuthor(self.author)
self.canvas.setTitle(self.title)
self.canvas.setSubject('Python Generated Report')
self._draw_header()
self._draw_footer()
vspace = self._working_height
left = self.left_margin
right = self.page_width - self.right_margin
for item in self.draw_list:
while True:
if vspace < 1:
self._start_new_page()
vspace = self._working_height
yoff = self.bottom_margin + vspace
used = item.draw_some(self.canvas, left, right, yoff, vspace)
if used == 0:
break
else:
vspace -= used
## Add the numbering for last page
## We have to do this as a PDF 'Form' object since we don't know in
## advance how many pages there will be.
self.canvas.beginForm('last_page')
self.canvas.saveState()
self.last_page.value = '%d' % self._page_count
self.last_page.draw(self.canvas,
self._right_edge - ( self.right_margin + 14),
self.bottom_margin * .65)
self.canvas.restoreState()
self.canvas.endForm()
## Close the PDF
self.canvas.save()
#----------------------------------------------------------------Start Page
def _start_new_page(self):
self._page_count += 1
self.canvas.showPage()
self._draw_header()
self._draw_footer()
#---------------------------------------------------------------Draw Header
def _draw_header(self):
self.header.value = self.title
self.header.draw(self.canvas, self.left_margin, self._top_edge -
(self.top_margin * .65) )
#---------------------------------------------------------------Draw Footer
def _draw_footer(self):
self.footer.value = self.author
self.footer.draw(self.canvas, self.left_margin,
self.bottom_margin * .65)
self.date.draw(self.canvas, self.left_margin,
self.bottom_margin * .65)
self.page_num.value = 'Page %d of ' % self._page_count
self.page_num.draw(self.canvas, self.left_margin,
self.bottom_margin * .65)
self.canvas.doForm('last_page')
示例9: bl
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
if verbose:
print "%s: bl (%d,%d), tr (%d,%d), size (%d,%d), dpi (%g,%g)" % (
image["filename"],
image["x"], image["y"],
image["x"]+image["w"], image["y"]+image["h"],
image["w"], image["h"],
image["pw"] * 72.0 / image["w"],
image["ph"] * 72.0 / image["h"],
)
# Rotate.
rotates = [
lambda x,y,w,h: (x,y,w,h), # no rotation
lambda x,y,w,h: (y, -x-w, h, w), # anticlockwise
lambda x,y,w,h: (-x-w, -y-h, w, h), # 180
lambda x,y,w,h: (-y-h, x, h, w), # clockwise
]
image["x"], image["y"], image["w"], image["h"] = (
rotates[angle](image["x"], image["y"], image["w"], image["h"])
)
# And draw the image.
pdf.saveState()
pdf.rotate(angle * 90)
pdf.drawImage(img, image["x"], image["y"], image["w"], image["h"])
pdf.restoreState()
pdf.showPage()
pdf.save()
示例10: draw_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def draw_pdf(buffer, member, details):
from members.models import Member
""" Draws the invoice """
canvas = Canvas(buffer, pagesize=A4)
canvas.translate(0, 29.7 * cm)
canvas.setFont('Helvetica', 10)
canvas.saveState()
draw_header(canvas)
canvas.restoreState()
canvas.saveState()
draw_footer(canvas)
canvas.restoreState()
canvas.saveState()
draw_address(canvas)
canvas.restoreState()
# member address (aka head-of-list contact details)
textobject = canvas.beginText(13 * cm, -3.5 * cm)
textobject.textLine(member.head_of_list.first_name + ' ' + unicode.upper(member.head_of_list.last_name))
if member.type == Member.ORG:
textobject.textLine(member.organisation.name)
textobject.textLine(member.address.street)
textobject.textLine(member.address.postal_code + ' ' + member.address.town)
textobject.textLine(get_country_from_address(member.address))
canvas.drawText(textobject)
# title
canvas.setFont('Helvetica', 14)
textobject = canvas.beginText(5.5 * cm, -6.75 * cm)
textobject.textLine(u'Invoice for the CLUSIL membership for %s' % details['YEAR'])
canvas.drawText(textobject)
canvas.setFont('Helvetica', 10)
# invoice summary
textobject = canvas.beginText(1.5 * cm, -8 * cm)
textobject.textLine(u'Invoice ID: %s' % details['ID'])
textobject.textLine(u'Invoice Date: %s' % details['DATE'])
canvas.drawText(textobject)
# membership summary
textobject = canvas.beginText(1.5 * cm, -9.5 * cm)
textobject.textLine(u'Membership type: %s' % Member.MEMBER_TYPES[member.type][1])
if member.type == Member.ORG:
textobject.textLine(u'Head-of-list: %s' % details['FULLNAME'])
else:
textobject.textLine(u'Member: %s' % details['FULLNAME'])
if member.type == Member.ORG:
textobject.textLine(u'Nb of registered people: %i' % member.lvl)
canvas.drawText(textobject)
# list of people
textobject = canvas.beginText(2.5 * cm, -11 * cm)
#head-of-list:
textobject.textLine(' - ' + member.head_of_list.first_name + ' ' + unicode.upper(member.head_of_list.last_name))
if member.type == Member.ORG:
#delegate:
if member.delegate:
textobject.textLine(' - ' + member.delegate.first_name + ' ' + unicode.upper(member.delegate.last_name))
for u in member.users.all():
textobject.textLine(' - ' + u.first_name + ' ' + unicode.upper(u.last_name))
canvas.drawText(textobject)
offset = member.users.count() / 3
# fee
textobject = canvas.beginText(2.5 * cm, -(14+offset) * cm)
textobject.textLine(u'Total amount of the CLUSIL membership fee: %s' % unicode(details['AMOUNT']) + u' EUR')
canvas.drawText(textobject)
# thank you message
textobject = canvas.beginText(1.5 * cm, -(16+offset) * cm)
textobject.textLine(u'Thank you for being a CLUSIL member.')
textobject.textLine(u'Please be so kind and pay the membership fee within the next two weeks.')
canvas.drawText(textobject)
canvas.showPage()
canvas.save()
示例11: Report
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
class Report(object):
render = {'table': render.TableRender,
'pie': render.PieRender,
'histo': render.HistoRender,
'line': render.LineRender,
'gantt': render.GanttRender,
}
margin = 30
big_title_height = 40
title_height = 50
frame_margin = 5
frag_title_height = 20
frag_margin = 9
edenwall_height = 60
def __init__(self, title, enterprise, interval, logo):
self.title = title
self.enterprise = enterprise
self.interval = interval
self.logo = logo
self.width, self.height = A4
self.buf = StringIO()
self.canvas = Canvas(self.buf, pagesize=A4)
self.page_title = ''
self.page_rows = []
self.page_frags = 0
self.page_num = 1
# Build story.
self.canvas.saveState()
self.canvas.setStrokeColor(colors.RED)
self.canvas.setLineWidth(2)
self.canvas.roundRect(self.margin, self.edenwall_height + self.margin, self.width, self.height, 20, stroke=1, fill=0)
self.canvas.setFillColor(colors.GREEN2)
self.canvas.setStrokeColor(colors.GREEN1)
self.canvas.roundRect(- self.margin, - self.margin, self.width - self.margin, self.edenwall_height + self.margin,
20, stroke=1, fill=1)
# TODO do not hardcode this values.
img = Image('/var/lib/ufwi_rpcd/edenwall.png', 1209 / (300/(self.edenwall_height-self.margin/2)), self.edenwall_height-self.margin/2)
img.drawOn(self.canvas, self.margin, self.margin/4)
self.canvas.restoreState()
if self.logo:
img = Image(StringIO(self.logo))
img._setup_inner()
img.drawOn(self.canvas, (self.width - self.margin)/2 - img.drawWidth/2, 2*self.height/3)
offset = 40
self.canvas.setFillColor(black)
self.canvas.setFont("Helvetica-Bold", self.big_title_height)
self.canvas.drawCentredString((self.width-self.margin)/2, self.height/3, title)
self.canvas.setFont("Helvetica-Bold", self.frag_title_height)
self.canvas.drawString(offset, self.height - offset, enterprise)
def __getstate__(self):
d = self.__dict__.copy()
del d['canvas']
return d
def __setstate__(self, d):
self.__dict__ = d
self.canvas = Canvas(self.buf, pagesize=A4)
def build(self):
self.canvas.showPage()
self.canvas.save()
return self.buf
def addGraph(self, title, columns, table, render):
frags = self.page_frags
for row, cols in enumerate(self.page_rows):
frags -= cols
if frags < 0:
break
if frags >= 0:
self.addPage(self.page_title, self.page_rows)
col = 0
row = 0
cols = self.page_rows[0]
else:
col = - frags - 1
# You can read that? Not me.
x = self.margin + self.frame_margin + (col+1) * self.frag_margin + \
col * (self.width - 2*self.margin - 2*self.frame_margin - (col+1)*self.frag_margin) / cols
y = self.margin + self.frame_margin + (row+1) * self.frag_margin + \
row * (self.height - 2*self.margin - 2*self.frame_margin - self.title_height - 2*self.frag_margin) / len(self.page_rows)
width = (self.width - 2*self.margin - 2*self.frame_margin - 2*cols*self.frag_margin) / cols
height = (self.height - 2*self.margin - 2*self.frame_margin - self.title_height - 2*len(self.page_rows)*self.frag_margin) / len(self.page_rows)
self.canvas.setFillColor(colors.GREEN1)
self.canvas.roundRect(x, y, width, height, 7, stroke=0, fill=1)
self.canvas.setFillColor(white)
x += 1
#.........这里部分代码省略.........
示例12: main
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def main():
pdfmetrics.registerFont(TTFont('Dosis', 'Dosis-Medium.ttf'))
stars = []
with open('bsc5.dat', 'rb') as f:
for line in f:
line = '.' + line # switch to 1-based indexing
if not line[62].strip():
continue # skip coordinate-less novas
letter = intern(line[8:11])
if letter == ' ':
letter = None
h, m, s = float(line[61:63]), float(line[63:65]), float(line[65:69])
ra = (h + (m + s / 60.0) / 60.0) * tau / 24.0
d, m, s = float(line[69:72]), float(line[72:74]), float(line[76:78])
dec = (d + (m + s / 60.0) / 60.0) * tau / 360.0
mag = float(line[103:108])
stars.append((letter, ra, dec, mag))
h, w = 48, 96
c = Canvas('logo.pdf', pagesize=(w, h))
c.setFillColor('white')
c.rect(0, 0, w, h, stroke=0, fill=1)
c.setFillColor(bright_star_color)
rotation = 10.0 * tau / 360.0
# magscale = 0.1
# For 10 degrees:
x_offset = 96 -33.5
y_offset = h +37.5
# For 15 degrees:
# x_offset = 96 -28.5
# y_offset = 96 +0.5
# for 45 degrees:
# x_offset = 96 -13.5
# y_offset = 96 -10
small_glyphs = []
c.setFont('Helvetica', 2)
for letter, ra, dec, mag in stars:
# if mag > 4.0:
# continue
d = - (dec - quarter_tau) * 100
ra += rotation
x = d * sin(ra)
y = d * cos(ra)
if y < -63.0 or y > -39.0:
continue
if x < -43.0 or x > 19.0:
continue
x += x_offset
y += y_offset
r = ((13.0 - mag) / 10.0) ** 4.0 #* magscale
r = min(r, 1.0)
if r < 0.5:
small_glyphs.append((x, y, r))
else:
if letter is not None:
c.saveState()
greek_letter, offset = greeks[letter]
c.setFillColor(greek_color)
c.drawString(x+offset, y+0.5, greek_letter)
if letter == 'Alp':
c.setFillColor(alpha_star_color)
c.circle(x, y, r, stroke=0, fill=1)
c.restoreState()
if letter != 'Alp':
c.circle(x, y, r, stroke=0, fill=1)
else:
c.circle(x, y, r, stroke=0, fill=1)
c.setFillColor(dim_star_color)
for x, y, r in small_glyphs:
c.circle(x, y, r, stroke=0, fill=1)
c.setFillColor(text_color) #, alpha=0.5)
c.setFont('Dosis', 24)
sw = c.stringWidth('Skyfield')
c.drawString(w // 2 - sw // 2, h - 40, 'Skyfield')
c.showPage()
with open('logo.pdf', 'wb') as f:
f.write(c.getpdfdata())
示例13: render
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [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()
示例14: gen_bill_ride_stuff
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def gen_bill_ride_stuff(ob):
buffer_ = BytesIO()
try:
tree = ET.fromstring(ob.xml_content.encode('utf8'))
except ET.ParseError:
tree = None
pagesize = A4
margin = inch, inch, inch, inch
canvas = Canvas(buffer_, pagesize=pagesize)
c = RenderStack(0, 0, pagesize[0], pagesize[1], margin=margin)
# p.roundRect(c.x(0), c.y(0), c.width(1), c.height(1), 3, stroke=1, fill=0)
# Print warnings
warnings = get_warning(ob)
if warnings:
canvas.saveState()
grey = 0.3
canvas.setFillColorCMYK(0, 0, 0, grey)
canvas.setStrokeColorCMYK(0, 0, 0, grey)
canvas.setFont("Helvetica", 50)
total_height = 60 * len(warnings)
canvas.translate(c.x(0.5), c.y(0.7))
canvas.rotate(45)
canvas.translate(0, total_height / 2)
for item in warnings:
canvas.drawCentredString(0, 0, item)
canvas.translate(0, -60)
canvas.restoreState()
def add_items(items, showBoundary=False):
f = Frame(c.x(0), c.y(0), c.width(1), c.height(1),
showBoundary=showBoundary,
leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
f.addFromList(items, canvas)
if items:
raise Exception("Does not fit - items left")
# Parameters
column_height = 0.3
column_width = 0.5
footer_height = 0.14
standard_separation = inch / 20
# styles
styles = getSampleStyleSheet()
small = styles['Normal'].clone("Smaller", fontSize=8)
normal = styles['Normal']
bigheader = styles['h2']
mediumheader = styles['h3']
smallheader = styles['h4']
with c.section(0, 1 - column_height, 1, 1):
# columna izquierda
with c.section(0, 0, column_width, 1,
margin=(0, 0, standard_separation, 0)):
if ob.company.get_logo():
with c.section(0, 0.5, 1, 1,
margin=standard_separation):
# logo
logo = ob.company.get_logo()
if logo:
add_items(
[get_image(logo.file.file.name, width=c.width(1), height=c.height(1))]
)
with c.section(0, 0, 1, column_width,
margin=standard_separation):
story = []
if ob.company.nombre_comercial:
story.append(Paragraph(ob.company.nombre_comercial,
bigheader))
story.append(Paragraph("Razon Social: {}".format(ob.company.razon_social),
normal))
else:
story.append(Paragraph("Razon Social: {}".format(ob.company.razon_social),
bigheader))
if ob.company.direccion_matriz != ob.punto_emision.establecimiento.direccion:
story.append(Paragraph(u"Dirección Matriz:",
normal))
story.append(Paragraph(ob.company.direccion_matriz,
small))
story.append(Paragraph(u"Dirección Sucursal:",
normal))
story.append(Paragraph(ob.punto_emision.establecimiento.direccion,
small))
else:
story.append(Paragraph(u"Dirección:",
normal))
story.append(Paragraph(ob.company.direccion_matriz,
small))
if ob.company.contribuyente_especial:
story.append(Paragraph("Contribuyente Especial: {}".format(ob.company.contribuyente_especial),
normal))
#.........这里部分代码省略.........
示例15: __call__
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import restoreState [as 别名]
def __call__(self, data):
"""
Generate the PDF
"""
icon = self.settings['icons'].get(data['issue_type'], self.settings['icons']['Unknown'])
priority_icon = self.settings['priority_icons'].get(data['priority'], self.settings['priority_icons']['Unknown'])
priority_color = self.settings['priority_colors'].get(data['priority'], self.settings['priority_colors']['Unknown'])
styles = self._getStyleSheet()
canvas = Canvas(self.output, pagesize=self.settings['pagesize'])
margin = self.settings['margin']
page_width, page_height = self.settings['pagesize']
frame_width = page_width-(margin*2)
frame_height = page_height-(margin*2)
main = Frame(margin, margin, frame_width, frame_height, showBoundary=0, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
footer = Frame(margin, margin, frame_width, frame_height, showBoundary=0, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
if data['border']:
canvas.setLineWidth(0.5)
canvas.rect(1, 1, page_width-2, page_height-2, stroke=1, fill=0)
# label the checkbox arrays with a rotated text label
canvas.saveState()
canvas.setFillColor((0.9, 0.9, 0.9))
canvas.setFont('Helvetica-Bold', 20)
canvas.translate(margin*2, margin*2)
canvas.rotate(15)
canvas.drawString(0, -10, "INTERRUPTED")
canvas.restoreState()
canvas.saveState()
canvas.setFillColor((0.9, 0.9, 0.9))
canvas.setFont('Helvetica-Bold', 20)
canvas.translate(frame_width/2+(inch*0.6), margin*2)
canvas.rotate(15)
canvas.drawString(0, -10, "BLOCKED")
canvas.restoreState()
######### use a table to hold the header
#
# +--------+-------------------------+-------+
# | ID | Reporter | Icon |
# | Type | Created Date | |
# +--------+-------------------------+-------+
#
# Illustrates the use of inline styling.
#
# @TODO: move the inline styles to the style sheet
header_data = [
[
Image(icon, inch*0.4, inch*0.4),
[
Paragraph('<para size="18"><b>%(issue_id)s</b></para>' % data, styles['BodyText']),
Spacer(1,2),
Paragraph('<para size="8">%(issue_type)s</para>' % data, styles['BodyText']),
],
[
Paragraph('<para size="16" alignment="center"><u>%(reporter)s</u></para>' % data, styles['BodyText']),
Spacer(1,2),
Paragraph('<para size="10" alignment="center"><b>Opened: %s</b></para>' % data['date'].strftime('%m/%d @ %I:%M %p'), styles['BodyText']),
],
# XBox(inch*0.4, inch*0.4, ""),
Image(priority_icon, inch*0.4, inch*0.4),
],
]
# set the alignment
header_style = TableStyle([
('ALIGNMENT', (0,0), (-1,-1), 'CENTER'),
('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
('LEFTPADDING', (0,0), (-1,-1), 3),
('RIGHTPADDING', (0,0), (-1,-1), 3),
('TOPPADDING', (0,0), (-1,-1), 3),
('BOTTOMPADDING', (0,0), (-1,-1), 3),
('BACKGROUND', (0,0), (-1,-1), priority_color),
('BOX', (0,0), (-1,-1), 0.5, black),
# exceptions for the first cell
('ALIGNMENT', (0,0), (0,0), 'LEFT'),
])
header = Table(header_data, colWidths=[ 0.6*inch, inch*1.2, None, 0.6*inch], style=header_style)
# The text of the story
story = Paragraph("<b>"+data['summary']+"</b>", styles['BodyText'])
# the text of the description - just the first 20 words
detail_words = data['detail'].split()
short_detail = " ".join(detail_words[:50])
if len(detail_words) > 50:
short_detail += '...'
details = KeepInFrame(frame_width, frame_height/3, [Paragraph(short_detail, styles['BodyText']),], mode="shrink", mergeSpace=0)
#.........这里部分代码省略.........