持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天,点击查看活动详情
本文主要介绍利用python的reportlab包打印简单的报告图,如下图示:
注意:一般来说,利用reportlab包得到的字体TTF字体下载-字体分类-字体大全-字客网 (fontke.com)默认时英文字体,但是如果想要中文字体的话
还是需要去下载相应的字体,下载地址:TTF字体下载-字体分类-字体大全-字客网 (fontke.com)
先上代码:
from reportlab.platypus import SimpleDocTemplate, Image, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
pdfmetrics.registerFont(TTFont('SimKai', 'D:\Anaconda3\envs\torch1.5\Lib\site-packages\reportlab\fonts\SimKai.ttf'))
doc = SimpleDocTemplate("Hello1.pdf")
styles = getSampleStyleSheet()
style0 = styles["Title"]
style0.fontName = "SimKai"
style = styles['Normal']
style.fontName = "SimKai"
style1 = styles["Heading3"]
style1.fontName = "SimKai"
style1.alignment = 1
story =[]
story.append(Paragraph("XX大学校医院眼图诊断报告", style0))
story.append(Paragraph("姓名:XXX", style))
story.append(Paragraph("年龄:23", style))
story.append(Paragraph("性别:男", style))
story.append(Paragraph("XX诊断图示:", style))
t = Image("E:\1.png", width=300, height=200) ##图片路径地址
story.append(t)
story.append(Paragraph("结果:一切正常", style))
story.append(Paragraph("日期:2022年6月15日", style))
story.append(Paragraph("XX大学校医院", style1))
doc.build(story)
关于ParagraphStyle的参数说明如下:
我们选取几个重要的参数进行说明:
- fontName:字体名称
- fontSize:字体大小
- leading:行间距
- leftIndent:左缩进
- rightIndent:右缩进
- firstLineIndent:首行缩进
- alignment:对齐方式
- spaceBefore:段前间隙
- spaceAfter:段后间隙
- bulletFontName:列表名称
- bulletFontSize:列表字体大小
- bulletIndent:列表缩进
- textColor:字体颜色
- backColor:背景色
- borderWidth:边框粗细
- borderPadding:边框间距
- borderColor:边框颜色
关于字体的形式参数说明:
这里就是获得系统提供的Normal格式,其实Normal格式与ParagraphStyle是一模一样的,除了Normal格式,还可以获得其他的格式。
- Normal
- BodyText
- Italic
- Heading1
- Title
- Heading2
- Heading3
- Heading4
- Heading5
- Heading6
- Bullet
- Definition
- Code
- UnorderedList
- OrderedList
Reference:
用Python快速自动生成图文并茂的PDF文件 - 知乎 (zhihu.com)https://zhuanlan.zhihu.com/p/318390273
\