python 使用 reportlab 生成 pdf

本文演示如何使用Python的ReportLab库创建PDF文件,包括曲线图、饼图、文字样式设置等。通过定义CSS样式,实现类似CSS的布局,并提供了生成PDF文件和在Web应用中返回PDF的示例。还介绍了表格和多线图的高级用法。
Python3.8

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

Intro

项目中遇到需要 导出统计报表 等业务时,通常需要 pdf 格式。python 中比较有名的就是 reportlab
这边通过几个小 demo 快速演示常用 api。所有功能点 源码 都在 使用场景

一句话了解:跟 css 差不多,就是不断地对每样东西设置 style,然后把 style 和内容绑定。

功能点

  • 生成
    • 文件: 先 SimpleDocTemplate(‘xxx.pdf’),然后 build
    • 流文件:先 io.BytesIO() 生成句柄,然后同理
  • 曲线图 LinePlot
  • 饼图 Pie
  • 文字 Paragraph
    • fontSize 字体大小 推荐 14
    • 加粗 <b>xxx</b> 使用的是 html 的方式,字体自动实现
    • firstLineIndent 首行缩进 推荐 2 * fontSize
    • leading 行间距 推荐 1.5 * fontSize
    • fontName 默认中文会变成 ■
      • 下载 .ttf 文件 至少2个 【常规】【加粗】
      • 注册字体 pdfmetrics.registerFont 【常规】请用原名,方便加粗的实现
      • 注册字体库 registerFontFamily(“HanSans”, normal=“HanSans”, bold=“HanSans-Bold”)

其他 api 自行摸索,但基本离不开 css 那种理念。官网并没有常规文档的那种 md 模式,而是完全写在了 pdf 里,玩家需要自己去 pdf 里像查字典一样去找。官方文档 ; 官方demo

预览

在这里插入图片描述

完整代码

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>"),
    p.doH3("<b>2021.12.1 ~ 2021.12.31</b>"),
    p.doP("该月接入能耗管理系统水泵系统 xx 套,水泵 x 台。"),
    p.doP("本月最大总功率 xx kW,环比上月增加 xx %,平均功率 xx kW;环比上月增加 xx %。"),
    p.doP("功率消耗趋势图:"),
    p.doLine(),
    p.doP("本月总能耗 xxx kWh,环比上月增加 xx %。"),
    p.doP("分水泵能耗统计:"),
    p.doChart(list(range(15, 105, 20))),
    p.doP("其中能耗最高的水泵为:xxx, 环比上月增加 xxx kWh,xx %。"),
])

使用场景2:web(flask)

@Controller.get("/api/pdf")
def api_hub_energy_pdf():
    buffer = io.BytesIO()										# 重点 起一个 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"},
    )

进阶

表格

	@classmethod
    def doTable(cls, data: List[List]):
        """
        data = [
            ["相对xxx", "设计值%", "最近3个月%", "最近1年%", "自定义1%", "自定义2%"],
            [00, 11, 22, 33, 44, 55],
            [000, 111, 222, 333, 444, 555],
            [0000, 1111, 2222, 3333, 4444, 5555],
        ]
        @return:
        """
        colWidths = 400 / len(data[0])
        dis_list = []
        for x in data:
            # dis_list.append(map(lambda i: Paragraph('%s' % i, cn), x))
            dis_list.append(x)
        style = [
            ("FONTNAME", (0, 0), (-1, -1), FONT_NAME),
            # ("FONTSIZE", (0, 0), (-1, 0), 15),
            ("BACKGROUND", (0, 0), (-1, 0), HexColor("#d5dae6")),
            ("ALIGN", (0, 0), (-1, -1), "CENTER"),
            ("VALIGN", (-1, 0), (-2, 0), "MIDDLE"),
            # ("TEXTCOLOR", (0, 0), (-1, 0), colors.royalblue),
            ("GRID", (0, 0), (-1, -1), 0.5, colors.grey),
        ]
        component_table = Table(dis_list, colWidths=colWidths, style=style)
        return component_table

多线

    @classmethod
    def doLineRaw(cls, labels: List[str], *data: List[Tuple[int, int]]):
        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.lines[3].strokeColor = colors.grey
        line.lines[4].strokeColor = colors.pink

        line.data = data
        for idx, label in enumerate(labels):
            line.lines[idx].name = label

        legend = Legend()
        legend.fontName = FONT_NAME
        legend.fontSize, legend.alignment = 6, 'right'
        legend.colorNamePairs = Auto(obj=line)
        legend.dxTextSpace = 7
        legend.columnMaximum = 1
        legend.deltax = 1
        legend.deltay = 0
        legend.dy = 5
        legend.y = 200
        legend.x = 50

        drawing.add(line)
        drawing.add(legend)
        return drawing

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wolanx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值