关于python:Python生成图文并茂的PDF报告

12次阅读

共计 4315 个字符,预计需要花费 11 分钟才能阅读完成。

reportlab 是 Python 的一个规范库,能够画图、画表格、编辑文字,最初能够输入 PDF 格局。它的逻辑和编辑一个 word 文档或者 PPT 很像。有两种办法:

1)建设一个空白文档,而后在下面写文字、画图等;
2)建设一个空白 list,以填充表格的模式插入各种文本框、图片等,最初生成 PDF 文档。因为须要产生一份给用户看的报告,外面须要插入图片、表格等,所以采纳的是第二种办法。

装置第三方库
reportlab 输出 Python 的第三方库,应用前须要先装置:pip install reportlab

模块导入提前导入相干内容,并且注册字体。(注册字体前须要先筹备好字体文件)

from reportlab.pdfbase import pdfmetrics   # 注册字体
from reportlab.pdfbase.ttfonts import TTFont # 字体类
from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image  # 报告内容相干类
from reportlab.lib.pagesizes import letter  # 页面的标记尺寸 (8.5*inch, 11*inch)
from reportlab.lib.styles import getSampleStyleSheet  # 文本款式
from reportlab.lib import colors  # 色彩模块
from reportlab.graphics.charts.barcharts import VerticalBarChart  # 图表类
from reportlab.graphics.charts.legends import Legend  # 图例类
from reportlab.graphics.shapes import Drawing  # 绘图工具
from reportlab.lib.units import cm  # 单位:cm

# 注册字体 (提前准备好字体文件, 如果同一个文件须要多种字体能够注册多个)
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))

封装不同内容对应的函数

创立一个 Graphs 类,通过不同的静态方法提供不同的报告内容,包含:题目、一般段落、图片、表格和图表。函数中的相干数据目前绝大多数都是固定值,能够依据状况自行设置成相干参数。

class Graphs:
    # 绘制题目
    @staticmethod
    def draw_title(title: str):
        # 获取所有样式表
        style = getSampleStyleSheet()
        # 拿到题目款式
        ct = style['Heading1']
        # 独自设置款式相干属性
        ct.fontName = 'SimSun'      # 字体名
        ct.fontSize = 18            # 字体大小
        ct.leading = 50             # 行间距
        ct.textColor = colors.green     # 字体色彩
        ct.alignment = 1    # 居中
        ct.bold = True
        # 创立题目对应的段落,并且返回
        return Paragraph(title, ct)
      
  # 绘制小标题
    @staticmethod
    def draw_little_title(title: str):
        # 获取所有样式表
        style = getSampleStyleSheet()
        # 拿到题目款式
        ct = style['Normal']
        # 独自设置款式相干属性
        ct.fontName = 'SimSun'  # 字体名
        ct.fontSize = 15  # 字体大小
        ct.leading = 30  # 行间距
        ct.textColor = colors.red  # 字体色彩
        # 创立题目对应的段落,并且返回
        return Paragraph(title, ct)

    # 绘制一般段落内容
    @staticmethod
    def draw_text(text: str):
        # 获取所有样式表
        style = getSampleStyleSheet()
        # 获取一般款式
        ct = style['Normal']
        ct.fontName = 'SimSun'
        ct.fontSize = 12
        ct.wordWrap = 'CJK'     # 设置主动换行
        ct.alignment = 0        # 左对齐
        ct.firstLineIndent = 32     # 第一行结尾空格
        ct.leading = 25
        return Paragraph(text, ct)

    # 绘制表格
    @staticmethod
    def draw_table(*args):
        # 列宽度
        col_width = 120
        style = [('FONTNAME', (0, 0), (-1, -1), 'SimSun'),  # 字体
            ('FONTSIZE', (0, 0), (-1, 0), 12),  # 第一行的字体大小
            ('FONTSIZE', (0, 1), (-1, -1), 10),  # 第二行到最初一行的字体大小
            ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'),  # 设置第一行背景色彩
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  # 第一行程度居中
            ('ALIGN', (0, 1), (-1, -1), 'LEFT'),  # 第二行到最初一行左右左对齐
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),  # 所有表格高低居中对齐
            ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray),  # 设置表格内文字色彩
            ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),  # 设置表格框线为 grey 色,线宽为 0.5
            # ('SPAN', (0, 1), (0, 2)),  # 合并第一列二三行
            # ('SPAN', (0, 3), (0, 4)),  # 合并第一列三四行
            # ('SPAN', (0, 5), (0, 6)),  # 合并第一列五六行
            # ('SPAN', (0, 7), (0, 8)),  # 合并第一列五六行
        ]
        table = Table(args, colWidths=col_width, style=style)
        return table

    # 创立图表
    @staticmethod
    def draw_bar(bar_data: list, ax: list, items: list):
        drawing = Drawing(500, 250)
        bc = VerticalBarChart()
        bc.x = 45       # 整个图表的 x 坐标
        bc.y = 45      # 整个图表的 y 坐标
        bc.height = 200     # 图表的高度
        bc.width = 350      # 图表的宽度
        bc.data = bar_data
        bc.strokeColor = colors.black       # 顶部和左边轴线的色彩
        bc.valueAxis.valueMin = 5000           # 设置 y 坐标的最小值
        bc.valueAxis.valueMax = 26000         # 设置 y 坐标的最大值
        bc.valueAxis.valueStep = 2000         # 设置 y 坐标的步长
        bc.categoryAxis.labels.dx = 2
        bc.categoryAxis.labels.dy = -8
        bc.categoryAxis.labels.angle = 20
        bc.categoryAxis.categoryNames = ax

        # 图示
        leg = Legend()
        leg.fontName = 'SimSun'
        leg.alignment = 'right'
        leg.boxAnchor = 'ne'
        leg.x = 475         # 图例的 x 坐标
        leg.y = 240
        leg.dxTextSpace = 10
        leg.columnMaximum = 3
        leg.colorNamePairs = items
        drawing.add(leg)
        drawing.add(bc)
        return drawing

    # 绘制图片
    @staticmethod
    def draw_img(path):
        img = Image(path)       # 读取指定门路下的图片
        img.drawWidth = 5*cm        # 设置图片的宽度
        img.drawHeight = 8*cm       # 设置图片的高度
        return img

