Snake's Home

ReportLab 实践

python 生成报告, ReportLab 实践,网上找的例子,自己实践了一把。

文档

然后照着文档,例子

写成了一个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from reportlab.graphics.shapes import Drawing  
from reportlab.graphics.charts.barcharts import VerticalBarChart
from urllib import urlopen
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF
drawing = Drawing(400, 200)
data = [(13, 5, 20),(14, 6, 21)]
bc = VerticalBarChart()
bc.x = 50
bc.y = 50
bc.height = 125
bc.width = 300
bc.data = data
bc.strokeColor = colors.black
bc.valueAxis.valueMin = 0
bc.valueAxis.valueMax = 50
bc.valueAxis.valueStep = 10
bc.categoryAxis.labels.boxAnchor ='ne'
bc.categoryAxis.labels.dx = 8
bc.categoryAxis.labels.dy = -2
bc.categoryAxis.labels.angle = 30
bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99']
drawing.add(bc)

drawing.add(String(250,150,"ss", fontSize=14,fillColor=colors.red))
renderPDF.drawToFile(drawing,'report2.pdf','API')

然后按照

学习了下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python  
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
import os
def disk_report():
p = os.popen("df -h")
# print p.stdout.readlines()
return p.readlines()
def create_pdf(input, output="disk_report.pdf"):
now = datetime.datetime.today()
date = now.strftime("%Y-%m-%d %H:%M:%S")
c = canvas.Canvas(output)
textobject = c.beginText()
textobject.setTextOrigin(inch, 11*inch)
textobject.textLines('''''Disk Capcity Report: %s''' %date)
for line in input:
textobject.textLine(line.strip())
c.drawText(textobject)
c.showPage()
c.save()
report = disk_report()
create_pdf(report)

再练习:

1
2
3
4
5
6
7
8
#!/usr/bin/python  
from reportlab.pdfgen import canvas
def hello():
c = canvas.Canvas("helloworld.pdf")
c.drawString(100,100,"Hello,World")
c.showPage()
c.save()
hello()