python+reportlab创建PDF文件

目录

字体导入

画布写入

创建画布对象

写入文本内容

写入图片内容

新增页

画线

表格

保存

模板写入

创建模板对象

段落及样式

表格及样式

画框

图片

页眉页脚

添加图形

构建pdf文件


reportlab库支持创建包含文本、图像、图形和表格的复杂PDF文档。

安装:pip install reportlab -i https://pypi.tuna.tsinghua.edu.cn/simple

字体导入

在写入中文内容时会出现中文乱码的情况,如下图,所以需要导入对应的字体库,一般Windows系统自带的字体库文件在C:\Windows\Fonts下

python 复制代码
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont(TTFont('SimSun', 'simsun.ttc'))  # 宋体
pdfmetrics.registerFont(TTFont('华文彩云', 'C:\Windows\Fonts\STCAIYUN.TTF'))

画布写入

reportlab支持画布写入内容和模版框架写入

创建画布对象

python 复制代码
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.lib import pagesizes, colors
from reportlab.graphics.shapes import Drawing, Rect
from reportlab.platypus import Image, Table, TableStyle
from reportlab.platypus import Paragraph, SimpleDocTemplate
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle

cav = canvas.Canvas(pdf_name)  # pagesize(元组类型)参数可设置页面大小,也可以设置reportlab.lib中的预设值(pagesize=pagesizes.letter)
cav.setAuthor('设置作者测试')
cav.setTitle('设置标题')
cav.setSubject('设置主题')

# 导入字体,字体是在Windows系统字体库中存在的数据
pdfmetrics.registerFont(TTFont('SimSun', 'simsun.ttc'))  # 宋体
cav.setFont('SimSun', 10)  # 设置字体和字体大小

写入文本内容

难过的一点,画布写入内容过长(长文本)不会自动换行!!!!

python 复制代码
# 写入文字内容
cav.drawString(100, 600, '测试文本数据' * 150)  # 添加文本内容,可设置左边距和下边距
cav.drawCentredString(20, 50, 'test测试' * 100)

写入图片内容

python 复制代码
# 写入图片方法1
cav.drawImage(r'E:\桌面\99\测试图片\1.jpg', x=100, y=100, width=50, height=50)  # 插入图片  x,y 为左边距和下边距
# 写入图片方法2
image = Image(r'E:\桌面\99\测试图片\2.jpg', width=300, height=400)
image.drawOn(cav, x=100, y=100)  # 计算图像的尺寸并将其插入到PDF中,x,y 为左边距和下边距

新增页

python 复制代码
cav.showPage()  # 新增页面

画线

python 复制代码
cav.line(5, 300, 300, 300)
cav.line(5, 5, 300, 5)
cav.line(5, 300, 5, 5)
cav.line(300, 300, 300, 5)
cav.setStrokeColorRGB(100 / 255, 200 / 255, 50 / 255)
cav.line(90, 300, 90, 5)
cav.setStrokeColorRGB(50 / 255, 50 / 255, 50 / 255)

表格

python 复制代码
image3 = Image(r'E:\桌面\99\测试图片\3.jpg', width=40, height=40)
data = [['姓名', '性别', '年龄', '图片'], ['张', '男', 32], ['刘', '女', 23], ['马', '男', 24, image3]]
table_style = [
    ('BACKGROUND', (0, 0), (-1, 0), colors.aqua),  # 设置标题背景色
    ('TEXTCOLOR', (0, 0), (-1, 0), (50 / 255, 200 / 255, 100 / 255)),  # 设置文本颜色
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  # 设置对齐方式
    ('FONTNAME', (0, 0), (-1, -1), 'SimSun'),  # 设置字体
    ('BOTTOMPADDING', (0, 0), (-1, 0), 20),
    ('BACKGROUND', (0, 1), (-1, -1), colors.azure),
    ('GRID', (0, 0), (-1, -1), 2, colors.blue)  # 设置网格及网格样式  ,2为表格宽度
]

table = Table(data, 100, 50)  # 可指定表格大小
table.setStyle(table_style)
table.wrapOn(cav, 0, 0)
table.drawOn(cav, 50, 500)

保存

python 复制代码
cav.save()

模板写入

创建模板对象

python 复制代码
doc = SimpleDocTemplate(pdf_name)

段落及样式

ParagraphStyle: 段落支持大多数样式的设置,可见源码

