51Testing软件测试论坛

标题: Python生成图文并茂的PDF报告 [打印本页]

作者: lsekfe    时间: 2022-7-21 09:54
标题: Python生成图文并茂的PDF报告
reportlab是Python的一个标准库,可以画图、画表格、编辑文字,最后可以输出PDF格式。它的逻辑和编辑一个word文档或者PPT很像。有两种方法:
  1)建立一个空白文档,然后在上面写文字、画图等;
  2)建立一个空白list,以填充表格的形式插入各种文本框、图片等,最后生成PDF文档。
  因为需要产生一份给用户看的报告,里面需要插入图片、表格等,所以采用的是第二种方法。
  安装第三方库
  reportlab输入Python的第三方库,使用前需要先安装:pip install reportlab
  模块导入
  提前导入相关内容,并且注册字体。(注册字体前需要先准备好字体文件)
  1. from reportlab.pdfbase import pdfmetrics   # 注册字体
  2.   from reportlab.pdfbase.ttfonts import TTFont # 字体类
  3.   from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image  # 报告内容相关类
  4.   from reportlab.lib.pagesizes import letter  # 页面的标志尺寸(8.5*inch, 11*inch)
  5.   from reportlab.lib.styles import getSampleStyleSheet  # 文本样式
  6.   from reportlab.lib import colors  # 颜色模块
  7.   from reportlab.graphics.charts.barcharts import VerticalBarChart  # 图表类
  8.   from reportlab.graphics.charts.legends import Legend  # 图例类
  9.   from reportlab.graphics.shapes import Drawing  # 绘图工具
  10.   from reportlab.lib.units import cm  # 单位:cm
  11.   # 注册字体(提前准备好字体文件, 如果同一个文件需要多种字体可以注册多个)
  12.   pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))
复制代码
封装不同内容对应的函数
  创建一个Graphs类,通过不同的静态方法提供不同的报告内容,包括:标题、普通段落、图片、表格和图表。函数中的相关数据目前绝大多数都是固定值,可以根据情况自行设置成相关参数。
  1. class Graphs:
  2.      # 绘制标题
  3.      @staticmethod
  4.      def draw_title(title: str):
  5.          # 获取所有样式表
  6.          style = getSampleStyleSheet()
  7.          # 拿到标题样式
  8.          ct = style['Heading1']
  9.          # 单独设置样式相关属性
  10.          ct.fontName = 'SimSun'      # 字体名
  11.          ct.fontSize = 18            # 字体大小
  12.          ct.leading = 50             # 行间距
  13.          ct.textColor = colors.green     # 字体颜色
  14.          ct.alignment = 1    # 居中
  15.          ct.bold = True
  16.          # 创建标题对应的段落,并且返回
  17.          return Paragraph(title, ct)
  18.    # 绘制小标题
  19.      @staticmethod
  20.      def draw_little_title(title: str):
  21.          # 获取所有样式表
  22.          style = getSampleStyleSheet()
  23.          # 拿到标题样式
  24.          ct = style['Normal']
  25.          # 单独设置样式相关属性
  26.          ct.fontName = 'SimSun'  # 字体名
  27.          ct.fontSize = 15  # 字体大小
  28.          ct.leading = 30  # 行间距
  29.          ct.textColor = colors.red  # 字体颜色
  30.          # 创建标题对应的段落,并且返回
  31.          return Paragraph(title, ct)
  32.      # 绘制普通段落内容
  33.      @staticmethod
  34.      def draw_text(text: str):
  35.          # 获取所有样式表
  36.          style = getSampleStyleSheet()
  37.          # 获取普通样式
  38.          ct = style['Normal']
  39.          ct.fontName = 'SimSun'
  40.          ct.fontSize = 12
  41.          ct.wordWrap = 'CJK'     # 设置自动换行
  42.          ct.alignment = 0        # 左对齐
  43.          ct.firstLineIndent = 32     # 第一行开头空格
  44.          ct.leading = 25
  45.          return Paragraph(text, ct)
  46.      # 绘制表格
  47.      @staticmethod
  48.      def draw_table(*args):
  49.          # 列宽度
  50.          col_width = 120
  51.          style = [
  52.              ('FONTNAME', (0, 0), (-1, -1), 'SimSun'),  # 字体
  53.              ('FONTSIZE', (0, 0), (-1, 0), 12),  # 第一行的字体大小
  54.              ('FONTSIZE', (0, 1), (-1, -1), 10),  # 第二行到最后一行的字体大小
  55.              ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'),  # 设置第一行背景颜色
  56.              ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  # 第一行水平居中
  57.              ('ALIGN', (0, 1), (-1, -1), 'LEFT'),  # 第二行到最后一行左右左对齐
  58.              ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),  # 所有表格上下居中对齐
  59.              ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray),  # 设置表格内文字颜色
  60.              ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),  # 设置表格框线为grey色,线宽为0.5
  61.              # ('SPAN', (0, 1), (0, 2)),  # 合并第一列二三行
  62.              # ('SPAN', (0, 3), (0, 4)),  # 合并第一列三四行
  63.              # ('SPAN', (0, 5), (0, 6)),  # 合并第一列五六行
  64.              # ('SPAN', (0, 7), (0, 8)),  # 合并第一列五六行
  65.          ]
  66.          table = Table(args, colWidths=col_width, style=style)
  67.          return table
  68.      # 创建图表
  69.      @staticmethod
  70.      def draw_bar(bar_data: list, ax: list, items: list):
  71.          drawing = Drawing(500, 250)
  72.          bc = VerticalBarChart()
  73.          bc.x = 45       # 整个图表的x坐标
  74.          bc.y = 45      # 整个图表的y坐标
  75.          bc.height = 200     # 图表的高度
  76.          bc.width = 350      # 图表的宽度
  77.          bc.data = bar_data
  78.          bc.strokeColor = colors.black       # 顶部和右边轴线的颜色
  79.          bc.valueAxis.valueMin = 5000           # 设置y坐标的最小值
  80.          bc.valueAxis.valueMax = 26000         # 设置y坐标的最大值
  81.          bc.valueAxis.valueStep = 2000         # 设置y坐标的步长
  82.          bc.categoryAxis.labels.dx = 2
  83.          bc.categoryAxis.labels.dy = -8
  84.          bc.categoryAxis.labels.angle = 20
  85.          bc.categoryAxis.categoryNames = ax
  86.          # 图示
  87.          leg = Legend()
  88.          leg.fontName = 'SimSun'
  89.          leg.alignment = 'right'
  90.          leg.boxAnchor = 'ne'
  91.          leg.x = 475         # 图例的x坐标
  92.          leg.y = 240
  93.          leg.dxTextSpace = 10
  94.          leg.columnMaximum = 3
  95.          leg.colorNamePairs = items
  96.          drawing.add(leg)
  97.          drawing.add(bc)
  98.          return drawing
  99.      # 绘制图片
  100.      @staticmethod
  101.      def draw_img(path):
  102.          img = Image(path)       # 读取指定路径下的图片
  103.          img.drawWidth = 5*cm        # 设置图片的宽度
  104.          img.drawHeight = 8*cm       # 设置图片的高度
  105.          return img
