def add_header(self):
# # aiddata logo
# logo = self.assets_dir + '/templates/aid_data.png'
# im = Image(logo, 2.188*inch, 0.5*inch)
# im.hAlign = 'LEFT'
# self.Story.append(im)
# self.Story.append(Spacer(1, 0.25*inch))
# title
ptext = '<font size=20>AidData GeoQuery Request Documentation</font>'
self.Story.append(Paragraph(ptext, self.styles['Center']))
# report generation info
python类Paragraph()的实例源码
def draw_paragraph(self, text, max_width, max_height, style):
if not text:
text = ''
if not isinstance(text, str):
text = str(text)
text = text.strip(string.whitespace)
text = text.replace('\n', "<br/>")
p = Paragraph(text, style)
used_width, used_height = p.wrap(max_width, max_height)
line_widths = p.getActualLineWidths0()
number_of_lines = len(line_widths)
if number_of_lines > 1:
actual_width = used_width
elif number_of_lines == 1:
actual_width = min(line_widths)
used_width, used_height = p.wrap(actual_width + 0.1, max_height)
else:
return 0, 0
p.drawOn(self.canvas, self.cursor.x, self.cursor.y - used_height)
return used_width, used_height
def tabla_otros(self):
orden = self.orden_compra
p = ParagraphStyle('parrafos',
alignment = TA_CENTER,
fontSize = 8,
fontName="Times-Roman")
sub_total = Paragraph(u"SUBTOTAL: ",p)
igv = Paragraph(u"IGV: ",p)
total = Paragraph(u"TOTAL: ",p)
datos_otros = [[ Paragraph(u"LUGAR DE ENTREGA",p), Paragraph(u"PLAZO DE ENTREGA",p), Paragraph(u"FORMA DE PAGO",p),sub_total,orden.subtotal],
[Paragraph(EMPRESA.direccion(),p),Paragraph(u"INMEDIATA",p),Paragraph(orden.forma_pago.descripcion,p),igv,str(orden.igv)],
['','','',total,str(orden.total)],
]
tabla_otros = Table(datos_otros,colWidths=[5.5 * cm, 5 * cm, 5 * cm, 2 * cm, 2.5 * cm])
tabla_otros.setStyle(TableStyle(
[
('GRID', (0, 0), (2, 2), 1, colors.black),
('SPAN',(0,1),(0,2)),
('SPAN',(1,1),(1,2)),
('SPAN',(2,1),(2,2)),
('GRID', (4, 0), (4, 2), 1, colors.black),
('VALIGN',(0,1),(2,1),'MIDDLE'),
]
))
return tabla_otros
def tabla_observaciones(self):
orden = self.orden_compra
p = ParagraphStyle('parrafos',
alignment = TA_JUSTIFY,
fontSize = 8,
fontName="Times-Roman")
obs=Paragraph("OBSERVACIONES: "+orden.observaciones,p)
observaciones = [[obs]]
tabla_observaciones = Table(observaciones,colWidths=[20 * cm], rowHeights=1.8 * cm)
tabla_observaciones.setStyle(TableStyle(
[
('GRID', (0, 0), (0, 2), 1, colors.black),
('FONTSIZE', (0, 0), (-1, -1), 8),
('ALIGN',(0,0),(-1,-1),'LEFT'),
('VALIGN',(0,0),(-1,-1),'TOP'),
]
))
return tabla_observaciones
def cuadro_observaciones(self,pdf,y,orden):
p = ParagraphStyle('parrafos')
p.alignment = TA_JUSTIFY
p.fontSize = 10
p.fontName="Times-Roman"
obs=Paragraph("Observaciones: "+orden.observaciones,p)
observaciones = [[obs]]
tabla_observaciones = Table(observaciones,colWidths=[18.50 * cm], rowHeights=1.8 * cm)
tabla_observaciones.setStyle(TableStyle(
[
('GRID', (0, 0), (0, 2), 1, colors.black),
('FONTSIZE', (0, 0), (-1, -1), 8),
('ALIGN',(0,0),(-1,-1),'LEFT'),
('VALIGN',(0,0),(-1,-1),'TOP'),
]
))
tabla_observaciones.wrapOn(pdf, 800, 600)
tabla_observaciones.drawOn(pdf, 40,y-58)
def tabla_encabezado(self,valorizado):
sp = ParagraphStyle('parrafos',
alignment=TA_CENTER,
fontSize=14,
fontName="Times-Roman")
try:
archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo))
imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT')
except:
imagen = Paragraph(u"LOGO", sp)
if valorizado:
titulo = Paragraph(u"REGISTRO DEL INVENTARIO PERMANENTE VALORIZADO", sp)
else:
titulo = Paragraph(u"REGISTRO DEL INVENTARIO PERMANENTE EN UNIDADES FÍSICAS", sp)
encabezado = [[imagen,titulo]]
tabla_encabezado = Table(encabezado, colWidths=[2 * cm, 23 * cm])
return tabla_encabezado
def rightBottom(self, e):
story = []
if e is None:
return story
parts = []
if 'solution' in e:
story.append(
reportlab.platypus.Preformatted(
wrapParagraph(
e['solution'],
50),
self.style_pre))
if 'keywords' in e:
parts.append('<i>' + ', '.join(e['keywords']) + '</i>')
if 'comments' in e:
parts.append('<br/>'.join(e['comments']))
story.append(reportlab.platypus.Paragraph(
'<font face="%s" size=%d>%s</font>' % (
FONT_FAMILY,
FONT_SIZE['rightpane'],
'<br/><br/>'.join(parts)
), self.style
))
return story
def test_11_drawing(self):
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
from reportlab.pdfbase import pdfmetrics
from reportlab.graphics.shapes import Drawing, Rect
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
stylesheet = getSampleStyleSheet()
elements = []
doc = SimpleDocTemplate("demo.pdf")
elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title']))
elements.append(Spacer(1,12))
d = Drawing(400,200)
d.add(Rect(50,50,300,100, fillColor=colors.yellow))
elements.append(d)
doc.build(elements)
def generate_pdf_report(self, report_id, recipient):
# PREPARE PDF
report_buffer = BytesIO()
doc = SimpleDocTemplate(
report_buffer,
pagesize=letter,
rightMargin=72, leftMargin=72,
topMargin=72, bottomMargin=72,
)
# COVER PAGE
self.pdf_elements.extend(
api.NotificationApi.get_cover_page(
report_id=report_id,
recipient=recipient,
),
)
# METADATA PAGE
self.pdf_elements.extend(self.get_metadata_page(recipient))
# REPORT
self.pdf_elements.extend(
[Paragraph("Report Questions", self.section_title_style)],
)
for item in self.report_data:
question, answers = item.popitem()
self.render_question(question, answers)
doc.build(
self.pdf_elements,
onFirstPage=self.get_header_footer(recipient),
onLaterPages=self.get_header_footer(recipient),
canvasmaker=NumberedCanvas,
)
result = report_buffer.getvalue()
report_buffer.close()
return result
def afterFlowable(self, flowable):
if flowable.__class__.__name__ == 'Paragraph':
text = flowable.getPlainText()
style = flowable.style.name
if style == 'Heading1':
key = 'h1-%s' % self.seq.nextf('heading1')
self.canv.bookmarkPage(key)
self.notify('TOCEntry', (0, text, self.page, key))
if style == 'Heading2':
key = 'h2-%s' % self.seq.nextf('heading2')
self.canv.bookmarkPage(key)
self.notify('TOCEntry', (1, text, self.page, key))
if style == 'Heading3':
key = 'h3-%s' % self.seq.nextf('heading3')
self.canv.bookmarkPage(key)
self.notify('TOCEntry', (2, text, self.page, key))
def parse_repeat(self, r_object):
styNormal = styleSheet['Normal']
styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.white)
gnr_question = r_object['name']
for gnr_answer in self.main_answer[gnr_question]:
for first_children in r_object['children']:
question = first_children['name']
group_answer = self.main_answer[gnr_question]
question_label = first_children['label']
if gnr_question+"/"+question in gnr_answer:
if first_children['type'] == 'note':
answer= ''
elif first_children['type'] == 'photo':
#photo = '/media/user/attachments/'+ gnr_answer[gnr_question+"/"+question]
photo = 'http://'+self.base_url+'/media/'+ self.media_folder +'/attachments/'+ gnr_answer[gnr_question+"/"+question]
answer = self.create_logo(photo)
# answer =''
else:
answer = gnr_answer[gnr_question+"/"+question]
else:
answer = ''
if 'label' in first_children:
question = first_children['label']
row=[Paragraph(question, styBackground), answer]
self.data.append(row)
def parse_group(self, g_object):
styNormal = styleSheet['Normal']
styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.white)
gnr_question = g_object['name']
for first_children in g_object['children']:
question = first_children['name']
if gnr_question+"/"+question in self.main_answer:
if first_children['type'] == 'note':
answer= ''
elif first_children['type'] == 'photo':
photo = 'http://'+self.base_url+'/media/'+ self.media_folder +'/attachments/'+self.main_answer[gnr_question+"/"+question]
answer = self.create_logo(photo)
else:
answer = self.main_answer[gnr_question+"/"+question]
else:
answer = ''
if 'label' in first_children:
question = first_children['label']
row=[Paragraph(question, styBackground), answer]
self.data.append(row)
def parse_individual_questions(self, parent_object):
styNormal = styleSheet['Normal']
styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.white)
answer=self.main_answer
for first_children in parent_object:
if first_children['type'] == "repeat":
self.parse_repeat(first_children)
elif first_children['type'] == 'group':
self.parse_group(first_children)
else:
question = first_children['name']
if first_children['type'] == 'note' or question not in self.main_answer:
answer= Paragraph('', styBackground)
elif first_children['type'] == 'photo':
photo = 'http://'+self.base_url+'/media/'+ self.media_folder +'/attachments/'+self.main_answer[question]
answer = self.create_logo(photo)
else:
answer = Paragraph(self.main_answer[question], styBackground)
if 'label' in first_children:
question = first_children['label']
row=(Paragraph(question, styBackground), answer)
self.data.append(row)
def cuadro_observaciones(self,pdf,y,cotizacion):
p = ParagraphStyle('parrafos')
p.alignment = TA_JUSTIFY
p.fontSize = 8
p.fontName="Times-Roman"
obs=Paragraph("OBSERVACIONES: "+cotizacion.observaciones,p)
observaciones = [[obs]]
tabla_observaciones = Table(observaciones,colWidths=[18 * cm], rowHeights=1.8 * cm)
tabla_observaciones.setStyle(TableStyle(
[
('GRID', (0, 0), (0, 2), 1, colors.black),
('FONTSIZE', (0, 0), (-1, -1), 8),
('ALIGN',(0,0),(-1,-1),'LEFT'),
('VALIGN',(0,0),(-1,-1),'TOP'),
]
))
tabla_observaciones.wrapOn(pdf, 800, 600)
tabla_observaciones.drawOn(pdf, 40,y+20)
def tabla_encabezado(self, styles):
sp = ParagraphStyle('parrafos',
alignment=TA_CENTER,
fontSize=14,
fontName="Times-Roman")
requerimiento = self.requerimiento
try:
archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo))
imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT')
except:
print u"Ingresa acá "
imagen = Paragraph(u"LOGO", sp)
nro = Paragraph(u"REQUERIMIENTO DE BIENES Y SERVICIOS<br/>N°" + requerimiento.codigo, sp)
encabezado = [[imagen, nro, '']]
tabla_encabezado = Table(encabezado, colWidths=[4 * cm, 11 * cm, 4 * cm])
tabla_encabezado.setStyle(TableStyle(
[
('ALIGN', (0, 0), (1, 0), 'CENTER'),
('VALIGN', (0, 0), (1, 0), 'CENTER'),
]
))
return tabla_encabezado
def tabla_datos(self, styles):
requerimiento = self.requerimiento
izquierda = ParagraphStyle('parrafos',
alignment=TA_LEFT,
fontSize=10,
fontName="Times-Roman")
solicitado = Paragraph(u"SOLICITADO POR: " + requerimiento.solicitante.nombre_completo(), izquierda)
oficina = Paragraph(u"OFICINA: " + requerimiento.oficina.nombre, izquierda)
motivo = Paragraph(u"MOTIVO: " + requerimiento.motivo, izquierda)
fecha = Paragraph(u"FECHA DE REQUERIMIENTO: " + requerimiento.fecha.strftime('%d/%m/%Y'), izquierda)
mes = Paragraph(u"MES EN QUE SE NECESITA: " + requerimiento.get_mes_display(), izquierda)
para_stock = Paragraph(u"AÑO EN QUE SE NECESITA: " + str(requerimiento.annio), izquierda)
if requerimiento.entrega_directa_solicitante:
entrega = Paragraph(u"ENTREGA DIRECTAMENTE AL SOLICITANTE: SI", izquierda)
else:
entrega = Paragraph(u"ENTREGA DIRECTAMENTE AL SOLICITANTE: NO", izquierda)
datos = [[solicitado, oficina], [motivo], [fecha, mes], [para_stock, entrega]]
tabla_datos = Table(datos, colWidths=[11 * cm, 9 * cm])
style = TableStyle(
[
('SPAN', (0, 1), (1, 1)),
]
)
tabla_datos.setStyle(style)
return tabla_datos
def tabla_observaciones(self):
requerimiento = self.requerimiento
p = ParagraphStyle('parrafos')
p.alignment = TA_JUSTIFY
p.fontSize = 8
p.fontName = "Times-Roman"
obs = Paragraph("OBSERVACIONES: " + requerimiento.observaciones, p)
observaciones = [[obs]]
tabla_observaciones = Table(observaciones, colWidths=[20 * cm], rowHeights=1.8 * cm)
tabla_observaciones.setStyle(TableStyle(
[
('GRID', (0, 0), (0, 2), 1, colors.black),
('FONTSIZE', (0, 0), (-1, -1), 8),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
]
))
return tabla_observaciones
def tabla_total(self):
movimiento = self.movimiento
izquierda = ParagraphStyle('parrafos',
alignment = TA_LEFT,
fontSize = 10,
fontName="Times-Roman")
texto_total = Paragraph("Total: ",izquierda)
total = Paragraph(str(round(movimiento.total,2)),izquierda)
total = [['',texto_total, total]]
tabla_total = Table(total,colWidths=[15.5 * cm,2 * cm,2.5 * cm])
tabla_total.setStyle(TableStyle(
[
('GRID', (2, 0), (2, 0), 1, colors.black),
('FONTSIZE', (0, 0), (-1, -1), 8),
('ALIGN',(0,0),(-1,-1),'RIGHT'),
]
))
return tabla_total
def tabla_observaciones(self):
movimiento = self.movimiento
p = ParagraphStyle('parrafos',
alignment = TA_JUSTIFY,
fontSize = 8,
fontName="Times-Roman")
obs=Paragraph("OBSERVACIONES: "+movimiento.observaciones,p)
observaciones = [[obs]]
tabla_observaciones = Table(observaciones,colWidths=[20 * cm], rowHeights=1.8 * cm)
tabla_observaciones.setStyle(TableStyle(
[
('GRID', (0, 0), (0, 2), 1, colors.black),
('FONTSIZE', (0, 0), (-1, -1), 8),
('ALIGN',(0,0),(-1,-1),'LEFT'),
('VALIGN',(0,0),(-1,-1),'TOP'),
]
))
return tabla_observaciones
def tabla_encabezado_consolidado(self, grupos):
sp = ParagraphStyle('parrafos',
alignment=TA_CENTER,
fontSize=14,
fontName="Times-Roman")
try:
archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo))
imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT')
except:
imagen = Paragraph(u"LOGO", sp)
if grupos:
titulo = Paragraph(u"RESUMEN MENSUAL DE ALMACÉN POR GRUPOS Y CUENTAS", sp)
else:
titulo = Paragraph(u"RESUMEN MENSUAL DE ALMACÉN POR PRODUCTOS", sp)
encabezado = [[imagen,titulo]]
tabla_encabezado = Table(encabezado, colWidths=[2 * cm, 23 * cm])
style = TableStyle(
[
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
]
)
tabla_encabezado.setStyle(style)
return tabla_encabezado
def convertSourceFiles(filenames):
"Helper function - makes minimal PDF document"
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted
from reportlab.lib.styles import getSampleStyleSheet
styT=getSampleStyleSheet()["Title"]
styC=getSampleStyleSheet()["Code"]
doc = SimpleDocTemplate("pygments2xpre.pdf")
S = [].append
for filename in filenames:
S(Paragraph(filename,style=styT))
src = open(filename, 'r').read()
fmt = pygments2xpre(src)
S(XPreformatted(fmt, style=styC))
doc.build(S.__self__)
print('saved pygments2xpre.pdf')
def test_09_docTemplate(self):
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
stylesheet = getSampleStyleSheet()
elements = []
doc = SimpleDocTemplate("demo.pdf")
elements.append(Paragraph('<font name="chsFont">AUT OOM????</font>', stylesheet['Title']))
elements.append(Spacer(1,12))
doc.build(elements)
def add_str_content(self, content, size=9, Bold=False, indent=(0.05*inch, 0.05*inch), style=None):
'''
??????
:param content: ??????
:param size: ????,??9
:param Bold: ????,??False
:param indent: ??????,(???,???)
:param style: ????
'''
if style == None:
style = styles["Normal"]
__content = "<font name='chsFont' size=%s>%s</font>" % (size, content)
if Bold:
__content = "<b>%s</b>" % __content
p = Paragraph(__content, style)
self.__content.append(Spacer(PAGE_WIDTH, indent[0]))
self.__content.append(p)
self.__content.append(Spacer(PAGE_WIDTH, indent[1]))
def _add_notes(self, canvas):
"""
This is designed to be the last element on the page.
Don't move it or stuff will break
"""
start_posn = self.start_posn
start_posn = self.start_posn
canvas.setFillColor(colors.blue)
canvas.setFont('Helvetica', 10)
canvas.drawString(0.5*inch, start_posn,
'Section E - Registration Notes')
canvas.setFillColor(colors.black)
canvas.rect(0.5*inch, 0.75*inch,
PAGE_WIDTH-inch, start_posn-0.85*inch)
style_sheet = getSampleStyleSheet()
style = style_sheet['BodyText']
para = Paragraph(self.details['registration_notes'], style)
h=para.wrap(7.1 * inch, start_posn-0.65*inch)[1]
para.drawOn(canvas, 0.7 * inch, start_posn-h-0.2*inch)
def render_footer(url, date=None):
'''
Renders the footer used in the different PDFs
:return: a Paragraph object
'''
if not date:
date = datetime.date.today().strftime("%d.%m.%Y")
p = Paragraph('''<para>
{date} -
<a href="{url}">{url}</a> -
wger Workout Manager
{version}
</para>'''.format(date=date,
url=url,
version=get_version()),
styleSheet["Normal"])
return p
# register new truetype fonts for reportlab
def gen_team_pdf(team_tuples: list):
global _reged
if not _reged:
pdfmetrics.registerFont(TTFont('my_font', options.options.ttf_font_name))
_reged = True
buf = io.BytesIO()
canv = canvas.Canvas(buf, pagesize=A4_TRANSVERSE)
style = ParagraphStyle(name='default', fontName='my_font', fontSize=options.options.pdf_font_size,
alignment=1, leading=options.options.pdf_font_size * 1.2)
for index, team in team_tuples:
paragraph = Paragraph('Team {0}<br />{1}'.format(index, team['team_name']), style)
w, h = paragraph.wrap(A4_TRANSVERSE[0] - 50, A4_TRANSVERSE[1] - 50)
paragraph.drawOn(canv, (A4_TRANSVERSE[0] - w) / 2, (A4_TRANSVERSE[1] - h) / 2)
canv.showPage()
canv.save()
return buf.getvalue()
def add_timeline(self):
ptext = '<b><font size=14>Processing Timeline</font></b>'
self.Story.append(Paragraph(ptext, self.styles['Normal']))
self.Story.append(Spacer(1, 0.1*inch))
data = [
[self.request['stage'][0]['name'], self.time_str(self.request['stage'][0]['time'])],
[self.request['stage'][1]['name'], self.time_str(self.request['stage'][1]['time'])],
[self.request['stage'][2]['name'], self.time_str(self.request['stage'][2]['time'])],
[self.request['stage'][3]['name'], self.time_str(int(time.time()))]
# ['complete', self.time_str(self.request['stage'][3]['time'])]
]
data = [[i[0], pg(i[1], 1)] for i in data]
t = Table(data)
t.setStyle(TableStyle([
('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black)
]))
self.Story.append(t)
def gather_elements(self, client, node, style):
if isinstance(node.parent, docutils.nodes.sidebar):
elements = [Paragraph(client.gen_pdftext(node),
client.styles['sidebar-subtitle'])]
elif isinstance(node.parent, docutils.nodes.document):
#elements = [Paragraph(client.gen_pdftext(node),
#client.styles['subtitle'])]
# The visible output is now done by the cover template
elements = []
# FIXME: looks like subtitles don't have a rawsource like
# titles do.
# That means that literals and italics etc in subtitles won't
# work.
client.doc_subtitle = getattr(node,'rawtext',node.astext()).strip()
else:
elements = node.elements # FIXME Can we get here???
return elements
def gather_elements(self, client, node, style):
if isinstance(node.parent, docutils.nodes.authors):
# Is only one of multiple authors. Return a paragraph
node.elements = [Paragraph(client.gather_pdftext(node),
style=style)]
if client.doc_author:
client.doc_author += client.author_separator(style=style) \
+ node.astext().strip()
else:
client.doc_author = node.astext().strip()
else:
# A single author: works like a field
fb = client.gather_pdftext(node)
t_style=TableStyle(client.styles['field-list'].commands)
colWidths=map(client.styles.adjustUnits,
client.styles['field-list'].colWidths)
node.elements = [Table(
[[Paragraph(client.text_for_label("author", style)+":",
style=client.styles['fieldname']),
Paragraph(fb, style)]],
style=t_style, colWidths=colWidths)]
client.doc_author = node.astext().strip()
return node.elements
def gather_elements(self, client, node, style):
# Based on the graphviz extension
global graphviz_warn
try:
# Is vectorpdf enabled?
if hasattr(VectorPdf,'load_xobj'):
# Yes, we have vectorpdf
fname, outfn = sphinx.ext.graphviz.render_dot(node['builder'], node['code'], node['options'], 'pdf')
else:
# Use bitmap
if not graphviz_warn:
log.warning('Using graphviz with PNG output. You get much better results if you enable the vectorpdf extension.')
graphviz_warn = True
fname, outfn = sphinx.ext.graphviz.render_dot(node['builder'], node['code'], node['options'], 'png')
if outfn:
client.to_unlink.append(outfn)
client.to_unlink.append(outfn+'.map')
else:
# Something went very wrong with graphviz, and
# sphinx should have given an error already
return []
except sphinx.ext.graphviz.GraphvizError, exc:
log.error('dot code %r: ' % node['code'] + str(exc))
return [Paragraph(node['code'],client.styles['code'])]
return [MyImage(filename=outfn, client=client)]