一、安裝
pip install reportlab
若有問題,就用 conda 環境下安裝,比較沒問題
二、執行範例
from reportlab.platypus import SimpleDocTemplate, Paragraph
fileName = "example.pdf"
pdfTemplate = SimpleDocTemplate(fileName)
story = []
story.append(Paragraph("Hello World"))
pdfTemplate.build(story)
即可產生PDF檔案
三、解決中文問題
1.下載 SimSun.ttf
https://github.com/StellarCN/scp_zh/blob/master/fonts/SimSun.ttf
2.放到正確路徑下
C:\Users\111.conda\envs\snapcam\Lib\site-packages\reportlab\fonts
3.寫測試範例程式碼:
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, TableStyle, Table
pdfmetrics.registerFont(TTFont('SimSun', "SimSun.ttf"))
fileName = "example2.pdf"
pdfTemplate = SimpleDocTemplate(fileName)
story = []
tableStyle = TableStyle([
('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 置中對齊
('FONTNAME', (0, 0), (-1, -1), 'SimSun'), # 字體
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # 上下置中
('GRID', (0, 0), (-1, -1), 0.5, colors.black), # 框線黑色,寬度0.5
])
dataList = [
["測試", "2", "3", "4"],
["5", "測試一qweqw一", "7", "8"],
["9", "10", "11", "12"],
["13", "14", "15", "16"],
]
table = Table(dataList, style=tableStyle)
story.append(table)
pdfTemplate.build(story)
四、產生報表範例
from reportlab.pdfbase import pdfmetrics # 注册字体
from reportlab.pdfbase.ttfonts