热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python使用reportlab生成pdf实例_python

大家好,本篇文章主要讲的是python使用reportlab生成pdf实例,感兴趣的同学赶快来看一看吧,对你有

Intro

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

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

功能点

生成
文件: 先 SimpleDocTemplate(‘xxx.pdf’),然后 build
流文件:先 io.BytesIO() 生成句柄,然后同理
曲线图 LinePlot
饼图 Pie
文字 Paragraph
fontSize 字体大小 推荐 14
加粗 xxx 使用的是 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 里像查字典一样去找。

预览

在这里插入图片描述

完整代码


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(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("水泵能源消耗简报"),
p.doH3("2021.12.1 ~ 2021.12.31"),
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("2021.12.1 ~ 2021.12.31"),
])
buffer.seek(0)
return Response( # io 形式返回
buffer,
mimetype="application/pdf",
headers={"Content-disposition": "inline; filename=test.pdf"},
)

总结

Intro

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

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

功能点

生成
文件: 先 SimpleDocTemplate(‘xxx.pdf’),然后 build
流文件:先 io.BytesIO() 生成句柄,然后同理
曲线图 LinePlot
饼图 Pie
文字 Paragraph
fontSize 字体大小 推荐 14
加粗 xxx 使用的是 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 里像查字典一样去找。

预览

在这里插入图片描述

完整代码


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(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("水泵能源消耗简报"),
p.doH3("2021.12.1 ~ 2021.12.31"),
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("2021.12.1 ~ 2021.12.31"),
])
buffer.seek(0)
return Response( # io 形式返回
buffer,
mimetype="application/pdf",
headers={"Content-disposition": "inline; filename=test.pdf"},
)

总结


推荐阅读
  • 开发笔记:小白python机器学习之路——支持向量机
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了小白python机器学习之路——支持向量机相关的知识,希望对你有一定的参考价值。支持 ... [详细]
  • 本文介绍了计算机网络的定义和通信流程,包括客户端编译文件、二进制转换、三层路由设备等。同时,还介绍了计算机网络中常用的关键词,如MAC地址和IP地址。 ... [详细]
  • Python瓦片图下载、合并、绘图、标记的代码示例
    本文提供了Python瓦片图下载、合并、绘图、标记的代码示例,包括下载代码、多线程下载、图像处理等功能。通过参考geoserver,使用PIL、cv2、numpy、gdal、osr等库实现了瓦片图的下载、合并、绘图和标记功能。代码示例详细介绍了各个功能的实现方法,供读者参考使用。 ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • Day2列表、字典、集合操作详解
    本文详细介绍了列表、字典、集合的操作方法,包括定义列表、访问列表元素、字符串操作、字典操作、集合操作、文件操作、字符编码与转码等内容。内容详实,适合初学者参考。 ... [详细]
  • 十大经典排序算法动图演示+Python实现
    本文介绍了十大经典排序算法的原理、演示和Python实现。排序算法分为内部排序和外部排序,常见的内部排序算法有插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序等。文章还解释了时间复杂度和稳定性的概念,并提供了相关的名词解释。 ... [详细]
  • 本文介绍了Python对Excel文件的读取方法,包括模块的安装和使用。通过安装xlrd、xlwt、xlutils、pyExcelerator等模块,可以实现对Excel文件的读取和处理。具体的读取方法包括打开excel文件、抓取所有sheet的名称、定位到指定的表单等。本文提供了两种定位表单的方式,并给出了相应的代码示例。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 本文详细介绍了PHP中与URL处理相关的三个函数:http_build_query、parse_str和查询字符串的解析。通过示例和语法说明,讲解了这些函数的使用方法和作用,帮助读者更好地理解和应用。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 解决python matplotlib画水平直线的问题
    本文介绍了在使用python的matplotlib库画水平直线时可能遇到的问题,并提供了解决方法。通过导入numpy和matplotlib.pyplot模块,设置绘图对象的宽度和高度,以及使用plot函数绘制水平直线,可以解决该问题。 ... [详细]
  • 使用正则表达式爬取36Kr网站首页新闻的操作步骤和代码示例
    本文介绍了使用正则表达式来爬取36Kr网站首页所有新闻的操作步骤和代码示例。通过访问网站、查找关键词、编写代码等步骤,可以获取到网站首页的新闻数据。代码示例使用Python编写,并使用正则表达式来提取所需的数据。详细的操作步骤和代码示例可以参考本文内容。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • 树莓派语音控制的配置方法和步骤
    本文介绍了在树莓派上实现语音控制的配置方法和步骤。首先感谢博主Eoman的帮助,文章参考了他的内容。树莓派的配置需要通过sudo raspi-config进行,然后使用Eoman的控制方法,即安装wiringPi库并编写控制引脚的脚本。具体的安装步骤和脚本编写方法在文章中详细介绍。 ... [详细]
  • POJ 1046 Color Me Less
    ColorMeLessTimeLimit: 1000MS MemoryLimit: 10000KTotalSubmissions: 31449 Accept ... [详细]
author-avatar
-彼岸花开-hui
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有