pip install reportlab
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('msyh', 'msyh.ttf'))
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, LongTable, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_JUSTIFY
pdfmetrics.registerFont(TTFont('SimSun', './SimSun.ttf')) # 默认不支持中文,需要注册字体
pdfmetrics.registerFont(TTFont('SimSunBd', './宋体-粗体.ttf'))
stylesheet = getSampleStyleSheet() # 获取样式集
# 获取reportlab自带样式
Normal = stylesheet['Normal']
BodyText = stylesheet['BodyText']
Italic = stylesheet['Italic']
Title = stylesheet['Title']
Heading1 = stylesheet['Heading1']
Heading2 = stylesheet['Heading2']
Heading3 = stylesheet['Heading3']
Heading4 = stylesheet['Heading4']
Heading5 = stylesheet['Heading5']
Heading6 = stylesheet['Heading6']
Bullet = stylesheet['Bullet']
Definition = stylesheet['Definition']
Code = stylesheet['Code']
# 自带样式不支持中文,需要设置中文字体,但有些样式会丢失,如斜体Italic。有待后续发现完全兼容的中文字体
Normal.fontName = 'SimSun'
Italic.fontName = 'SimSun'
BodyText.fontName = 'SimSun'
Title.fontName = 'SimSunBd'
Heading1.fontName = 'SimSun'
Heading2.fontName = 'SimSun'
Heading3.fontName = 'SimSun'
Heading4.fontName = 'SimSun'
Heading5.fontName = 'SimSun'
Heading6.fontName = 'SimSun'
Bullet.fontName = 'SimSun'
Definition.fontName = 'SimSun'
Code.fontName = 'SimSun'
# 添加自定义样式
stylesheet.add(
ParagraphStyle(name='body',
fontName="SimSun",
fontSize=10,
textColor='black',
leading=20, # 行间距
spaceBefore=0, # 段前间距
spaceAfter=10, # 段后间距
leftIndent=0, # 左缩进
rightIndent=0, # 右缩进
firstLineIndent=20, # 首行缩进,每个汉字为10
alignment=TA_JUSTIFY, # 对齐方式
)
)
body = stylesheet['body']
story = []
table_data = [['参数', '值'], # First row or headers
['名称', '11'], # Second row
['00', '21'], # Third row
['30', '31'],
]
table_style = [
('FONTNAME', (0, 0), (-1, -1), 'SimSun'), # 字体
('FONTSIZE', (0, 0), (-1, 0), 12), # 第一行的字体大小
('FONTSIZE', (0, 1), (-1, -1), 10), # 第二行到最后一行的字体大小
('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 所有表格左右中间对齐
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # 所有表格上下居中对齐
('TEXTCOLOR', (0, -1), (0, -1), colors.green), # 设置表格内文字颜色
('GRID', (0, 0), (-1, -1), 0.1, colors.black), # 设置表格框线为灰色,线宽为0.1
]
table = Table(data=table_data, style=table_style, colWidths=180)
story.append(Paragraph("区块链", Title))
story.append(table)
doc = SimpleDocTemplate('hello.pdf')
doc.build(story)
这里需要安装字体库,不然就会报错
SimSun.ttf
宋体-粗体.ttf
这两个自行百度下载,下载后放在文件夹里面,
你的虚拟环境\Lib\site-packages\reportlab