我想在reportlab生成的pdf文档中放置一个图像(更精确的条形码)。 我可以把它放在一张桌子里。这与createBarcodeDrawing()完美配合。
关键是我想在每页上更改条形码。 因此,我想把它放在一个画布制作者。
无论我使用什么方法(drawImage(),drawInLineImage(),...),我总是有错误。 我甚至试图使用Reportlab [ Platypus ] - Image does not render中的CustomImage而没有任何成功。 因此,我的问题是如何在画布中绘制图像.Canvas?
有人可以帮忙吗? 先感谢您 大教堂 (我不是专业人士)
我在http://www.tylerlesmann.com/2009/jan/28/writing-pdfs-python-adding-images/上读到了一条评论,我试过了:
img = 'apple-logo.jpg'
self.drawInlineImage('C:\\'+img,20,20)
这样可行,而'C:\ apple-logo.jpg'则不行!! 尽管如此,我还是不知道如何绘制条形码而不将其写入文件之前! 如果有人设法做到这一点,我真的很感激。 再见
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
class NumberedCanvas(canvas.Canvas):
def __init__(self, *args, **kwargs):
canvas.Canvas.__init__(self, *args, **kwargs)
self._saved_page_states = []
def showPage(self):
self._saved_page_states.append(dict(self.__dict__))
self._startPage()
def save(self):
"""add page info to each page (page x of y)"""
num_pages = len(self._saved_page_states)
for state in self._saved_page_states:
self.__dict__.update(state)
page_num = self._pageNumber
mybarcode = createBarcodeDrawing('QR', value= 'www.mousevspython.com - Page %s'%page_num)
self.drawInlineImage(mybarcode,20,20)
canvas.Canvas.showPage(self)
canvas.Canvas.save(self)
def main():
import sys
import urllib2
from cStringIO import StringIO
from reportlab.platypus import SimpleDocTemplate, Image, Paragraph, PageBreak
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
#This is needed because ReportLab accepts the StringIO as a file-like object,
#but doesn't accept urllib2.urlopen's return value
def get_image(url):
u = urllib2.urlopen(url)
return StringIO(u.read())
styles = getSampleStyleSheet()
styleN = ParagraphStyle(styles['Normal'])
# build doc
if len(sys.argv) > 1:
fn = sys.argv[1]
else:
fn = "filename.pdf"
doc = SimpleDocTemplate(open(fn, "wb"))
elements = [
Paragraph("Hello,", styleN),
Image(get_image("http://www.red-dove.com/images/rdclogo.gif")),
PageBreak(),
Paragraph("world!", styleN),
Image(get_image("http://www.python.org/images/python-logo.gif")),
]
doc.build(elements, canvasmaker=NumberedCanvas)
if __name__ == "__main__":
main()
答案 0 :(得分:1)
你快到了。只需将self.drawImage(mybarcode,20,20)
替换为mybarcode.drawOn(self, 20, 20)
即可。条形码实际上不是图像,更像是可以导出到图像的条形码对象。作为旁注:您正在使用NumberedCanvas,这是一种获取总页数的黑客行为。正如我所看到的,你并不真正需要它,因为你只是使用当前的页码。如果您不需要总页数,则可以定义一个画布绘制功能,在每个页面上绘制条形码。为此你会做这样的事情:
def draw_barcode(canvas, doc):
canvas.saveState()
page_num = canvas._pageNumber
mybarcode = createBarcodeDrawing('QR', value= 'www.mousevspython.com - Page %s'%page_num)
mybarcode.drawOn(canvas, 20, 20)
canvas.restoreState()
[...]
# doc.build(elements, canvasmaker=NumberedCanvas)
doc.build(elements, onFirstPage=draw_barcode, onLaterPages=draw_barcode)