python 使用 reportlab 生成 pdf

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
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: reportlab是一个PythonPDF生成库,可以用来生成PDF文件,下面是一个简单的示例代码: ```python from reportlab.pdfgen import canvas # 创建一个PDF文档对象 pdf = canvas.Canvas("example.pdf") # 设置字体 pdf.setFont("Helvetica", 12) # 写入文本 pdf.drawString(100, 750, "Welcome to Reportlab!") # 画一个矩形 pdf.rect(50, 50, 200, 100) # 保存PDF文件 pdf.save() ``` 这个示例代码创建了一个PDF文档对象,设置了字体,写入了文本并画了一个矩形,最后保存PDF文件。 你可以根据自己的需求,修改文本内容、字体、位置、颜色等等。更多的使用方法可以查看reportlab的官方文档。 ### 回答2: Python中的reportlab库可以用于生成PDF文件。reportlab是一个强大的工具,可以帮助开发者在Python中创建和定制各种类型的PDF文档。 首先,需要安装reportlab库。可以通过使用pip命令在命令行中运行以下命令来安装reportlab: ```python pip install reportlab ``` 安装完毕后,可以在Python代码中导入reportlab库: ```python from reportlab.pdfgen import canvas ``` 接下来,可以创建一个canvas对象来构建PDF文件。Canvas是reportlab库中最基本的对象之一,它允许开发者在PDF页面上进行各种操作。通过调用canvas对象的方法,可以绘制文本、图片、图形等。 例如,以下代码演示了如何创建一个PDF文件并在其中添加一些文本: ```python from reportlab.pdfgen import canvas # 创建一个canvas对象,指定PDF文件路径和名称 pdf = canvas.Canvas("example.pdf") # 在(100, 750)位置添加一段文本 pdf.setFont('Helvetica', 12) pdf.drawString(100, 750, "Hello, World!") # 关闭canvas对象,保存PDF文件 pdf.save() ``` 运行以上代码后,将在当前目录下生成一个名为example.pdfPDF文件。在该文件中,将添加一个位置在(100, 750)的文本“Hello, World!”。 总结:使用reportlab库中的canvas对象和相应的方法,可以轻松地在Python生成并定制各种类型的PDF文件。以上是一个简单的示例,你可以根据自己的需求进一步扩展和定制PDF文档。 ### 回答3: 使用python中的第三方库ReportLab可以很方便地生成PDF文件。ReportLab是一个用于创建PDF文档的强大工具,可以在Python使用它来生成报告、统计图表、标签等。 首先,在使用ReportLab之前,需通过pip安装ReportLab库。 ``` pip install reportlab ``` 然后,我们需要创建一个画布对象来绘制我们的PDF文件。 ```python from reportlab.pdfgen import canvas # 创建一个PDF文件 pdf = canvas.Canvas("output.pdf") # 绘制文本 pdf.drawString(100, 750, "Hello World!") # 保存PDF文件 pdf.save() ``` 以上示例代码创建了一个名为output.pdfPDF文件,并在画布上绘制了一个"Hello World!"的文本。使用`drawString`方法,可以设置文本的位置和内容。在绘制完所需内容后,通过`save`方法可以保存生成PDF文件。 除了绘制文本,ReportLab还提供了许多其他功能,如绘制图像、绘制表格、设置页面布局等。可以通过查阅ReportLab的官方文档来学习更多相关的用法,进一步定制生成自己需要的PDF文件。 使用ReportLab生成PDF文件是一种简单而强大的方法,可以应用于许多场景,如生成报告、生成标签、生成图表等。无论是个人使用还是商业应用,ReportLab提供了丰富且灵活的功能来满足不同的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wolanx

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

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

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

打赏作者

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

抵扣说明:

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

余额充值