2010-09-22 122 views
2

我見過很多reportlab繪圖示例。生成圖形不是問題,我似乎無法弄清楚如何在PDF上顯示圖形。將圖添加到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) 頭= p.beginText(100,765) header.textLine( 「頁標題文本」) p.drawText(頭)

回答

0

我寫這前一段時間,但它是該網站上最受歡迎的文章之一,所以我想它適用於某些網站。

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

如果這還不夠,通過讓你,讓我知道,我會回來,以幫助更多後來當我有更多的時間。

+4

鏈接不起作用。請發佈信息或刪除答案。 – Elliptica 2017-06-30 21:17:49

+0

工作鏈接: http://protocolostomy.com/2008/10/22/generating-reports-with-charts-using-python-reportlab/ – 2017-11-10 18:04:53

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

我改進的答案:https://stackoverflow.com/a/47229335/6166911 – 2017-11-10 18:52:27

0

如果您需要將圖表從添加到您的畫布使用d.drawOn(p,0,0)代替p.drawPath(d)

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('/') 

輸出這裏:

Generated pdf graph with reportlab 2.7