本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.setStrokeColor方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.setStrokeColor方法的具体用法?Python Canvas.setStrokeColor怎么用?Python Canvas.setStrokeColor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.setStrokeColor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generateNumberedPages
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [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()
示例2: test_05_coordinates
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [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()
示例3: genTestFile
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [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()
示例4: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
def test0(self):
"A basic document drawing some strings"
c = Canvas(outputfile('test_multibyte_jpn.pdf'))
c.setFont('Helvetica', 30)
c.drawString(100,700, 'Japanese Font Support')
c.setStrokeColor(colors.red)
#unicode font automatically supplies the encoding
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3'))
msg = u'\u6771\u4EAC : Unicode font, unicode input'
self.hDraw(c, msg, 'HeiseiMin-W3', 100, 600)
msg = u'\u6771\u4EAC : Unicode font, utf8 input'.encode('utf8')
self.hDraw(c, msg, 'HeiseiMin-W3', 100, 575)
# now try verticals - this is broken, not sure how to make it
# work in post Unicode world.
pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-V'))
c.setFont('HeiseiMin-W3-90ms-RKSJ-V', 16)
c.drawString(450, 650, '\223\214\213\236 vertical Shift-JIS')
height = c.stringWidth('\223\214\213\236 vertical Shift-JIS', 'HeiseiMin-W3-90ms-RKSJ-V', 16)
c.rect(450-8,650,16,-height)
pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','EUC-V'))
c.setFont('HeiseiMin-W3-EUC-V', 16)
c.drawString(475, 650, '\xC5\xEC\xB5\xFE vertical EUC')
height = c.stringWidth('\xC5\xEC\xB5\xFE vertical EUC', 'HeiseiMin-W3-EUC-V', 16)
c.rect(475-8,650,16,-height)
from reportlab.platypus.paragraph import Paragraph
from reportlab.lib.styles import ParagraphStyle
jStyle = ParagraphStyle('jtext',
fontName='HeiseiMin-W3',
fontSize=12,
wordWrap="CJK"
)
gatwickText = '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99\xe3\x81\x97\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'
gatwickText2= '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf<font color=red>\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90</font>\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88<link fg="blue" href="http://www.reportlab.com">\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99</link>\xe3\x81\x97\xe3\x81\xa6<u>\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99</u>\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'
c.setFont('HeiseiMin-W3', 12)
jPara = Paragraph(gatwickText, jStyle)
jPara.wrap(300, 200)
jPara.drawOn(c, 100, 220)
jPara = Paragraph(gatwickText2, jStyle)
jPara.wrap(300, 200)
jPara.drawOn(c, 100, 320)
c.setFillColor(colors.purple)
tx = c.beginText(100, 200)
tx.setFont('Helvetica', 12)
tx.textLines("""This document shows sample output in Japanese
from the Reportlab PDF library. This page shows the two fonts
available and tests our ability to measure the width of glyphs
in both horizontal and vertical writing, with proportional and
fixed-width characters. The red boxes should be the same width
(or height) as the character strings they surround.
The next pages show more samples and information.
""")
c.drawText(tx)
c.setFont('Helvetica',10)
c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())
c.showPage()
c.setFont('Helvetica', 30)
c.drawString(100,700, 'Japanese TrueType Font Support')
msg = u'\u6771\u4EAC : Unicode font'.encode('utf8')
msg2 = u'utf8 input 0123456789 ABCDEF'.encode('utf8')
from reportlab.pdfbase.ttfonts import TTFont
try:
msmincho = TTFont('MS Mincho','msmincho.ttc',subfontIndex=0,asciiReadable=0)
fn = ' file=msmincho.ttc subfont 0'
except:
try:
msmincho = TTFont('MS Mincho','msmincho.ttf',asciiReadable=0)
fn = 'file=msmincho.ttf'
except:
#Ubuntu - works on Lucid Lynx if xpdf-japanese installed
try:
msmincho = TTFont('MS Mincho','ttf-japanese-mincho.ttf')
fn = 'file=msmincho.ttf'
except:
msmincho = None
if msmincho is None:
c.setFont('Helvetica', 12)
c.drawString(100,600, 'Cannot find msmincho.ttf or msmincho.ttc')
else:
#.........这里部分代码省略.........
示例5: formboleto
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
def formboleto(response,sacado,endereco,endereco1,valor,vencimento_date,nossonumero,observacao2):
#temporarios
#nossonumero = '99999998'
#valor = '1,00'
vencimento = vencimento_date.strftime('%d/%m/%Y')
v = valor.replace(',','')
fator = diff_date(vencimento_date)
linhadigitavel = mount_line(banco,'9',carteira,agencia,nossonumero,fator,v)
nossonumero += '-'+str(calc_our_number(ag+conta+carteira+nossonumero))
boleto=Canvas(response)
# Logomarca da empresa
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/empresa.jpg', x=7*mm, y=280*mm, width=30*mm, height=11*mm)
boleto.setStrokeColor(colors.black)
boleto.setLineWidth(0.1)
boleto.setFont('Helvetica-Bold',14)
global localpagamento, usobanco
if banco=='237':
# bradesco
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancobradesco.jpg',x=160*mm, y=280*mm, width=25*mm, height=8*mm)
# imagem do recido do sacado
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancobradesco.jpg',x=7*mm, y=229*mm, width=25*mm, height=8*mm)
# imagem do banco na ficha de compensação
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancobradesco.jpg',x=7*mm, y=112*mm, width=25*mm, height=8*mm)
# codigo do banco
boleto.drawString(43*mm, 229*mm, '237-9')
boleto.drawString(43*mm, 112*mm, '237-9')
localpagamento+='Banco BRADESCO S/A'
usobanco='269'
#LINHADIGITAVEL='2379.264712 90600.000336 23007.514005 5 33070000011402'
#CODIGOBARRA='23795330700000114022647190600000332300751400'
elif banco=='422':
# safra
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancosafra.jpg',x=160*mm, y=275*mm, width=32*mm, height=7*mm)
# imagem do recido do sacado
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancosafra.jpg',x=7*mm, y=229*mm, width=30*mm, height=6*mm)
# imagem do banco na ficha de compensação
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancosafra.jpg',x=7*mm, y=112*mm, width=30*mm, height=6*mm)
# codigo do banco
boleto.drawString(43*mm, 229*mm, '422-7')
boleto.drawString(43*mm, 112*mm, '422-7')
localpagamento+='Banco SAFRA'
elif banco=='341':
# itau
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancoitau.jpg',x=160*mm, y=275*mm, width=32*mm, height=7*mm)
# imagem do recido do sacado
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancoitau.jpg',x=7*mm, y=229*mm, width=30*mm, height=6*mm)
# imagem do banco na ficha de compensação
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancoitau.jpg',x=7*mm, y=112*mm, width=30*mm, height=6*mm)
# codigo do banco
boleto.drawString(43*mm, 229*mm, '341-7')
boleto.drawString(43*mm, 112*mm, '341-7')
#localpagamento+='Banco ITAU'
else:
# banco do brasil para default
# imagem do canhoto
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancodobrasil.jpg',x=160*mm, y=280*mm, width=30*mm, height=5*mm)
# imagem do recido do sacado
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancodobrasil.jpg',x=7*mm, y=229*mm, width=30*mm, height=5*mm)
# imagem do banco na ficha de compensação
boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancodobrasil.jpg',x=7*mm, y=112*mm, width=30*mm, height=5*mm)
# codigo do banco
boleto.drawString(43*mm, 229*mm, '001-9')
boleto.drawString(43*mm, 112*mm, '001-9')
localpagamento+='Banco do BRASIL S/A'
# telefone da empresa
boleto.setFont('Helvetica-Bold', 12)
boleto.drawString(7*mm, 275*mm, telefone_empresa)
###############
#RETICULAS DO VENCIMENTO E DO VALOR
# (NÃO RETIRAR DAQUI SENÃO SOBREPORÁ O VALOR E O VENCIMENTO)
# Recibo do sacado
# retícula com cinza (Vencimento)
#.........这里部分代码省略.........
示例6: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
#.........这里部分代码省略.........
ret = args[0]
for i in args[1:]:
ret -= i
return ret
def get_top_pos(self):
"""Since the coordinates are bottom-left on PDF, we have to use this to get
the current top position, considering also the top margin."""
ret = self.calculate_size(self.report.page_size[1]) - self.calculate_size(self.report.margin_top) - self._current_top_position
if self.report.band_page_header:
ret -= self.calculate_size(self.report.band_page_header.height)
return ret
def make_paragraph(self, text, style=None): # XXX
"""Uses the Paragraph class to return a new paragraph object"""
return Paragraph(text, style)
def wrap_paragraph_on(self, paragraph, width, height): # XXX
"""Wraps the paragraph on the height/width informed"""
paragraph.wrapOn(self.canvas, width, height)
# Stylizing
def set_fill_color(self, color):
"""Sets the current fill on canvas. Used for fonts and shape fills"""
self.canvas.setFillColor(color)
def set_stroke_color(self, color):
"""Sets the current stroke on canvas"""
self.canvas.setStrokeColor(color)
def set_stroke_width(self, width):
"""Sets the stroke/line width for shapes"""
self.canvas.setLineWidth(width)
def make_paragraph_style(self, band, style=None):
"""Merge report default_style + band default_style + widget style"""
d_style = self.report.default_style.copy()
if band.default_style:
for k,v in band.default_style.items():
d_style[k] = v
if style:
for k,v in style.items():
d_style[k] = v
import datetime
return ParagraphStyle(name=datetime.datetime.now().strftime('%H%M%S'), **d_style)
def keep_in_frame(self, widget, width, height, paragraphs, mode):
widget.keep = KeepInFrame(width, height, paragraphs, mode=mode)
widget.keep.canv = self.canvas
widget.keep.wrap(self.calculate_size(widget.width), self.calculate_size(widget.height))
# METHODS THAT ARE TOTALLY SPECIFIC TO THIS GENERATOR AND MUST
# OVERRIDE THE SUPERCLASS EQUIVALENT ONES
def generate_pages(self):
"""Specific method that generates the pages"""
示例7: SpanningInvoice
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
def SpanningInvoice(path, sheet):
'''
canvas的坐标原点在坐下角,inc表示的是英寸
setFillColor可以设置字体的颜色
setStrokeColor可以设置线的颜色
setFont设置字体属性
'''
can = Canvas(path)
(width, height) = pagesizes.A4 #返回A4页面大小,单位不是英寸,应该是像素
can.setFillColor(colors.red)
can.setStrokeColor(colors.red)
can.setFont("song", 20)
can.drawCentredString(width/2.0, height*0.9, "XXX财务管理系统")
can.setFont("hei", 20)
can.drawCentredString(width/2.0, height*0.9-25, "发票联")
can.setFont("song", 15)
can.drawString(width*0.6+10, height*0.9-50, "发票代码:")
can.drawString(width*0.6+10, height*0.9-65, "开票日期:")
can.drawString(width*0.05+10, height*0.9-50, "付款人(客户):")
can.drawString(width*0.05+10, height*0.9-65, " 地址:")
can.drawString(width*0.15+10, height*0.75+7, "项目")
can.drawString(width*0.4+10, height*0.75+7, "数量")
can.drawString(width*0.6+10, height*0.75+7, "单价")
can.drawString(width*0.8+10, height*0.75+7, "金额")
can.setFillColor(colors.black)
can.drawString(width*0.7+40, height*0.9-50, "NO."+sheet.num)
if sheet.year != -1:
stryear = str(sheet.year)
else:
stryear = ''
if sheet.month != -1:
strmonth = str(sheet.month)
else:
strmonth = ''
if sheet.day != -1:
strday = str(sheet.day)
else:
strday = ''
can.drawString(width*0.7+40, height*0.9-65, stryear+"年"+strmonth+"月"+strday+"日")
can.drawString(width*0.15+55, height*0.9-50, sheet.name)
can.drawString(width*0.15+55, height*0.9-65, sheet.addr)
sheetline = sheet.sheetline
sheetline = int(sheetline)
info_list = []
for i in range(1, sheetline+1):
info_list.append([])
exec_str = "info_list[i-1].append(sheet.s"+str(i)+")" #利用exec函数来运行字符串对应代码
exec(exec_str)
exec_str = "info_list[i-1].append(sheet.n"+str(i)+")"
exec(exec_str)
exec_str = "info_list[i-1].append(sheet.p"+str(i)+")"
exec(exec_str)
from_height = height*0.7
position = height*0.7
height_pace = height*0.04
coor = [width*0.15+10, width*0.4+10, width*0.6+10, width*0.8+10]
for i in range(0, sheetline):
can.drawString(coor[0]-20, position, str(info_list[i][0].encode("utf-8")))
for j in range(1, len(coor)-1):
if info_list[i][j] != -1:
can.drawString(coor[j], position, str(info_list[i][j]))
if info_list[i][j] != -1 and info_list[i][j-1] != -1:
can.drawString(coor[j+1], position, str(info_list[i][j]*info_list[i][j-1]))
position = position - height_pace
can.setFillColor(colors.red)
can.setStrokeColor(colors.red)
from_height = from_height + height_pace/2 + 5
for i in range(0, sheetline+1):
can.line(width*0.05, from_height, width*0.95, from_height)
from_height = from_height - height_pace
can.line(width*0.05, height*0.8, width*0.95, height*0.8)
for i in range(1, len(coor)):
can.line(coor[i]-width*0.09, from_height+height_pace, coor[i]-width*0.09, height*0.8)
can.setFont("song", 15)
can.drawString(width*0.1, position, "合计人民币")
can.drawString(width*0.1+15, position-20, "(大写)")
can.line(coor[1]-10, from_height+height_pace, coor[1]-10, from_height+height_pace-60)
can.setFillColor(colors.black)
can.setStrokeColor(colors.black)
lst = []
#total是一个浮点数,需要进行处理一下
total = int(sheet.total)
lst.append(int(total/10000 - 10*(total/100000)))
lst.append(int(total/1000-10*(total/10000)))
lst.append(int(total/100-10*(total/1000)))
lst.append(int(total/10-10*(total/100)))
lst.append(int(total%10))
ch1 = ["万", "仟", "佰", "拾"]
ch2 = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]
#.........这里部分代码省略.........
示例8: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
#.........这里部分代码省略.........
return ret
def get_top_pos(self):
"""Since the coordinates are bottom-left on PDF, we have to use this to get
the current top position, considering also the top margin."""
ret = self.calculate_size(self.report.page_size[1]) - self.calculate_size(self.report.margin_top) - self._current_top_position
if self.report.band_page_header:
ret -= self.calculate_size(self.report.band_page_header.height)
return ret
def make_paragraph(self, text, style=None):
"""Uses the Paragraph class to return a new paragraph object"""
return Paragraph(text, style)
def wrap_paragraph_on(self, paragraph, width, height):
"""Wraps the paragraph on the height/width informed"""
paragraph.wrapOn(self.canvas, width, height)
def wrap_barcode_on(self, barcode, width, height):
"""Wraps the barcode on the height/width informed"""
barcode.wrapOn(self.canvas, width, height)
# Stylizing
def set_fill_color(self, color):
"""Sets the current fill on canvas. Used for fonts and shape fills"""
self.canvas.setFillColor(color)
def set_stroke_color(self, color):
"""Sets the current stroke on canvas"""
self.canvas.setStrokeColor(color)
def set_stroke_width(self, width):
"""Sets the stroke/line width for shapes"""
self.canvas.setLineWidth(width)
def make_paragraph_style(self, band, style=None):
"""Merge report default_style + band default_style + widget style"""
d_style = self.report.default_style.copy()
if band.default_style:
for k,v in band.default_style.items():
d_style[k] = v
if style:
for k,v in style.items():
d_style[k] = v
return ParagraphStyle(name=datetime.datetime.now().strftime('%H%M%S'), **d_style)
def keep_in_frame(self, widget, width, height, paragraphs, mode, persistent=False):
keep = KeepInFrame(width, height, paragraphs, mode=mode)
keep.canv = self.canvas
keep.wrap(self.calculate_size(widget.width), self.calculate_size(widget.height))
if persistent:
widget.keep = keep
return keep
# METHODS THAT ARE TOTALLY SPECIFIC TO THIS GENERATOR AND MUST
# OVERRIDE THE SUPERCLASS EQUIVALENT ONES
示例9: Canvas
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
# (Ces lignes peuvent être supprimées si Reportlab est disponible pour Python3)
from __future__ import unicode_literals
from __future__ import division # division "réelle"
# -------------------------------------------------------------------------
# Importation de quelques éléments de la bibliothèque ReportLab :
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import cm
from reportlab.lib.pagesizes import A4
fichier ="document_2.pdf"
can = Canvas("%s" % (fichier), pagesize=A4)
# Installation d'éléments divers dans le canevas :
largeurP, hauteurP = A4 # largeur et hauteur de la page
centreX, centreY = largeurP/2, hauteurP/2 # coordonnées du centre page
can.setStrokeColor("red") # couleur des lignes
# Rappel : la position verticale sur la page est comptée à partir du bas.
can.line(1*cm, 1*cm, 1*cm, 28*cm) # ligne verticale à gauche
can.line(1*cm, 1*cm, 20*cm, 1*cm) # ligne horizontale en bas
can.line(1*cm, 28*cm, 20*cm, 1*cm) # ligne oblique (descendante)
can.setLineWidth(3) # nouvelle épaisseur des lignes
can.setFillColorRGB(1,1,.5) # couleur de remplissage (RVB)
can.rect(2*cm, 2*cm, 18*cm, 20*cm, fill=1) # rectangle de 18 x 20 cm
# Dessin d'un bitmap (aligné par son coin inférieur gauche). La méthode
# drawImage renvoie les dimensions du bitmap (en pixels) dans un tuple :
dX, dY =can.drawImage("cocci3.gif", 1*cm, 23*cm, mask="auto")
ratio =dY/dX # rapport haut./larg. de l'image
can.drawImage("cocci3.gif", 1*cm, 14*cm,
width=3*cm, height=3*cm*ratio, mask="auto")
can.drawImage("cocci3.gif", 1*cm, 7*cm, width=12*cm, height=5*cm, mask="auto")
示例10: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
#.........这里部分代码省略.........
elif self.colorspace == uc2const.COLOR_GRAY:
gray = self.cms.get_grayscale_color(color)
k = 1.0 - gray[1][0]
c = m = y = 0.0
pdfcolor = CMYKColor(c, m, y, k, alpha=alpha)
else:
if color[0] == uc2const.COLOR_RGB:
r, g, b = color[1]
return Color(r, g, b, alpha)
elif color[0] == uc2const.COLOR_GRAY:
k = 1.0 - color[1][0]
c = m = y = 0.0
pdfcolor = CMYKColor(c, m, y, k, alpha=alpha)
else:
c, m, y, k = self.cms.get_cmyk_color(color)[1]
pdfcolor = CMYKColor(c, m, y, k, alpha=alpha)
self.set_rgb_values(color, pdfcolor)
return pdfcolor
def stroke_pdfpath(self, pdfpath, stroke_style, stroke_trafo=[]):
width = stroke_style[1]
if not stroke_style[8]:
width = stroke_style[1]
else:
if not stroke_trafo:
stroke_trafo = [] + sk2_const.NORMAL_TRAFO
points = [[0.0, 0.0], [1.0, 0.0]]
points = libgeom.apply_trafo_to_points(points, stroke_trafo)
coef = libgeom.distance(*points)
width = stroke_style[1] * coef
self.canvas.setStrokeColor(self.get_pdfcolor(stroke_style[2]))
dash = stroke_style[3]
caps = stroke_style[4]
joint = stroke_style[5]
miter = stroke_style[6]
self.canvas.setLineWidth(width)
self.canvas.setLineCap(caps - 1)
self.canvas.setLineJoin(joint)
dashes = []
if dash:
dashes = list(dash)
w = width
if w < 1.0: w = 1.0
for i in range(len(dashes)):
dashes[i] = w * dashes[i]
self.canvas.setDash(dashes)
self.canvas.setMiterLimit(miter)
self.canvas.drawPath(pdfpath, 1, 0)
self.canvas.setStrokeAlpha(1.0)
def fill_pdfpath(self, obj, pdfpath, fill_style, fill_trafo=None):
self.set_fill_rule(fill_style[0])
if fill_style[1] == sk2_const.FILL_SOLID:
self.canvas.setFillColor(self.get_pdfcolor(fill_style[2]))
self.canvas.drawPath(pdfpath, 0, 1)
elif fill_style[1] == sk2_const.FILL_GRADIENT:
gradient = fill_style[2]
stops = gradient[2]
transparency = False
for stop in stops:
if stop[1][2] < 1.0:
示例11: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
#.........这里部分代码省略.........
# Get current object from list
self._current_object = objects[self._current_object_index]
# Generates the detail band
self.generate_band(self.report.band_detail)
# Updates top position
self.update_top_pos(self.report.band_detail.height)
# Next object
self._current_object_index += 1
# Break is this is the end of this page
if self.get_available_height() < self.report.band_detail.height:
break
# Sets this is the latest page or not
self._is_latest_page = self._current_object_index >= len(objects)
# Ends the current page, printing footer and summary and necessary
self.end_current_page()
# Breaks if this is the latest item
if self._is_latest_page:
break
# Increment page number
self._current_page_number += 1
def start_new_page(self, with_header=True):
"""Do everything necessary to be done to start a new page"""
if with_header:
self.generate_page_header()
def end_current_page(self):
"""Closes the current page, using showPage method. Everything done after
this will draw into a new page. Before this, using the generate_page_footer
method to draw the footer"""
self.generate_page_footer()
if self._is_latest_page:
self.generate_summary()
self.canvas.showPage()
self._current_page_number += 1
self._is_first_page = False
self.update_top_pos(set=0) # <---- update top position
def get_top_pos(self):
"""Since the coordinates are bottom-left on PDF, we have to use this to get
the current top position, considering also the top margin."""
ret = self.report.page_size[1] - self.report.margin_top - self._current_top_position
if self.report.band_page_header:
ret -= self.report.band_page_header.height
return ret
def get_available_height(self):
"""Returns the available client height area from the current top position
until the end of page, considering the bottom margin."""
ret = self.report.page_size[1] - self.report.margin_bottom -\
self.report.margin_top - self._current_top_position
if self.report.band_page_header:
ret -= self.report.band_page_header.height
if self.report.band_page_footer:
ret -= self.report.band_page_footer.height
return ret
def update_top_pos(self, increase=0, decrease=0, set=None):
"""Updates the current top position controller, increasing (by default),
decreasing or setting it with a new value."""
if set is not None:
self._current_top_position = set
else:
self._current_top_position += increase
self._current_top_position -= decrease
return self._current_top_position
def get_page_count(self): # TODO
"""Calculate and returns the page count for this report. The challenge
here is do this calculate before to generate the pages."""
pass
def set_fill_color(self, color):
"""Sets the current fill on canvas. Used for fonts and shape fills"""
self.canvas.setFillColor(color)
def set_stroke_color(self, color):
"""Sets the current stroke on canvas"""
self.canvas.setStrokeColor(color)
def set_stroke_width(self, width):
"""Sets the stroke/line width for shapes"""
self.canvas.setLineWidth(width)
示例12: yourfilename
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
class CreatePDF:
"""
A class to create a PDF with the slides from AudioCours Version 2 recording
Usage:
Python CrezatePDF.py myDirectoryPath yourfilename (without the .pdf)
"""
def __init__(self):
"""
Onitialize the PDF (A4) and reade the timecode file
"""
try:
self.pdf = Canvas(workingDirectory+"/"+pdfName+".pdf")
timecode= open(workingDirectory+"/timecode.csv",'r')
self.slides=[]
for line in timecode:
self.slides.append(line)
print "\nNumber of slides to process :", len(self.slides)
print "\nPlease wait while processing ..."
# Get informations from the description file
self.author = self.title = self.formation = self.subject = self.date = ""
description = open("%s/description.txt" % workingDirectory,'r')
for line in description:
line = line.replace('\n','').split(':')
if len(line) == 2 and line[0] == "Author":
self.author = line[1]
elif len(line) == 2 and line[0] == "Title":
self.title = line[1]
elif len(line) == 2 and line[0] == "Formation":
self.formation = line[1]
elif len(line) == 2 and line[0] == "Subject":
self.subject = line[1]
elif len(line) == 2 and line[0] == "Date":
self.date = line[1]
except Exception:
print "An error occurred during the initialization of the pdf"
else:
timecode.close()
description.close()
def timeToHMS(self,t):
"""
Return a Hour Minute Seconds string from the time given in seconds
"""
t=float(t)
hours=int(t/3600)
mins=int(t-hours*3600)/60
seconds=int(t-hours*3600-mins*60)
hms= str(hours)+" h "+str(mins)+" m "+str(seconds)+" s "
return hms
def produce(self):
"""
Draw in the PDF the screenshots and datas
(2 screenshots per page : Up and Down)
"""
#print title and author
intro = "<font name=Courier size=14>\
<b>Title:</b> %s<br /><br />\
<b>Author:</b> %s<br /><br />\
<b>Formation:</b> %s<br /><br />\
<b>Subject:</b> %s<br /><br />\
<b>Date:</b> %s\
</font>" % (self.title, self.author, self.formation, self.subject, self.date)
styles = getSampleStyleSheet()
p = Paragraph(intro,styles["Normal"])
p.wrapOn(self.pdf,15*cm, 20*cm)
p.drawOn(self.pdf, 3*cm, 28*cm-p.height)
self.pdf.showPage()
#print slides
d=2
# Slides Positions
SUx,SUy=3*cm,3*cm # upper slide
SDx,SDy=3*cm,16*cm #Slide Down (bottom)
Swidth,Sheight= 16*cm,11*cm
while d <= len(self.slides):
#define font
self.pdf.setFont("Courier", 10)
self.pdf.setStrokeColor("grey")
self.pdf.setLineWidth(2)
#footer
self.pdf.drawString(3*cm,1*cm,"Author: %s" % (self.author,))
if d % 2 != 0: # Upper slide
captureTime =self.timeToHMS(self.slides[d-2])
self.pdf.drawString(SUx, SUy-0.5*cm, "^ Capture "+str(d)+\
" (timing = "+ captureTime +")")
self.pdf.drawImage(workingDirectory+"/screenshots/D"+str(d)+\
".jpg", SUx,SUy,width=Swidth,height=Sheight)
self.pdf.rect(SUx,SUy,Swidth,Sheight, fill=0)
self.pdf.showPage()
#.........这里部分代码省略.........
示例13: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
def test0(self):
"A basic document drawing some strings"
# if they do not have the Japanese font files, go away quietly
try:
from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile
findCMapFile("90ms-RKSJ-H")
findCMapFile("90msp-RKSJ-H")
findCMapFile("UniJIS-UCS2-H")
findCMapFile("EUC-H")
except:
# don't have the font pack. return silently
return
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "90ms-RKSJ-H"))
pdfmetrics.registerFont(CIDFont("HeiseiKakuGo-W5", "90ms-RKSJ-H"))
c = Canvas(outputfile("test_multibyte_jpn.pdf"))
c.setFont("Helvetica", 30)
c.drawString(100, 700, "Japanese Font Support")
c.setStrokeColor(colors.red)
# the two typefaces
c.setFont("HeiseiMin-W3-90ms-RKSJ-H", 16)
# this says "This is HeiseiMincho" in shift-JIS. Not all our readers
# have a Japanese PC, so I escaped it. On a Japanese-capable
# system, print the string to see Kanji
message1 = "\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B"
c.drawString(100, 675, message1)
wid = pdfmetrics.stringWidth(message1, "HeiseiMin-W3-90ms-RKSJ-H", 16)
c.rect(100, 675, wid, 16, stroke=1, fill=0)
c.setFont("HeiseiKakuGo-W5-90ms-RKSJ-H", 16)
# this says "This is HeiseiKakugo" in shift-JIS
message2 = "\202\261\202\352\202\315\225\275\220\254\212p\203S\203V\203b\203N\202\305\202\267\201B"
c.drawString(100, 650, message2)
wid = pdfmetrics.stringWidth(message2, "HeiseiKakuGo-W5-90ms-RKSJ-H", 16)
c.rect(100, 650, wid, 16, stroke=1, fill=0)
self.hDraw(c, "\223\214\213\236 says Tokyo in Shift-JIS", "HeiseiMin-W3-90ms-RKSJ-H", 100, 600)
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "90msp-RKSJ-H"))
self.hDraw(c, "\223\214\213\236, but in proportional Shift-JIS.", "HeiseiMin-W3-90msp-RKSJ-H", 100, 575)
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "EUC-H"))
self.hDraw(c, "\xC5\xEC\xB5\xFE says Tokyo in EUC", "HeiseiMin-W3-EUC-H", 100, 550)
if 0:
# this is super-slow until we do encoding caching.
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "UniJIS-UCS2-H"))
def asciiToUCS2(text):
s = ""
for ch in text:
s = s + chr(0) + ch
return s
self.hDraw(
c, "\x67\x71\x4E\xAC" + asciiToUCS2(" says Tokyo in UCS2"), "HeiseiMin-W3-UniJIS-UCS2-H", 100, 525
)
# now try verticals
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "90ms-RKSJ-V"))
c.setFont("HeiseiMin-W3-90ms-RKSJ-V", 16)
c.drawString(400, 650, "\223\214\213\236 vertical Shift-JIS")
height = c.stringWidth("\223\214\213\236 vertical Shift-JIS", "HeiseiMin-W3-90ms-RKSJ-V", 16)
c.rect(400 - 8, 650, 16, -height)
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "EUC-V"))
c.setFont("HeiseiMin-W3-EUC-V", 16)
c.drawString(425, 650, "\xC5\xEC\xB5\xFE vertical EUC")
height = c.stringWidth("\xC5\xEC\xB5\xFE vertical EUC", "HeiseiMin-W3-EUC-V", 16)
c.rect(425 - 8, 650, 16, -height)
c.setFillColor(colors.purple)
tx = c.beginText(100, 250)
tx.setFont("Helvetica", 12)
tx.textLines(
"""This document shows sample output in Japanese
from the Reportlab PDF library. This page shows the two fonts
available and tests our ability to measure the width of glyphs
in both horizontal and vertical writing, with proportional and
fixed-width characters. The red boxes should be the same width
(or height) as the character strings they surround.
The next pages show more samples and information.
"""
)
c.drawText(tx)
c.setFont("Helvetica", 10)
c.drawCentredString(297, 36, "Page %d" % c.getPageNumber())
c.showPage()
# realistic text sample
sample = """Adobe Acrobat
\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xaa\x8aJ\x82\xa9\x82\xc8\x82\xad\x82\xc4\x8d\xa2\x82\xc1\x82\xbd\x82\xb1\x82\xc6\x82\xcd
\x82\xa0\x82\xe8\x82\xdc\x82\xb9\x82\xf1\x82\xa9\x81B\x8e\x96\x8b\xc6\x8cv\x89\xe6\x8f\x91\x81A\x89c\x8b\xc6\x83\x8c\x83|\x81[\x83g
\x81A\x83J\x83^\x83\x8d\x83O\x82\xe2\x83p\x83\x93\x83t\x83\x8c\x83b\x83g\x82\xc8\x82\xc7\x90\xa7\x8d\xec\x95\xa8\x82\xcc\x8e\xed
\x97\xde\x82\xc9\x82\xa9\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A
#.........这里部分代码省略.........
示例14: create_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
def create_pdf(hocr, filename, font="Courier", author=None, keywords=None, subject=None, title=None, image_path=None, draft=False):
""" transform hOCR information into a searchable PDF.
@param hocr the hocr structure as coming from extract_hocr.
@param filename the name of the PDF generated in output.
@param font the default font (e.g. Courier, Times-Roman).
@param author the author name.
@param subject the subject of the document.
@param title the title of the document.
@param image_path the default path where images are stored. If not specified
relative image paths will be resolved to the current directory.
@param draft whether to enable debug information in the output.
"""
def adjust_image_size(width, height):
return max(width / A4[0], height / A4[1])
canvas = Canvas(filename)
if author:
canvas.setAuthor(author)
if keywords:
canvas.setKeywords(keywords)
if title:
canvas.setTitle(title)
if subject:
canvas.setSubject(subject)
for bbox, image, lines in hocr:
if not image.startswith('/') and image_path:
image = os.path.abspath(os.path.join(image_path, image))
img_width, img_height = bbox[2:]
ratio = adjust_image_size(img_width, img_height)
if draft:
canvas.drawImage(image, 0, A4[1] - img_height / ratio , img_width / ratio, img_height / ratio)
canvas.setFont(font, 12)
for bbox, line in lines:
if draft:
canvas.setFillColor(red)
x0, y0, x1, y1 = bbox
width = (x1 - x0) / ratio
height = ((y1 - y0) / ratio)
x0 = x0 / ratio
#for ch in 'gjpqy,(){}[];[email protected]':
#if ch in line:
#y0 = A4[1] - (y0 / ratio) - height
#break
#else:
y0 = A4[1] - (y0 / ratio) - height / 1.3
#canvas.setFontSize(height * 1.5)
canvas.setFontSize(height)
text_width = canvas.stringWidth(line)
if text_width:
## If text_width != 0
text_object = canvas.beginText(x0, y0)
text_object.setHorizScale(1.0 * width / text_width * 100)
text_object.textOut(line)
canvas.drawText(text_object)
else:
info('%s, %s has width 0' % (bbox, line))
if draft:
canvas.setStrokeColor(green)
canvas.rect(x0, y0, width, height)
if draft:
canvas.circle(0, 0, 10, fill=1)
canvas.circle(0, A4[1], 10, fill=1)
canvas.circle(A4[0], 0, 10, fill=1)
canvas.circle(A4[0], A4[1], 10, fill=1)
canvas.setFillColor(green)
canvas.setStrokeColor(green)
canvas.circle(0, A4[1] - img_height / ratio, 5, fill=1)
canvas.circle(img_width / ratio, img_height /ratio, 5, fill=1)
else:
canvas.drawImage(image, 0, A4[1] - img_height / ratio , img_width / ratio, img_height / ratio)
canvas.save()
示例15: __init__
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setStrokeColor [as 别名]
#.........这里部分代码省略.........
# Préparation
marge_haut = copy.copy(dictDonnees["page_marge_haut"])
marge_bas = copy.copy(dictDonnees["page_marge_bas"])
# Calcule la largeur des cases
largeur_case = ((largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"]) - dictDonnees["page_espace_horizontal"] * (nbre_colonnes - 1)) / nbre_colonnes
# Dessine l'image de fond
if dictDonnees["page_fond_image"] != "aucune" :
canvas.drawImage(Chemins.GetStaticPath("Images/%s" % dictDonnees["page_fond_image"]), 0, 0, largeur_page, hauteur_page, preserveAspectRatio=False)
# Dessine le titre
if dictDonnees["titre_afficher"] == True:
if dictDonnees["titre_texte"] != "" :
texte_titre = u"%s %s" % (dictDonnees["titre_texte"], texte_titre)
titre = Titre(parent=self, texte=texte_titre, canvas=canvas, largeur=largeur_page)
marge_haut += dictDonnees["titre_hauteur"]
# Dessine les entêtes
if dictDonnees["entete_afficher"] == True:
for num_colonne in range(0, nbre_colonnes):
# Calcule la position de la case
x_entete = dictDonnees["page_marge_gauche"] + ((largeur_case + dictDonnees["page_espace_horizontal"]) * num_colonne)
y_entete = hauteur_page - marge_haut - dictDonnees["entete_hauteur"]
# Dessine l'entête
texte = UTILS_Dates.LISTE_JOURS[dictDonnees["jours_semaine"][num_colonne]]
entete = Entete(parent=self, texte=texte, canvas=canvas, x=x_entete, y=y_entete, largeur_case=largeur_case)
marge_haut += dictDonnees["entete_hauteur"] + dictDonnees["page_espace_vertical"]
# Dessine le pied
if dictDonnees["pied_afficher"] == True and len(dictDonnees["pied_texte"]) > 0 :
pied = Pied(parent=self, texte=dictDonnees["pied_texte"], canvas=canvas, x=dictDonnees["page_marge_gauche"], y=marge_bas, largeur=largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"])
marge_bas += dictDonnees["pied_hauteur"] + dictDonnees["page_espace_vertical"]
# Dessine la légende
self.dictNumerosLegendes = {}
if dictDonnees["legende_afficher"] == True :
# Recherche les légendes présentes dans la page
liste_legendes = []
for num_colonne in range(0, nbre_colonnes):
for num_ligne in range(0, nbre_lignes):
date, dictTextes = self.GetDateAndTextes(num_ligne=num_ligne, num_colonne=num_colonne, dict_page=dict_page, calendrier=calendrier)
for IDcategorie, dictTexte in dictTextes.iteritems():
for chaine in REGEX_LEGENDES.findall(dictTexte["texte"]):
try :
IDlegende = int(chaine[1:-1])
dictLegende = self.dictDonnees["legendes"][IDlegende]
if dictLegende not in liste_legendes and self.dictDonnees["legendes"].has_key(IDlegende) :
liste_legendes.append(dictLegende)
except :
pass
if len(liste_legendes) > 0 :
legende = Legende(parent=self, liste_legendes=liste_legendes, canvas=canvas, x=dictDonnees["page_marge_gauche"], y=marge_bas, largeur=largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"])
self.dictNumerosLegendes = legende.dictNumerosLegendes
marge_bas += dictDonnees["legende_hauteur"] + dictDonnees["page_espace_vertical"]
# Calcul la hauteur des cases
hauteur_case = ((hauteur_page - marge_haut - marge_bas) - dictDonnees["page_espace_vertical"] * (nbre_lignes - 1)) / nbre_lignes
# Dessine les cases
for num_colonne in range(0, nbre_colonnes):
for num_ligne in range(0, nbre_lignes):
# Calcule la position de la case
x_case = dictDonnees["page_marge_gauche"] + ((largeur_case + dictDonnees["page_espace_horizontal"]) * num_colonne)
y_case = hauteur_page - marge_haut - hauteur_case - ((hauteur_case + dictDonnees["page_espace_vertical"]) * num_ligne)
# Recherche la date et les textes
date, dictTextes = self.GetDateAndTextes(num_ligne=num_ligne, num_colonne=num_colonne, dict_page=dict_page, calendrier=calendrier)
# Dessin de la case
case = Case(parent=self, date=date, dictTextes=dictTextes, canvas=canvas, x=x_case, y=y_case, largeur_case=largeur_case, hauteur_case=hauteur_case)
# Dessine la grille
if dictDonnees["page_grille"] == True :
canvas.setStrokeColor(ColorWxToPdf(wx.LIGHT_GREY, alpha=0.5))
canvas.setFillColor(ColorWxToPdf(wx.LIGHT_GREY, alpha=0.5))
canvas.setLineWidth(0.25)
canvas.grid(range(0, int(largeur_page)+50, 50), range(0, int(hauteur_page)+50, 50))
canvas.setFont("Helvetica", 8)
canvas.drawString(10, 10, _(u"Largeur carreau=50"))
# Saut de page
if num_page < len(liste_pages) - 1:
canvas.showPage()
# Finalisation du PDF
canvas.save()
try:
FonctionsPerso.LanceFichierExterne(nomDoc)
except:
print "Probleme dans l'edition du menu"