reportlab.graphics 提供向量繪圖基礎設施,charts 子模組內建折線圖、長條圖、餅圖等。**純 Python、無系統相依、輸出 PDF/PNG/SVG/GIF**,適合伺服器端自動生成報表。
pip install reportlab
# 中文字體:需 .ttc/.ttf 檔 (如 simsun.ttc、msjh.ttc),放入專案目錄或系統字體資料夾
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import traceback
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF, renderPM
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# ===== 1. 資料準備 =====
# 格式:[ ( (x1,y1), (x2,y2), ... ), # 線條 1
# ( (x1,y1), (x2,y2), ... ) ] # 線條 2
data = [
((1, 100), (2, 200), (3, 300), (4, 400), (5, 500)),
((1, 50), (2, 80), (3, 400), (4, 40), (5, 70))
]
# ===== 2. 建立繪圖區 =====
drawing = Drawing(500, 300) # 寬、高 (points, 1pt=1/72 inch)
# ===== 3. 設定折線圖 =====
lp = LinePlot()
lp.x = 50 # 圖表左下角 X
lp.y = 30 # 圖表左下角 Y
lp.width = 400 # 繪圖區寬
lp.height = 250 # 繪圖區高
lp.data = data
lp.joinedLines = 1 # 連線
lp.lines.symbol = makeMarker('FilledCircle') # 資料點標記
# X 軸
lp.xValueAxis.valueMin = 1
lp.xValueAxis.valueMax = 5
lp.xValueAxis.valueStep = 1
# Y 軸
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 500
lp.yValueAxis.valueStep = 100
drawing.add(lp)
# ===== 4. 中文標題 (需註冊字體) =====
# 字體檔需存在:專案目錄或系統字體路徑
FONT_PATH = 'simsun.ttc' # 請確認路徑
FONT_NAME = 'SimSun'
try:
pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_PATH))
except Exception as e:
print(f"字體註冊失敗:{e},將使用預設字體 (中文會顯示方塊)")
FONT_NAME = 'Helvetica'
title = Label()
title.fontName = FONT_NAME
title.fontSize = 14
title._text = '銷售趨勢圖示範' # 直接指定 unicode 字串
title.x = 250
title.y = 280
title.textAnchor = 'middle'
drawing.add(title)
# ===== 5. 座標軸標籤 =====
x_label = Label()
x_label._text = '月份'
x_label.fontName = FONT_NAME
x_label.fontSize = 10
x_label.x = 450
x_label.y = 20
x_label.textAnchor = 'middle'
drawing.add(x_label)
y_label = Label()
y_label._text = '營業額 (萬元)'
y_label.fontName = FONT_NAME
y_label.fontSize = 10
x_label.x = 30
x_label.y = 280
x_label.textAnchor = 'middle'
drawing.add(y_label)
# ===== 6. 輸出多格式 =====
try:
# PDF (向量、最佳品質)
renderPDF.drawToFile(drawing, 'chart.pdf', 'Sales Chart')
print("PDF 已輸出:chart.pdf")
# PNG (位圖、需 Pillow)
renderPM.drawToFile(drawing, 'chart.png', fmt='PNG')
print("PNG 已輸出:chart.png")
# GIF
renderPM.drawToFile(drawing, 'chart.gif', fmt='GIF')
print("GIF 已輸出:chart.gif")
except Exception:
traceback.print_exc()
| 類別/方法 | 用途 |
|---|---|
Drawing(w, h) | 畫布容器 |
LinePlot() | 折線圖核心 |
lp.data | 資料序列:list of tuple of (x,y) |
lp.joinedLines | 1=連線, 0=散點 |
lp.lines[i].strokeColor | 第 i 條線顏色 |
lp.lines[i].strokeWidth | 線寬 |
makeMarker('FilledCircle') | 資料點形狀:Circle, Square, Diamond, Dash... |
Label() | 文字標籤 (標題、軸標、圖例) |
pdfmetrics.registerFont(TTFont(name, path)) | 註冊 TTF/TTC 字體 |
renderPDF.drawToFile | 輸出 PDF |
renderPM.drawToFile | 輸出位圖 (PNG/GIF/JPEG),需 pip install pillow |
lp.lines[0].strokeColor = colors.red; lp.lines[1].strokeDashArray = [4,2]from reportlab.graphics.charts.legends import Legend 手動建立對應標籤。lp.xValueAxis.gridEnd = lp.width; lp.yValueAxis.gridEnd = lp.height + strokeColor = colors.grey。LogScale 或自訂 labelTextFormat。reportlab.pdfgen.canvas 加入超連結、書籤。| 問題 | 原因 | 解法 |
|---|---|---|
| 中文顯示方塊/亂碼 | 未註冊中文字體 | pdfmetrics.registerFont(TTFont('SimSun', 'simsun.ttc')),確認字體檔路徑 |
| 輸出 PNG 失敗 | 缺少 Pillow | pip install pillow |
| 座標軸刻度擠在一起 | valueStep 過小或範圍過大 | 調整 valueMin/Max/Step 或啟用 labelTextFormat 科學記號 |
| 圖表超出畫布 | x/y/width/height 設定錯誤 | 留白邊距:x=50, y=30, width=W-100, height=H-80 |
ReportLab Graphics 以**宣告式 API** 構建專業級統計圖表,**純 Python、無系統相依、輸出多格式**。掌握 Drawing → LinePlot → Label → renderPDF/PM 流程,並解決**中文字體註冊**這一關鍵點,即可在伺服器端自動化生成高品質圖表報表。