本文整理汇总了Python中reportlab.platypus.Table类的典型用法代码示例。如果您正苦于以下问题:Python Table类的具体用法?Python Table怎么用?Python Table使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Table类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_pdf
def make_pdf(data, title):
tid = str(time()).replace('.', '')
pdf_file = "reports/" + tid + ".pdf"
# convert tuple to list
data = [list(elem) for elem in data]
doc = SimpleDocTemplate(pdf_file, pagesize=letter)
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
parts = []
table_with_style = Table(data)
table_with_style.setStyle(TableStyle([
('FONTSIZE', (0, 0), (-1, -1), 8),
('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
('BOX', (0, 0), (-1, -1), 0.25, colors.black),
('ALIGN', (0, 0), (-1, 0), 'CENTER'),
]))
parts.append(Paragraph(title, styles["Center"]))
parts.append(Spacer(1, 12))
parts.append(table_with_style)
doc.build(parts)
show_pdf(pdf_file)
示例2: buildTable
def buildTable(data):
doc = SimpleDocTemplate("MOOSE_requirements_tracability.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
doc.pagesize = landscape(A4)
elements = []
#Configure style and word wrap
s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
pdf_data = [["Requirement", "Description", "Test Case(s)"]]
#TODO: Need a numerical sort here
keys = sorted(data.keys())
for key in keys:
data[key][2] = '\n'.join(data[key][2])
pdf_data.append([Paragraph(cell, s) for cell in data[key]])
# Build the Table and Style Information
tableThatSplitsOverPages = Table(pdf_data, repeatRows=1)
tableThatSplitsOverPages.hAlign = 'LEFT'
tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),colors.black),
('VALIGN',(0,0),(-1,-1),'TOP'),
('LINEBELOW',(0,0),(-1,-1),1,colors.black),
('INNERGRID', (0,0), (-1,-1),1,colors.black),
('BOX',(0,0),(-1,-1),1,colors.black),
('BOX',(0,0),(0,-1),1,colors.black)])
tblStyle.add('BACKGROUND',(0,0),(-1,-1),colors.lightblue)
tblStyle.add('BACKGROUND',(0,1),(-1,-1),colors.white)
tableThatSplitsOverPages.setStyle(tblStyle)
elements.append(tableThatSplitsOverPages)
doc.build(elements)
示例3: _build_top
def _build_top(self):
width = self.doc.width
invoice_date = self.invoice.get('invoice_date')
if self.payment and self.payment.status != 30:
title = "Avansa rēķins"
else:
title = "Rēķins"
im = None
if self.invoice.get('organiser_data').get('logo'):
adv = os.path.join(settings.MEDIA_ROOT, "adverts", self.invoice.get('organiser_data').get('logo'))
im = Image(adv, 100, 35)
# self.elements.append(im)
data = [[im if im else '', Paragraph(title, self.styles.get('h1')), 'Nr.', self.invoice.get('name')],
['', invoice_date, '', '']]
header_table = Table(data, colWidths=list((width / 4.0, width / 2.0, width / 16.0, (width * 3) / 16.0,), ))
header_table.setStyle(
TableStyle([
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('ALIGN', (3, 0), (3, 0), 'LEFT'),
('ALIGN', (2, 0), (2, 0), 'RIGHT'),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('BOX', (3, 0), (3, 0), 0.25, colors.darkgray),
('FONT', (0, 0), (-1, -1), 'Ubuntu'),
('SPAN', (0, 0), (0, 1)),
]))
self.elements.append(header_table)
示例4: genBandStatsTable
def genBandStatsTable(self):
data = [[Paragraph('<b>Band</b>', self.styleSheet)
, Paragraph('<b>#Proposals</b>', self.styleSheet)
, Paragraph('<b>Req Hrs</b>', self.styleSheet)
]]
bandStats = {}
for rcvr in Receiver.objects.all():
bandStats[rcvr.code] = (0, 0)
for p in self.proposals:
bands = p.bands()
backends = p.backends()
if 'Z' in backends:
bands += 'Z'
for band in bands:
num, time = bandStats.get(band, (0,0))
bandStats[band] = (num + 1, time + (p.requestedTime() / float(len(bands))))
sortedBandStats = sorted(bandStats.iteritems(), key = lambda stat: stat[0])
for band, stats in sortedBandStats:
data.append([Paragraph(band, self.styleSheet)
, Paragraph('%s' % stats[0], self.styleSheet)
, Paragraph('%s' % round(stats[1], 2), self.styleSheet)
])
bandStatsTable = Table(data, colWidths = [50, 50, 50])
bandStatsTable.setStyle(self.tableStyle)
return bandStatsTable
示例5: outputtopdf
def outputtopdf(outputfile,title,labels,db,resdb):
import logging
log = logging.getLogger('outputtopdf')
try:
from reportlab.platypus import TableStyle, Table, SimpleDocTemplate, Paragraph
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfgen import canvas
except ImportError:
log.error('Reportlab was not found. To export to pdf you need to have reportlab installed. Check out www.reportlab.org')
return
log.debug('ok reportlab library found')
styles = getSampleStyleSheet()
rows=list()
rows.append(labels)
for k in db.keys():
cols = [k,db[k]]
if resdb is not None:
if resdb.has_key(k):
cols.append(resdb[k])
else:
cols.append('N/A')
rows.append(cols)
t=Table(rows)
mytable = TableStyle([('BACKGROUND',(0,0),(-1,0),colors.black),
('TEXTCOLOR',(0,0),(-1,0),colors.white)])
t.setStyle(mytable)
doc = SimpleDocTemplate(outputfile)
elements = []
style = styles["Heading1"]
Title = Paragraph(title,style)
elements.append(Title)
elements.append(t)
doc.build(elements)
示例6: add_info
def add_info(self):
ptext = "<b><font size=14>Report Info</font></b>"
self.Story.append(Paragraph(ptext, self.styles["BodyText"]))
self.Story.append(Spacer(1, 0.1 * inch))
data = [
["Request Name", self.request["custom_name"]],
["Request Id", str(self.request["_id"])],
["Email", self.request["email"]],
["Generated on", self.time_str()],
[
"Download Link",
'<a href="http://{0}/query/#/status/{1}">{0}/query/#/status/{1}</a>'.format(
self.download_server, self.request["_id"]
),
],
]
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)
示例7: build_chart
def build_chart(data, column, order, title):
"build chart"
headings = [('', _('Address'), _('Count'), _('Volume'), '')]
rows = [[draw_square(PIE_CHART_COLORS[index]),
tds_trunc(row[column], 45), row['num_count'],
filesizeformat(row['total_size']), '']
for index, row in enumerate(data)]
if len(rows) != 10:
missing = 10 - len(rows)
add_rows = [
('', '', '', '', '') for ind in range(missing)
]
rows.extend(add_rows)
headings.extend(rows)
dat = [row[order] for row in data]
total = sum(dat)
labels = [
("%.1f%%" % ((1.0 * row[order] / total) * 100))
for row in data
]
pie = PieChart()
pie.chart.labels = labels
pie.chart.data = dat
headings[1][4] = pie
table_with_style = Table(headings, [0.2 * inch,
2.8 * inch, 0.5 * inch, 0.7 * inch, 3.2 * inch])
table_with_style.setStyle(table_style)
paragraph = Paragraph(title, styles['Heading1'])
return [paragraph, table_with_style]
示例8: table
def table(data):
"""
return list, so "extend" method should be used.
"""
"""
para_style = STYLES["BodyText"]
para_style.wordWrap = 'CJK'
para_style.backColor = colors.red
table_data = [[Paragraph(cell, para_style) for cell in row] for row in data]
"""
table_data = data
table_style = TableStyle([
('ALIGN',(0,0),(-1,0),'CENTER'),
('ALIGN',(0,1),(0,-1),'LEFT'),
('ALIGN',(1,1),(-1,-1),'RIGHT'),
('VALIGN',(0,0),(-1,-1),'MIDDLE'),
('BOX', (0,0), (-1,0), 2, colors.black),
('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
('TEXTCOLOR',(1,1),(-2,-2),colors.red),
('BACKGROUND', (0,0), (-1,0), colors.black),
('TEXTCOLOR',(0,0),(-1,0),colors.white),
('TEXTCOLOR',(0,1),(-1,-1),colors.black),
#('VALIGN',(0,0),(0,-1),'TOP'),
#('TEXTCOLOR',(0,0),(0,-1),colors.blue),
])
for i in range(1, len(table_data)):
if i%2 == 0:
table_style.add('BACKGROUND', (0,i), (-1,i),
colors.Color(.835,.91,.976))
t = Table(table_data)
t.setStyle(table_style)
return [t]
示例9: add_form
def add_form(self, num_rows, form, is_mini_form=False):
cols = form.get_fields(print_only=True)
field_aliases, field_widths = ['ID'], [5]
field_aliases.extend([c.col_alias for c in cols])
field_widths.extend([c.display_width for c in cols])
field_widths = [n/100.0*self.inner_width for n in field_widths] #normalize
x, y = self.origin_x, self.origin_y + self.qr_size
width = self.inner_width
height = self.inner_height - self.qr_size - 35
if is_mini_form:
height = Units.pixel_to_point(300) #only render a 300-pixel tall form
data, rowheights, header_flowables = [], [39], []
style = ParagraphStyle(name='Helvetica', fontName='Helvetica', fontSize=10)
for a in field_aliases:
header_flowables.append(Paragraph('<b>%s</b>' % a, style))
data.append(header_flowables)
for n in range(0, num_rows):
data.append(['', '', '', ''])
rowheights.append(39)
t=Table(data, field_widths, rowheights)
GRID_STYLE = TableStyle([
('GRID', (0,0), (-1,-1), 0.25, colors.black),
('FONT', (0,0), (-1,-1), 'HandSean'),
('BOX',(0,0),(-1,-1),2,colors.black)
])
t.setStyle(GRID_STYLE)
frame = Frame(x, y, width, height, showBoundary=0, leftPadding=0,
bottomPadding=0, rightPadding=0, topPadding=0)
frame.addFromList([t], self.canvas)
示例10: build_marco_logo_y_empresa
def build_marco_logo_y_empresa(dde):
"""
dde es una lista con la ruta al logotipo de la empresa (o None) y una
serie de líneas de texto con los datos a mostrar de la empresa.
Devuelve una tabla con los marcos transparentes con el logo y las
líneas.
"""
if dde[0] != None:
logo = Image(dde[0])
logo.drawHeight = 2*cm * logo.drawHeight / logo.drawWidth
logo.drawWidth = 2*cm
else:
logo = Paragraph("", estilos["Normal"])
lineas_empresa = dde[1:]
if len(lineas_empresa) <= 3:
empresa = Preformatted("\n".join(lineas_empresa), estilos["Normal"])
else:
texto_empresa = lineas_empresa[0] + "\n"
#+ ". ".join(lineas_empresa[1:])
resto_lineas = lineas_empresa[1:]
pivot = len(resto_lineas)/2
r1, r2 = resto_lineas[:pivot], resto_lineas[pivot:]
texto_empresa += ". ".join(r1) + "\n" + ". ".join(r2)
empresa = Preformatted(texto_empresa, estilos["Normal"])
datos = [[logo, empresa]]
tabla = Table(datos,
colWidths = (PAGE_WIDTH * 0.25,
PAGE_WIDTH * 0.65))
tabla.setStyle(TableStyle([
("ALIGN", (0, 0), (1, 0), "RIGHT"),
("ALIGN", (1, 0), (-1, -1), "LEFT"),
("VALIGN", (0, 0), (-1, -1), "CENTER"),
]))
return tabla
示例11: cuadritos_en_ruta
def cuadritos_en_ruta():
"""
Devuelve dos flowables:
Un texto centrado con el texto de "ENVASES VACÍOS..." y una tabla
con el texto y los cuadraditos que se rellenan a mano durante la ruta
del transportista.
"""
estilo_centrado = ParagraphStyle("Alineado centrado",
parent=estilos["Normal"])
estilo_centrado.alignment = enums.TA_CENTER
cab = Paragraph(escribe("ENVASES VACÍOS SIN LIMPIAR, 3 A.D.R."),
estilo_centrado)
datos = [["G.R.G. 1.000L", "", "", "BIDONES 100L", ""],
["", "", "", "", ""],
["DEPÓSITO 600L", "", "", "BIDONES 50L", ""],
["", "", "", "", ""],
["BIDONES 200L", "", "", "GARRAFAS 60L", ""],
["", "", "", "", ""],
["BIDONES 25L", "", "", "BIDONES 10L", ""]]
datos = [[escribe(c) for c in fila] for fila in datos]
tabla = Table(datos,
colWidths = (3*cm, 0.75*cm, 5*cm, 3*cm, 0.75*cm))
tabla.setStyle(TableStyle([
("BOX", (1, 0), (1, 0), 1.0, colors.black),
("BOX", (4, 0), (4, 0), 1.0, colors.black),
("BOX", (1, 2), (1, 2), 1.0, colors.black),
("BOX", (4, 2), (4, 2), 1.0, colors.black),
("BOX", (1, 4), (1, 4), 1.0, colors.black),
("BOX", (4, 4), (4, 4), 1.0, colors.black),
("BOX", (1, 6), (1, 6), 1.0, colors.black),
("BOX", (4, 6), (4, 6), 1.0, colors.black),
]))
return KeepTogether([Spacer(1, 0.3*cm), cab, Spacer(1, 0.5*cm), tabla])
示例12: build_tabla_contenido
def build_tabla_contenido(data):
"""
Construye la tabla del contenido del albaranSalida.
Los datos deben venir en listas. Cada línea de la tabla, una tupla o lista
con el código, descripción, cantidad, precio unitario (con dto. si lo
lleva e IVA) y número de pedido.
El precio y cantidad deben ser flotantes para poder calcular el subtotal.
"""
estilo_cabecera_tabla = ParagraphStyle("Cabecera tabla",
parent=estilos["Heading3"])
estilo_cabecera_tabla.fontName = "Times-Bold"
estilo_cabecera_tabla.alignment = enums.TA_CENTER
estilo_numeros_tabla = ParagraphStyle("Números tabla",
parent=estilos["Normal"])
estilo_numeros_tabla.alignment = enums.TA_RIGHT
datos = [(Paragraph(escribe("Código"), estilo_cabecera_tabla),
Paragraph(escribe("Descripción"), estilo_cabecera_tabla),
Paragraph("Cantidad", estilo_cabecera_tabla),
Paragraph("Precio/U", estilo_cabecera_tabla),
#Paragraph("Total c/IVA", estilo_cabecera_tabla),
# CWT: Prefiere la carta de portes sin IVA.
Paragraph("Total", estilo_cabecera_tabla),
Paragraph(escribe("Nº Pedido"), estilo_cabecera_tabla))
]
for d in data:
fila = (escribe(d[0]),
Paragraph(escribe(d[1]),estilos["Normal"]),
Paragraph(escribe(utils.float2str(d[2])),estilo_numeros_tabla),
Paragraph(escribe(utils.float2str(d[3])),estilo_numeros_tabla),
Paragraph(escribe(utils.float2str(d[2] * d[3])),
estilo_numeros_tabla),
escribe(d[4])
)
datos.append(fila)
tabla = Table(datos,
colWidths = (PAGE_WIDTH * 0.13,
PAGE_WIDTH * 0.35,
PAGE_WIDTH * 0.09,
PAGE_WIDTH * 0.09,
PAGE_WIDTH * 0.13,
PAGE_WIDTH * 0.11),
repeatRows = 1)
tabla.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey),
("LINEBEFORE", (0, 0), (-1, -1), 0.25, colors.black),
("LINEBELOW", (0, 0), (-1, 0), 1.0, colors.black),
("LINEBELOW", (0, "splitlast"), (-1, "splitlast"), 1.0, colors.black),
("BOX", (0, 0), (-1, -1), 1.0, colors.black),
("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
("VALIGN", (0, 0), (-1, 0), "CENTER"),
("VALIGN", (0, 0), (0, -1), "TOP"),
("ALIGN", (0, 0), (-1, 0), "CENTER"),
("ALIGN", (-3, 1), (-1, -1), "RIGHT"),
#("ALIGN", (0, 1), (0, -1), "DECIMAL"), <- No puedo cambiar
# el pivotChar de "." a ",". No me vale.
("ALIGN", (-1, 1), (-1, -1), "CENTER"),
("ALIGN", (0, 1), (0, -1), "CENTER"),
#("RIGHTPADDING", (0, 1), (0, -1), 0.75 * cm),
]))
return tabla
示例13: build_encabezado
def build_encabezado(datos_albaran):
"""
Devuelve una tabla de dos líneas con los datos del albarán, que es un
diccionario de: fecha -como texto-, número (de albarán), kilos,
bultos.
"""
datos_albaran = sanitize(datos_albaran)
datos = [["Fecha", escribe("Nº Albarán"), "Kilos", "Bultos"],
[datos_albaran["fecha"], datos_albaran["número"],
datos_albaran["kilos"], datos_albaran["bultos"]]]
estilo_centrado = ParagraphStyle("Alineado centrado",
parent=estilos["Normal"])
estilo_centrado.alignment = enums.TA_CENTER
estilo_centrado.fontSize += 2
datos = [[Paragraph(celda, estilos["Normal"]) for celda in datos[0]] ,
[Paragraph(celda, estilo_centrado) for celda in datos[1]]]
tabla = Table(datos,
colWidths = (PAGE_WIDTH * 0.9/4,)*4)
tabla.setStyle(TableStyle([
("BOX", (0, 1), (-1, -1), 1.0, colors.black),
("INNERGRID", (0, 1), (-1, -1), 0.25, colors.black),
("ALIGN", (0, 0), (-1, 0), "LEFT"),
("ALIGN", (0, 1), (-1, 1), "CENTER"),
]))
return tabla
示例14: Cases
def Cases(self, modele=[1, 1, 1, 0, 1, 1, 1], texte="", largeurColonnes=10, couleur=(0.8, 0.8, 0.8)) :
"""
1 = Case à avec texte avec cadre
2 = Case avec texte sans cadre
0 = Case sans texte et sans cadre
"""
if texte == None : texte = ""
dataTableau = []
largeursColonnes = []
listeStyles = [
('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
('ALIGN', (0, 0), (-1, -1), "CENTER"),
]
indexColonne = 0
indexTexte = 0
for code in modele :
largeursColonnes.append(largeurColonnes)
if code == 1 or code == 2 :
if len(texte) > indexTexte :
dataTableau.append(texte[indexTexte])
indexTexte += 1
else :
dataTableau.append("")
if code == 1 :
listeStyles.append(('GRID', (indexColonne, 0), (indexColonne, -1), 0.25, couleur))
else :
dataTableau.append("")
indexColonne += 1
style = TableStyle(listeStyles)
tableau = Table([dataTableau,], largeursColonnes)
tableau.setStyle(style)
return tableau
示例15: reporte_contactos
def reporte_contactos(request):
print ("Genero el PDF");
response = HttpResponse(content_type='application/pdf')
pdf_name = "contactos.pdf" # llamado clientes
# la linea 26 es por si deseas descargar el pdf a tu computadora
# response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
buff = BytesIO()
doc = SimpleDocTemplate(buff,
pagesize=letter,
rightMargin=40,
leftMargin=40,
topMargin=60,
bottomMargin=18,
)
contactos = []
styles = getSampleStyleSheet()
header = Paragraph("Listado de Contactos de Proveedores", styles['Heading1'])
contactos.append(header)
headings = ('Nombre','Telefono','Correo','Proveedor','Fecha Creacion')
allcontactos = [(c.nombre,c.telefono,c.correo,c.proveedor.nombre,c.fecha_creacion) for c in ContactoProveedor.objects.all()]
print (allcontactos);
t = Table([headings] + allcontactos)
t.setStyle(TableStyle(
[
('GRID', (0, 0), (12, -1), 1, colors.dodgerblue),
('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
]
))
contactos.append(t)
doc.build(contactos)
response.write(buff.getvalue())
buff.close()
return response