Home > other >  adding table with Django and report lab
adding table with Django and report lab

Time:10-12

The following code works for pdf creation, what I wanted is put the data to a table

def pdf_view(request):
    enc = pdfencrypt.StandardEncryption("pass", canPrint=0)
    buf = io.BytesIO()
    c = canvas.Canvas(buf, encrypt=enc)
    width, height = A4
    textob = c.beginText()
    textob.setTextOrigin(inch, inch)
    textob.setFont("Helvetica", 14)
    lines = []
    users = User.objects.filter(is_staff=False)
    for user in users:
        lines.append(user.username)
        lines.append(user.email)
        lines.append(user.first_name)
    for line in lines:
        textob.textLine(line)
    c.drawText(textob)
    c.showPage()
    c.save()
    buf.seek(0)
    return FileResponse(buf, as_attachment=True, filename='users.pdf')

I tried to append the data to a table, what I tried is as follows

def pdf_view(request):
    enc = pdfencrypt.StandardEncryption("pass", canPrint=0)
    buf = io.BytesIO()
    c = canvas.Canvas(buf, encrypt=enc)
    width, height = A4
    textob = c.beginText()
    textob.setTextOrigin(inch, inch)
    textob.setFont("Helvetica", 14)
    lines = []
    users = User.objects.filter(is_staff=False)
    for user in users:
        lines.append(user.username)
        lines.append(user.email)
        lines.append(user.first_name)
    table = Table(lines, colWidths=10 * mm)
    table.setStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                    ("ALIGN", (0, 0), (-1, -1), "CENTER"),
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)])

    table.wrapOn(c, width, height)
    table.drawOn(c, 0 * mm, 5 * mm)

    styles = getSampleStyleSheet()
    ptext = "This is an example."
    p = Paragraph(ptext, style=styles["Normal"])
    p.wrapOn(c, 50 * mm, 50 * mm)  # size of 'textbox' for linebreaks etc.
    p.drawOn(c, 0 * mm, 0 * mm)  # position of text / where to draw
    c.save()
    buf.seek(0)
    return FileResponse(buf, as_attachment=True, filename='users.pdf')

This is printing single letter on each row of the table, how I can fix the issue and the data to a simple table, any sot of help is much appreciated.

CodePudding user response:

The problem is in your for-loop. Change it to this:

    for user in users:
        lines.append((user.username, user.email, user.first_name))
  • Related