Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Python 的 reportlab 生成 PDF 檔案

以下兩個程式整理自《Python.UNIX和Linux系統管理指南》 https://www.linuxidc.com/Linux/2013-06/86448.htm,示範如何從 Python 直接產出 PDF 報告。

pdf.py:寫入一行文字

#!/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()

流程固定為四步:建立 Canvas、在座標上繪製內容、showPage() 結束該頁、save() 輸出檔案。

diskreport.py:把 df -h 的結果寫成報告

#!/usr/bin/env python
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
def disk_report():
    p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE)
#   print p.stdout.readlines()
    return p.stdout.readlines()
def create_pdf(input, output="disk_report.pdf"):
    now = datetime.datetime.today()
    date = now.strftime("%h %d %Y %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)

這支程式的重點在於改用 text object:先 beginText() 取得文字物件、以 setTextOrigin 設定起始座標(這裡用 inch 單位,從頁面左上角附近開始),再逐行 textLine 寫入,最後 drawText 一次繪製。相比反覆呼叫 drawString,這種方式在大量文字時更省事,也方便統一設定字型與行距。

效果

Copyright © Linux教程網 All Rights Reserved