Generate multiple qr codes in one pdf file using reportlab and django framework

眉间皱痕 提交于 2019-12-06 04:27:01

问题


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:


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



来源:https://stackoverflow.com/questions/13129015/generate-multiple-qr-codes-in-one-pdf-file-using-reportlab-and-django-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!