Z
I expect this to serve you, I had the same problem in a report system and I did not find how to do it, so I implemented it, it is simply to page the information that will be added to the table, taking into account the height that occupies each cell of the table, the logic is as follows: First calculate the number of pixels that exist from the beginning of the page(in this case, the start is the end of the page, as the same page Look at the code here:def tabla(self, pdf, partes, y):
width, height = A4
headers = ('Unidad', 'Fecha', 'Produccion', 'Real', 'Plan', 'Cantidad', 'TOTAL')
items = [(item.unidad,
item.fecha,
item.produccion,
item.real,
item.plan,
item.cant,
item.total) for item in partes]
table = Table([headers] + items, colWidths=80)
table.setStyle(TableStyle(
[
('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
('BOX', (0, 0), (-1, -1), 0.25, colors.black),
('ALING', (0, 0), (3, 0), 'CENTER'),
('GRID', (0, 0), (6, -1), 1, colors.black),
('BACKGROUND', (0, 0), (-1, 0), colors.lightslategray),
('FONTSIZE', (0, 0), (-1, -1), 10),
]
))
table.wrapOn(pdf, width, height)
table.drawOn(pdf, 20, y)
pdf.showPage()
def get(self, request):
response = HttpResponse(content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename = Reporte'
buff = BytesIO()
pdf = canvas.Canvas(buff, pagesize=portrait(A4))
partes = Parte_Diario_Unidad.objects.filter(**filtros).order_by('unidad', 'fecha')
####################################################################################
esta es la parte de la paginacion
max_len = 25 # se define la cantidad por pagina(previamente calculado)
heigth_data = len(partes) # se obtiene la longitud de la lista de datos a mostrar
if heigth_data <= max_len: # si la cantidad de elementos de la lista es menor que la cantidad definida por paginas, en este caso 25 se pasa la lista tal cual
partes = list(partes)
self.tabla(pdf, partes, y=600 - (len(partes) * 18))
elif heigth_data > max_len:
partes = list(partes)[::-1] # esto es solo para invertir la lista
pages_needed = math.ceil(float(heigth_data / max_len)) #se obtiene la cantidad de paginas necesarias a partir de la cantidad de datos en la lista
iterator = max_len # se guarda el valor en un iterador
for page in range(0, int(pages_needed)): # esta parte se explica por si sola
record = []
if max_len < len(partes):
iterator = max_len
else:
iterator = len(partes)
for i in range(0, iterator):
record.append(partes.pop())
self.set_page_number(pdf, number_page=(page + 1)) # una funcion que hice para a;adir el numero de pagina
self.tabla(pdf, record, y=600 - (len(record) * 18.3)) # aqui y es la coordenada y donde empezara a dibujar la tabla
pdf.save()
pdf = buff.getvalue()
buff.close()
response.write(pdf)
return response