生成报告

if __name__ == '__main__':
    # 创立内容对应的空列表
    content = list()

    # 增加题目
    content.append(Graphs.draw_title('数据分析待业薪资'))

    # 增加图片
    content.append(Graphs.draw_img('抗疫必胜.png'))

    # 增加段落文字
    content.append(Graphs.draw_text('家喻户晓,大数据分析师岗位是香饽饽,近几年数据分析热席卷了整个互联网行业,与数据分析的相干的岗位招聘、培训不可胜数。很多人前仆后继,想要参加到这波红利当中。那么数据分析师待业前景到底怎么样呢?'))
    # 增加小标题
    content.append(Graphs.draw_title(''))
    content.append(Graphs.draw_little_title('不同级别的均匀薪资'))
    # 增加表格
    data = [('职位名称', '均匀薪资', '较上年增长率'),
        ('数据分析师', '18.5K', '25%'),
        ('高级数据分析师', '25.5K', '14%'),
        ('资深数据分析师', '29.3K', '10%')
    ]
    content.append(Graphs.draw_table(*data))

    # 生成图表
    content.append(Graphs.draw_title(''))
    content.append(Graphs.draw_little_title('热门城市的待业状况'))
    b_data = [(25400, 12900, 20100, 20300, 20300, 17400), (15800, 9700, 12982, 9283, 13900, 7623)]
    ax_data = ['BeiJing', 'ChengDu', 'ShenZhen', 'ShangHai', 'HangZhou', 'NanJing']
    leg_items = [(colors.red, '均匀薪资'), (colors.green, '招聘量')]
    content.append(Graphs.draw_bar(b_data, ax_data, leg_items))

    # 生成 pdf 文件
    doc = SimpleDocTemplate('report.pdf', pagesize=letter)
    doc.build(content)

生成报告后果如下:

以上就是本次分享的所有内容,如果你感觉文章还不错,欢送关注公众号:Python 编程学习圈 ,每日干货分享,内容笼罩 Python 电子书、教程、数据库编程、Django,爬虫,云计算等等。或是返回编程学习网,理解更多编程技术常识。

正文完
 0