使用reportlab和django框架在一个pdf文件中生成多个QR码 [英] Generate multiple qr codes in one pdf file using reportlab and django framework

查看:52
本文介绍了使用reportlab和django框架在一个pdf文件中生成多个QR码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用reportlab,如何生成一系列qr代码并将其放入一个pdf中,然后在用户浏览器中将其打开.这是我的尝试.提前致谢.对于下面的这段代码,什么也不会发生.我原本会被提示保存pdf文件.

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?

例如,myapp/views.py

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

myproject/urls.py

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

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

打开浏览器说http:127.0.0.1:8000会提示我下载在左下角使用QR码呈现的pdf.如果您不确定如何使用Django,建议您阅读 Django在线丛书

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

这篇关于使用reportlab和django框架在一个pdf文件中生成多个QR码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