在Reportlab PDF中添加图表

3 投票
4 回答
9217 浏览
提问于 2025-04-16 04:28

我看到很多关于reportlab绘图的例子。生成图表不是问题,我就是搞不清楚怎么把图表显示在PDF上。

这是我的代码:

buffer = StringIO()
p = canvas.Canvas(buffer, pagesize = letter)

##### Beginning of code in question

d = Drawing(200, 100)
pc = Pie()
pc.x = 65
pc.y = 15
pc.width = 70
pc.height = 70
pc.data = [10,20,30,40,50,60]
pc.labels = ['a','b','c','d','e','f']
pc.slices.strokeWidth=0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2,2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red
d.add(pc)

p.drawPath(d) ### THIS DOES NOT WORK, but need something similar

#####End of Code in Question

p.showPage() #Page Two

p.save() # Saves the PDF and Returns with Response\

pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response

这是我显示文本的方式。

p.setFillColorRGB(1,1,1) // 这行代码是设置文本的颜色为白色。

header = p.beginText(100, 765) // 这行代码是开始在PDF的(100, 765)这个位置写文本。

header.textLine("Page Heading Text") // 这行代码是写入“页面标题文本”。

p.drawText(header) // 这行代码是把刚才写的文本画到PDF上。

4 个回答

1

如果你想把图表添加到你的画布上,使用 d.drawOn(p,0,0),而不是 p.drawPath(d)

3

直接跳过画布,使用绘图小部件就可以了——它会生成PDF文件:

d = Drawing(200, 100)
pc = Pie()
pc.x = 65
pc.y = 15
pc.width = 70
pc.height = 70
pc.data = [10,20,30,40,50,60]
pc.labels = ['a','b','c','d','e','f']
pc.slices.strokeWidth=0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2,2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red
d.add(pc)

d.save(formats=['pdf'],outDir=None,fnRoot='C:/test')
0

我之前写过这个内容,没想到它成了网站上最受欢迎的文章之一,所以我想这对一些人来说是有用的。

http://www.protocolostomy.com/2008/10/22/generating-reports-with-charts-using-python-reportlab/

如果这些内容还不够帮助你,告诉我,我会在有更多时间的时候再回来帮忙。

撰写回答