5

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
1
  • Can you please describe your difficulties in a more specific way? What does your code do right/wrong, where exactly are you having difficulties etc.
    – Rytmis
    Commented Oct 29, 2012 at 20:42

1 Answer 1

7

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

2
  • I think their is a browser compatibility issue. Works in firefox but does not in chrome (15) Commented Oct 30, 2012 at 4:23
  • 2
    I had to change HttpResponse(mimetype='application/pdf') to HttpResponse(content_type='application/pdf') for the example to work
    – bjesus
    Commented Sep 10, 2014 at 8:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.