脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python使用reportlab生成pdf实例

python使用reportlab生成pdf实例

2022-09-16 11:13yujie.zhao Python

大家好,本篇文章主要讲的是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 里像查字典一样去找。

预览

python使用reportlab生成pdf实例

完整代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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:生成文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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"},
    )

总结

到此这篇关于python使用reportlab生成pdf实例的文章就介绍到这了,更多相关python reportlab生成pdf内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/wolanx/article/details/122828185

延伸 · 阅读

精彩推荐
  • Pythonpython爬虫之百度API调用方法

    python爬虫之百度API调用方法

    下面小编就为大家带来一篇python爬虫之百度API调用方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    脚本之家4392020-11-17
  • Pythonpython使用sorted函数对列表进行排序的方法

    python使用sorted函数对列表进行排序的方法

    这篇文章主要介绍了python使用sorted函数对列表进行排序的方法,涉及Python使用sorted函数的技巧,非常具有实用价值,需要的朋友可以参考下 ...

    令狐不聪6772020-05-29
  • PythonPygame游戏开发之太空射击实战精灵的使用上篇

    Pygame游戏开发之太空射击实战精灵的使用上篇

    相信大多数8090后都玩过太空射击游戏,在过去游戏不多的年代太空射击自然属于经典好玩的一款了,今天我们来自己动手实现它,在编写学习中回顾过往展...

    acktomas7992022-08-04
  • Pythonpython性能测试对手机号绑定进行压测

    python性能测试对手机号绑定进行压测

    这篇文章主要为大家介绍了python性能测试对手机号绑定进行压测示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职...

    FunTester3892022-07-21
  • Pythonpython生成1行四列全2矩阵的方法

    python生成1行四列全2矩阵的方法

    今天小编就为大家分享一篇python生成1行四列全2矩阵的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    yan456jie6072021-03-26
  • Pythonpython 切换root 执行命令的方法

    python 切换root 执行命令的方法

    今天小编就为大家分享一篇python 切换root 执行命令的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    格林-scorpio12832021-05-18
  • Python初学Python函数的笔记整理

    初学Python函数的笔记整理

    这篇文章主要介绍了初学Python函数的整理笔记,包括一些基础的参数使用方法以及匿名函数等特性的使用,需要的朋友可以参考下...

    脚本之家3702020-05-30
  • PythonPython的Django框架中settings文件的部署建议

    Python的Django框架中settings文件的部署建议

    这篇文章主要介绍了Python的Django框架中settings文件的部署建议,包括对local_settings的弊病的一些简单分析,需要的朋友可以参考下 ...

    脚本之家4242020-07-10