复制代码
生成报告:
  1. if __name__ == '__main__':
  2.      # 创建内容对应的空列表
  3.      content = list()
  4.      # 添加标题
  5.      content.append(Graphs.draw_title('数据分析就业薪资'))
  6.      # 添加图片
  7.      content.append(Graphs.draw_img('抗疫必胜.png'))
  8.      # 添加段落文字
  9.      content.append(Graphs.draw_text('众所周知,大数据分析师岗位是香饽饽,近几年数据分析热席卷了整个互联网行业,与数据分析的相关的岗位招聘、培训数不胜数。很多人前赴后继,想要参与到这波红利当中。那么数据分析师就业前景到底怎么样呢?'))
  10.      # 添加小标题
  11.      content.append(Graphs.draw_title(''))
  12.      content.append(Graphs.draw_little_title('不同级别的平均薪资'))
  13.      # 添加表格
  14.      data = [
  15.          ('职位名称', '平均薪资', '较上年增长率'),
  16.          ('数据分析师', '18.5K', '25%'),
  17.          ('高级数据分析师', '25.5K', '14%'),
  18.          ('资深数据分析师', '29.3K', '10%')
  19.      ]
  20.      content.append(Graphs.draw_table(*data))
  21.      # 生成图表
  22.      content.append(Graphs.draw_title(''))
  23.      content.append(Graphs.draw_little_title('热门城市的就业情况'))
  24.      b_data = [(25400, 12900, 20100, 20300, 20300, 17400), (15800, 9700, 12982, 9283, 13900, 7623)]
  25.      ax_data = ['BeiJing', 'ChengDu', 'ShenZhen', 'ShangHai', 'HangZhou', 'NanJing']
  26.      leg_items = [(colors.red, '平均薪资'), (colors.green, '招聘量')]
  27.      content.append(Graphs.draw_bar(b_data, ax_data, leg_items))
  28.      # 生成pdf文件
  29.      doc = SimpleDocTemplate('report.pdf', pagesize=letter)
  30.      doc.build(content)
复制代码
生成报告的结果如下:
[attach]139342[/attach]








欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2