我正在尝试使用Reportlab将QrCode添加到我的PDF中,但出现IOerror。我之前已经成功添加了条形码,但是QrCode似乎有点棘手。
这是我的QrCode代码:
def get_QRcode(self,inventory):
receipt = str(inventory.identifier)
qr_code = qr.QrCodeWidget(receipt)
bounds = qr_code.getBounds()
width = bounds[2] - bounds[1]
height = bounds[3] - bounds[1]
d = Drawing(45,45, transform = [45./width,0,0,45./height,0,0])
d.add(qr_code)
filename = tempfile.mkstemp()[1] + '.png'
d.save(filename)
return filename
这是我的QrCode附录:
parts.append(Image(self.qrCode, width=.15* 0.35 *inch, height=.2*.25*inch))
尝试运行此程序后,我得到了:
IOError at /inventories/download_tag/2525/
Cannot open resource "/tmp/tmpUf7ASf.png"
fileName='/tmp/tmpUf7ASf.png' identity=[ImageReader@0x7f6665819490 filename='/tmp/tmpUf7ASf.png']
感谢您的帮助!谢谢
我可以分享完成的方式,但是我的实现是将其直接绘制在画布上,然后将其添加到文档模板的脚注中。您的方法是先创建一个png,然后将其添加(我对一个图形对象进行了类似的操作,但是后来我使用了pdfrw,这是一个很好的插件,刚开始时我对文件夹的写访问有些费力)。看看下面是否适合您。
def get_footer(self):
def func(canvas, doc):
canvas.saveState()
# draw a QR code
receipt = str(inventory.identifier)
qr_code = qr.QrCodeWidget(f'{receipt}')
bounds = qr_code.getBounds()
width = bounds[2] - bounds[0]
height = bounds[3] - bounds[1]
d = Drawing(60, 60, transform=[60. / width, 0, 0, 60. / height, 0, 0])
d.add(qr_code)
d.drawOn(canvas, 1.77 * cm, 259.55 * mm)
canvas.restoreState()
return func
frontpage = PageTemplate(id='FrontPage',
onPage=self.get_footer(),
frames=[frame1, frame2],
)