Using reportlab, How can I generate a series of qr codes and put them in one pdf and then open it on the user browser. Here is my attempt. Thanks in advance. For this code below, nothing happens. I was expecting to be prompted to save the pdf file.
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
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
p = canvas.Canvas(response)
qrw = QrCodeWidget('Helo World!')
b = qrw.getBounds()
w=b[2]-b[0]
h=b[3]-b[1]
d = Drawing(45,45,transform=[45./w,0,0,45./h,0,0])
d.add(qrw)
renderPDF.draw(d, p, 1, 1)
p.showPage()
p.save()
return response
Your code worked for me, though I suspect it's because you didn't encapsulate it in a view?
For example, myapp/views.py
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
# Create your views here.
def test_qr(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
p = canvas.Canvas(response)
qrw = QrCodeWidget('Helo World!')
b = qrw.getBounds()
w=b[2]-b[0]
h=b[3]-b[1]
d = Drawing(45,45,transform=[45./w,0,0,45./h,0,0])
d.add(qrw)
renderPDF.draw(d, p, 1, 1)
p.showPage()
p.save()
return response
myproject/urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'myapp.views.test_qr'),
)
Opening my browser to say, http:127.0.0.1:8000 prompts me to download the pdf rendered with a QR code at the bottom left corner. If you're not sure how to use Django, I suggest reading through Django Book Online
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With