1

It seems to be a very easy problem but I can not manage it :(

I have a view which should create for me a pdf file. I need there a loop and I don't know why it doesn't work. I need to print all of list's questions. I have checked and I have 3 questions in "pytanie" list but my loop print me only one question (last question)

for i in range(len(pytanie)):
    p = canvas.Canvas(response)
    p.drawString(10, 800, ' '+ pytanie[i].title)   

The whole code in this view

from reportlab.pdfgen import canvas
from django.http import HttpResponse
from reportlab.graphics.shapes import Drawing 
from reportlab.graphics.barcode.qr import QrCodeWidget 
from reportlab.graphics import renderPDF
from django.contrib.auth.models import User
from pytania.models import Pytanie


def test_qr(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="egzamin.pdf"'

    pytanie = Pytanie.objects.all()

    for i in range(len(pytanie)):
        p = canvas.Canvas(response)
        p.drawString(10, 800, ' '+ pytanie[i].title)        


    qrw = QrCodeWidget('a') 
    b = qrw.getBounds()

    w=b[2]-b[0] 
    h=b[3]-b[1] 

    d = Drawing(200,200,transform=[200./w,0,0,200./h,0,0]) 
    d.add(qrw)

    renderPDF.draw(d, p, 1, 1)

    p.showPage()
    p.save()
    return response

2 Answers 2

2
  1. You should just loop over Pytanie.objects.all():
  2. Put the initialization of p outside the loop

    p = canvas.Canvas(response)
    for pytanie in Pytanie.objects.all():        
        p.drawString(10, 800, ' '+ pytanie.title)  
    
Sign up to request clarification or add additional context in comments.

2 Comments

I still get only the last question in my pdf :(
ah, i see now, you constantly reinitialize p
1

I think you should change coordinates of the string:

p = canvas.Canvas(response)
for i, pytanie in enumerate(Pytanie.objects.all()):
    p.drawString(10, 800 + i*10, ' '+ pytanie.title)  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.