python使用reportlab生成pdf實(shí)例
Intro
項(xiàng)目中遇到需要 導(dǎo)出統(tǒng)計(jì)報(bào)表 等業(yè)務(wù)時,通常需要 pdf 格式。python 中比較有名的就是 reportlab 。
這邊通過幾個小 demo 快速演示常用 api。所有功能點(diǎn) 源碼 都在 使用場景。
一句話了解:跟 css 差不多,就是不斷地對每樣?xùn)|西設(shè)置 style,然后把 style 和內(nèi)容綁定。
功能點(diǎn)
生成
文件: 先 SimpleDocTemplate(‘xxx.pdf’),然后 build
流文件:先 io.BytesIO() 生成句柄,然后同理
曲線圖 LinePlot
餅圖 Pie
文字 Paragraph
fontSize 字體大小 推薦 14
加粗 <b>xxx</b> 使用的是 html 的方式,字體自動實(shí)現(xiàn)
firstLineIndent 首行縮進(jìn) 推薦 2 * fontSize
leading 行間距 推薦 1.5 * fontSize
fontName 默認(rèn)中文會變成 ■
下載 .ttf 文件 至少2個 【常規(guī)】【加粗】
注冊字體 pdfmetrics.registerFont 【常規(guī)】請用原名,方便加粗的實(shí)現(xiàn)
注冊字體庫 registerFontFamily(“HanSans”, normal=“HanSans”, bold=“HanSans-Bold”)
其他 api 自行摸索,但基本離不開 css 那種理念。官網(wǎng)并沒有常規(guī)文檔的那種 md 模式,而是完全寫在了 pdf 里,玩家需要自己去 pdf 里像查字典一樣去找。
預(yù)覽

完整代碼
import os
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.piecharts import Pie
from reportlab.graphics.shapes import Drawing
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.pdfmetrics import registerFontFamily
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph
home = os.path.expanduser("~")
try:
pdfmetrics.registerFont(TTFont("HanSans", f"{home}/.fonts/SourceHanSansCN-Normal.ttf"))
pdfmetrics.registerFont(TTFont("HanSans-Bold", f"{home}/.fonts/SourceHanSansCN-Bold.ttf"))
registerFontFamily("HanSans", normal="HanSans", bold="HanSans-Bold")
FONT_NAME = "HanSans"
except:
FONT_NAME = "Helvetica"
class MyCSS:
h3 = ParagraphStyle(name="h3", fontName=FONT_NAME, fontSize=14, leading=21, alignment=1)
p = ParagraphStyle(name="p", fontName=FONT_NAME, fontSize=12, leading=18, firstLineIndent=24)
class PiiPdf:
@classmethod
def doH3(cls, text: str):
return Paragraph(text, MyCSS.h3)
@classmethod
def doP(cls, text: str):
return Paragraph(text, MyCSS.p)
@classmethod
def doLine(cls):
drawing = Drawing(500, 220)
line = LinePlot()
line.x = 50
line.y = 50
line.height = 125
line.width = 300
line.lines[0].strokeColor = colors.blue
line.lines[1].strokeColor = colors.red
line.lines[2].strokeColor = colors.green
line.data = [((0, 50), (100, 100), (200, 200), (250, 210), (300, 300), (400, 800))]
drawing.add(line)
return drawing
@classmethod
def doChart(cls, data):
drawing = Drawing(width=500, height=200)
pie = Pie()
pie.x = 150
pie.y = 65
pie.sideLabels = False
pie.labels = [letter for letter in "abcdefg"]
pie.data = data # list(range(15, 105, 15))
pie.slices.strokeWidth = 0.5
drawing.add(pie)
return drawing
使用場景1:生成文件
doc = SimpleDocTemplate("Hello.pdf")
p = PiiPdf()
doc.build([
p.doH3("<b>水泵能源消耗簡報(bào)</b>"),
p.doH3("<b>2021.12.1 ~ 2021.12.31</b>"),
p.doP("該月接入能耗管理系統(tǒng)水泵系統(tǒng) xx 套,水泵 x 臺。"),
p.doP("本月最大總功率 xx kW,環(huán)比上月增加 xx %,平均功率 xx kW;環(huán)比上月增加 xx %。"),
p.doP("功率消耗趨勢圖:"),
p.doLine(),
p.doP("本月總能耗 xxx kWh,環(huán)比上月增加 xx %。"),
p.doP("分水泵能耗統(tǒng)計(jì):"),
p.doChart(list(range(15, 105, 20))),
p.doP("其中能耗最高的水泵為:xxx, 環(huán)比上月增加 xxx kWh,xx %。"),
])
使用場景2:web(flask)
@Controller.get("/api/pdf")
def api_hub_energy_pdf():
buffer = io.BytesIO() # 重點(diǎn) 起一個 io
doc = SimpleDocTemplate(buffer)
p = PiiPdf()
doc.build([
p.doH3("<b>2021.12.1 ~ 2021.12.31</b>"),
])
buffer.seek(0)
return Response( # io 形式返回
buffer,
mimetype="application/pdf",
headers={"Content-disposition": "inline; filename=test.pdf"},
)
總結(jié)
到此這篇關(guān)于python使用reportlab生成pdf實(shí)例的文章就介紹到這了,更多相關(guān)python reportlab生成pdf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python正則表達(dá)式實(shí)現(xiàn)截取成對括號的方法
這篇文章主要介紹了Python正則表達(dá)式實(shí)現(xiàn)截取成對括號的方法,涉及Python正則匹配相關(guān)操作技巧,需要的朋友可以參考下2017-01-01
利用Python操作MongoDB數(shù)據(jù)庫的詳細(xì)指南
MongoDB是由C++語言編寫的非關(guān)系型數(shù)據(jù)庫,是一個基于分布式文件存儲的開源數(shù)據(jù)庫系統(tǒng),其內(nèi)容存儲形式類似JSON對象,下面這篇文章主要給大家介紹了關(guān)于利用Python操作MongoDB數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2022-06-06
Python利用PyVista進(jìn)行mesh的色彩映射的實(shí)現(xiàn)
這篇文章主要介紹了Python利用PyVista進(jìn)行mesh的色彩映射的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

