3

我看过很多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) header.textLine("页面标题文本") p.drawText(header)

4

4 回答 4

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')
于 2010-12-17T23:25:04.267 回答
1

如果您需要将图表添加到画布使用d.drawOn(p,0,0)而不是p.drawPath(d)

于 2016-03-21T17:47:38.590 回答
0

我前段时间写过这篇文章,但它是该网站上最受欢迎的文章之一,所以我想它对某些人有用。

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

如果这还不足以让您通过,请告诉我,稍后我有更多时间时会回来提供更多帮助。

于 2010-09-22T23:19:19.957 回答
0

来自@siguy 示例的改进答案,使用reportlab 2.7。

from reportlab.lib.colors import red
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie

def savePdfGraph(request):
    d = Drawing(width=400, height=200)
    pc = Pie()
    pc.x = 150
    pc.y = 50
    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 = red
    d.add(pc)

    filename = 'test'
    base_dir = '/home/'
    path = os.path.join(base_dir, filename)
    d.save(formats=['pdf'], outDir=None, fnRoot=path)
    return redirect('/')

此处输出:

使用reportlab 2.7生成的pdf图

于 2017-11-10T18:50:21.443 回答