gpt4 book ai didi

python - 使用reportlab和django框架在一个pdf文件中生成多个二维码

转载 作者:太空狗 更新时间:2023-10-30 01:02:50 25 4
gpt4 key购买 nike

使用reportlab,如何生成一系列二维码并将它们放在一个pdf中,然后在用户浏览器上打开它。这是我的尝试。提前致谢。对于下面的这段代码,没有任何反应。我原以为会提示保存 pdf 文件。

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

最佳答案

你的代码对我有用,但我怀疑这是因为你没有将它封装在 View 中?

例如,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

我的项目/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 提示我下载左下角用二维码呈现的 pdf。如果您不确定如何使用 Django,我建议您阅读 Django Book Online

关于python - 使用reportlab和django框架在一个pdf文件中生成多个二维码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com