python使用reportlab生成pdf實(shí)例
Intro
項(xiàng)目中遇到需要 導(dǎo)出統(tǒng)計(jì)報(bào)表
等業(yè)務(wù)時(shí),通常需要 pdf
格式。python
中比較有名的就是 reportlab
。
這邊通過(guò)幾個(gè)小 demo 快速演示常用 api。所有功能點(diǎn) 源碼
都在 使用場(chǎng)景
。
一句話了解:跟 css 差不多,就是不斷地對(duì)每樣?xùn)|西設(shè)置 style,然后把 style 和內(nèi)容綁定。
功能點(diǎn)
生成
文件: 先 SimpleDocTemplate(‘xxx.pdf’),然后 build
流文件:先 io.BytesIO() 生成句柄,然后同理
曲線圖 LinePlot
餅圖 Pie
文字 Paragraph
fontSize 字體大小 推薦 14
加粗 <b>xxx</b> 使用的是 html 的方式,字體自動(dòng)實(shí)現(xiàn)
firstLineIndent 首行縮進(jìn) 推薦 2 * fontSize
leading 行間距 推薦 1.5 * fontSize
fontName 默認(rèn)中文會(huì)變成 ■
下載 .ttf 文件 至少2個(gè) 【常規(guī)】【加粗】
注冊(cè)字體 pdfmetrics.registerFont 【常規(guī)】請(qǐng)用原名,方便加粗的實(shí)現(xiàn)
注冊(cè)字體庫(kù) registerFontFamily(“HanSans”, normal=“HanSans”, bold=“HanSans-Bold”)
其他 api 自行摸索,但基本離不開 css 那種理念。官網(wǎng)并沒(méi)有常規(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
使用場(chǎng)景1:生成文件
doc = SimpleDocTemplate("Hello.pdf") p = PiiPdf() doc.build([ p.doH3("<b>水泵能源消耗簡(jiǎn)報(bào)</b>"), p.doH3("<b>2021.12.1 ~ 2021.12.31</b>"), p.doP("該月接入能耗管理系統(tǒng)水泵系統(tǒng) xx 套,水泵 x 臺(tái)。"), p.doP("本月最大總功率 xx kW,環(huán)比上月增加 xx %,平均功率 xx kW;環(huán)比上月增加 xx %。"), p.doP("功率消耗趨勢(shì)圖:"), 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 %。"), ])
使用場(chǎng)景2:web(flask)
@Controller.get("/api/pdf") def api_hub_energy_pdf(): buffer = io.BytesIO() # 重點(diǎn) 起一個(gè) 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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Python實(shí)現(xiàn)網(wǎng)頁(yè)文章轉(zhuǎn)PDF文檔
有時(shí)候看到一篇好的文章,想去保存下來(lái),傳統(tǒng)方式一般是收藏書簽、復(fù)制粘貼到文檔或者直接復(fù)制鏈接保存,但這也太麻煩了。本文將用Python語(yǔ)言實(shí)現(xiàn)將網(wǎng)上的文章轉(zhuǎn)存為PDF文檔,保存電腦上慢慢看2022-05-05淺談Tensorflow由于版本問(wèn)題出現(xiàn)的幾種錯(cuò)誤及解決方法
今天小編就為大家分享一篇淺談Tensorflow由于版本問(wèn)題出現(xiàn)的幾種錯(cuò)誤及解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06Python執(zhí)行遺傳編程gplearn庫(kù)使用實(shí)例探究
這篇文章主要為大家介紹了Python執(zhí)行遺傳編程gplearn庫(kù)使用實(shí)例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01Python繪圖系統(tǒng)之自定義一個(gè)坐標(biāo)設(shè)置控件
這篇文章主要為大家詳細(xì)介紹了Python如何編寫一個(gè)繪圖系統(tǒng),可以實(shí)現(xiàn)自定義一個(gè)坐標(biāo)設(shè)置控件,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-08-08python 動(dòng)態(tài)遷移solr數(shù)據(jù)過(guò)程解析
這篇文章主要介紹了python 動(dòng)態(tài)遷移solr數(shù)據(jù)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09