Python平臺的優秀PDF報表類庫Reportlab。它不屬於Python的標準類庫,因此必須手動下載類庫包並安裝:
yum install python-reportlab -y
這篇文章將介紹reportlab中基本經常使用的api,使用canvas畫出一份整潔的PDF報表。詳細內容參考reportlab的官方user guide。python
示例1、生成一段文字
shell
#!/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()
示例2、生成單個文件的pdf
canvas
#須要安裝字體 yum install wqy-* -y #!/usr/bin/python import datetime import subprocess import codecs from reportlab.pdfgen import canvas from reportlab.lib.units import inch from reportlab.lib.pagesizes import A4, landscape import reportlab.pdfbase.ttfonts reportlab.pdfbase.pdfmetrics.registerFont(reportlab.pdfbase.ttfonts.TTFont('song', '/usr/share/fonts/cn/msjh.ttf')) import reportlab.lib.fonts def disk1_report(): p1 = subprocess.Popen("cat cmd1.log ",shell=True,stdout=subprocess.PIPE) return p1.stdout.readlines() def create_pdf(input,output="disk1.pdf"): now = datetime.datetime.today() date = now.strftime("%h %d %Y %H:%M:%S") c = canvas.Canvas(output,pagesize=A4) c.setFont('song',10) textobject = c.beginText() textobject.setTextOrigin(1*inch,11*inch) textobject.textLines('''Disk Capacity Report: %s ''' % date ) for line in input: textobject.textLine(line.strip()) c.drawText(textobject) c.showPage() c.save() report = disk1_report() create_pdf(report)
示例3、循環生成指定目錄下的多個文件()
api
#!/usr/bin/python import os import os.path import datetime import subprocess from reportlab.lib.pagesizes import A4, landscape from reportlab.pdfgen import canvas from reportlab.lib.units import inch logdir = "/var/www/device/check_log" for root,dirs,filenames in os.walk(logdir): for filename in filenames: v = root+os.sep+filename os.environ['file'] = str(v) def disk_report(): p = subprocess.Popen("cat $file ",shell=True,stdout=subprocess.PIPE) return p.stdout.readlines() def create_pdf(input,output="/var/www/device/check_pdf/"+filename+".pdf"): now = datetime.datetime.today() date = now.strftime("%h %d %Y %H:%M:%S") c = canvas.Canvas(output,pagesize=A4) textobject = c.beginText() textobject.setTextOrigin(1*inch,11*inch) textobject.textLines('''Disk Capacity Report: %s ''' % date ) for line in input: textobject.textLine(line.strip()) c.drawText(textobject) c.showPage() c.save() report = disk_report() create_pdf(report)