python 复制代码
# 设置段落样式
p_style = getSampleStyleSheet()['Normal']
par_style1 = ParagraphStyle(name='p_style1', parent=p_style, fontName='SimSun', spaceAfter=10, spaceBefore=10)
par_style2 = ParagraphStyle(name='p_style2', parent=p_style, fontName='华文彩云',fontSize=15, spaceAfter=30, spaceBefore=30)
# 添加段落
par1 = Paragraph('duanluo段落11' * 20, par_style1)
par2 = Paragraph('duanluo段落2' * 20, par_style2)

表格及样式

python 复制代码
image = Image(r'E:\桌面\99\测试图片\3.jpg', width=40, height=60)
data = [['姓名', '性别', '年龄', '图片'], ['张', '男', 32], ['刘', '女', 23], ['马', '男', 24, image]]
table_style = [
    ('BACKGROUND', (0, 0), (-1, 0), colors.aqua),  # 设置标题背景色
    ('TEXTCOLOR', (0, 0), (-1, 0), (50 / 255, 200 / 255, 100 / 255)),  # 设置文本颜色
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  # 设置对齐方式(左右对齐方式)
    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),  # 设置对齐方式(垂直对齐方式),垂直居中
    ('FONTNAME', (0, 0), (-1, -1), 'SimSun'),  # 设置字体
    ('FONTSIZE', (0, 0), (-1, -1), 20),  # 设置字号
    ('BOTTOMPADDING', (0, 0), (-1, 0), 20),
    ('BACKGROUND', (0, 1), (-1, -1), colors.azure),
    ('GRID', (0, 0), (-1, -1), 2, colors.blue),  # 设置网格及网格线宽度和颜色  ,2为表格宽度
    ('LINEBEFORE', (0, 0), (0, -1), 3, colors.dodgerblue),  # 设置左边线宽度和颜色
    ('LINEBEFORE', (1, 0), (1, -1), 6, colors.darkolivegreen),  # 指定边框线颜色
    ('SPAN', (0, 0), (0, -1))  # 合并单元格
]
table = Table(data, 100, 50)  # 可指定表格大小
table.setStyle(table_style)

画框

python 复制代码
d = Drawing()
d.background = Rect(0, 0, 300, 100, strokeWidth=1, strokeColor='#238E23', fillColor='#E47833')

图片

python 复制代码
image = Image(r'E:\桌面\99\测试图片\2.jpg', width=300, height=400)

页眉页脚

页眉页脚可通过自定义构建画布函数在构建文件时执行添加

python 复制代码
def page_layout(canvas, doc):
    canvas.setFont('华文彩云', 14)
    canvas.drawString(100, 770, "页眉")

    canvas.setFont('SimSun', 10)
    page_num = canvas.getPageNumber()
    canvas.drawString(500, 15, f"第{page_num}页")

添加图形

可支持添加各类统计图,如柱状图和饼形图,具体使用时自行参考文档

python 复制代码
from reportlab.graphics.charts import piecharts, barcharts  # 添加图形

构建pdf文件

onFirstPage # 在第一页生效的内容

onLaterPages # 在第一页之后生效的内容

python 复制代码
content = [par1, par2, table, image, d]
doc.build(content, onFirstPage=page_layout, onLaterPages=page_layout)
相关推荐
饮水桶_T13 分钟前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
悠仁さん1 小时前
【C++】unordered_map_set 模拟实现
开发语言·c++
萧子琦2 小时前
不装 C++ Snappy 也能秒解 LevelDB .ldb?拿 3 套公开取证靶场对拍 StarShield v0.4.1、dfindexeddb 与 strings
python
Risehuxyc2 小时前
为什么php结束符?>省略不写
开发语言·php
JonaHu3 小时前
GPT Image 2.6 商品图横竖版适配:安全区、留白与裁切预检
图像处理·人工智能·python·aigc
Fancy.7613 小时前
Python变量与基础数据类型学习总结
python
泡海椒3 小时前
Java 生成资金流向图 PDF:jquick-pdf 树图(JTreeChartData)节点尺寸与间距的追问记录
java·python·pdf
旖旎夜光4 小时前
【C 语言】(二)模拟实现 strlen、strcpy、strcmp、strstr、memcpy、memmove
c语言·开发语言·笔记·学习
开开心心就好4 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
钱栈up4 小时前
奥迪上汽拍板「三年三款」,合资阵营的换挡节奏终于跟上了
爬虫·python·数据分析