2012-10-29 15 views
5

Utilizzando reportlab, come posso generare una serie di codici qr e inserirli in un pdf e quindi aprirlo nel browser dell'utente. Ecco il mio tentativo. Grazie in anticipo. Per questo codice qui sotto, non succede nulla. Mi aspettavo di essere richiesto di salvare il file pdf.Generare più codici qr in un file pdf utilizzando reportlab e framework django

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 
+0

Puoi descrivere le tue difficoltà in un modo più specifico? Che cosa fa il tuo codice giusto/sbagliato, dove hai esattamente difficoltà ecc. – Rytmis

risposta

4

Il tuo codice ha funzionato per me, anche se sospetto che sia perché non l'hai incapsulato in una vista?

Ad esempio, frontend/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 

mioprogetto/urls.py

from django.conf.urls.defaults import patterns, include, url 

urlpatterns = patterns('', 
    url(r'^$', 'myapp.views.test_qr'), 
) 

apertura mio browser per dire, http: 127.0.0.1: 8000 mi spinge a scaricare il pdf reso con un codice QR nell'angolo in basso a sinistra. Se non sei sicuro di come usare Django, ti suggerisco di leggere attraverso Django Book Online

+0

Penso che il loro sia un problema di compatibilità del browser. Funziona in firefox ma non in chrome (15) – user1783848

+1

Ho dovuto cambiare 'HttpResponse (mimetype = 'application/pdf')' a 'HttpResponse (content_type = 'application/pdf')' per l'esempio di lavoro – bjesus

Problemi correlati