report_generate.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # -*- coding: utf-8 -*-
  2. # ! /usr/bin/env python3
  3. # @Author : yangzihao
  4. # @CreateTime : 2024/04/17
  5. """
  6. This file is for PDF report generate.
  7. Refer to the CSDN: https://blog.csdn.net/cainiao_python/article/details/128928298
  8. """
  9. from reportlab.pdfbase import pdfmetrics # 注册字体
  10. from reportlab.pdfbase.ttfonts import TTFont # 字体类
  11. from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image # 报告内容相关类
  12. from reportlab.lib.pagesizes import A4 # 页面的标志尺寸(8.5*inch, 11*inch)
  13. from reportlab.lib.styles import getSampleStyleSheet # 文本样式
  14. from reportlab.lib import colors # 颜色模块
  15. from reportlab.graphics.charts.barcharts import VerticalBarChart # 图表类
  16. from reportlab.graphics.charts.legends import Legend # 图例类
  17. from reportlab.graphics.shapes import Drawing # 绘图工具
  18. from reportlab.lib.units import cm # 单位:cm
  19. import json
  20. import pandas as pd
  21. # 注册字体(提前准备好字体文件, 如果同一个文件需要多种字体可以注册多个)
  22. pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))
  23. class ReportPDF:
  24. """
  25. This class is for PDF report generate.
  26. """
  27. # 绘制标题
  28. @staticmethod
  29. def draw_title(title: str):
  30. # 获取所有样式表
  31. style = getSampleStyleSheet()
  32. # 拿到标题样式
  33. ct = style['Heading4']
  34. # 单独设置样式相关属性
  35. ct.fontName = 'SimSun' # 字体名
  36. ct.fontSize = 18 # 字体大小
  37. ct.leading = 30 # 行间距
  38. ct.textColor = colors.black # 字体颜色
  39. ct.alignment = 1 # 居中
  40. ct.bold = True
  41. # 创建标题对应的段落,并且返回
  42. return Paragraph(title, ct)
  43. # 绘制小标题
  44. @staticmethod
  45. def draw_little_title(title: str):
  46. # 获取所有样式表
  47. style = getSampleStyleSheet()
  48. # 拿到标题样式
  49. ct = style['Normal']
  50. # 单独设置样式相关属性
  51. ct.fontName = 'SimSun' # 字体名
  52. ct.fontSize = 15 # 字体大小
  53. # ct.leading = 15 # 行间距
  54. ct.textColor = colors.darkblue # 字体颜色
  55. # 创建标题对应的段落,并且返回
  56. return Paragraph(title, ct)
  57. # 绘制普通段落内容
  58. @staticmethod
  59. def draw_text(text: str):
  60. # 获取所有样式表
  61. style = getSampleStyleSheet()
  62. # 获取普通样式
  63. ct = style['Normal']
  64. ct.fontName = 'SimSun'
  65. ct.fontSize = 10
  66. # ct.wordWrap = 'CJK' # 设置自动换行
  67. ct.alignment = 0 # 左对齐
  68. # ct.firstLineIndent = 32 # 第一行开头空格
  69. ct.leading = 15
  70. return Paragraph(text, ct)
  71. # 绘制普通段落内容
  72. @staticmethod
  73. def draw_line_feed(text: str):
  74. # 获取所有样式表
  75. style = getSampleStyleSheet()
  76. # 获取普通样式
  77. ct = style['Normal']
  78. ct.fontName = 'SimSun'
  79. ct.fontSize = 10
  80. ct.textColor = colors.white
  81. # ct.wordWrap = 'CJK' # 设置自动换行
  82. ct.alignment = 0 # 左对齐
  83. # ct.firstLineIndent = 32 # 第一行开头空格
  84. ct.leading = 15
  85. return Paragraph(text, ct)
  86. # 绘制表格
  87. @staticmethod
  88. def draw_table(*args):
  89. # 列宽度
  90. # col_width = 120
  91. style = [
  92. ('FONTNAME', (0, 0), (-1, -1), 'SimSun'), # 字体
  93. ('FONTSIZE', (0, 0), (-1, 0), 9), # 第一行的字体大小
  94. ('FONTSIZE', (0, 1), (-1, -1), 9), # 第二行到最后一行的字体大小
  95. ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'), # 设置第一行背景颜色
  96. ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 第一行水平居中
  97. ('ALIGN', (0, 1), (-1, -1), 'CENTER'), # 第二行到最后一行左右左对齐
  98. ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # 所有表格上下居中对齐
  99. ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray), # 设置表格内文字颜色
  100. ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), # 设置表格框线为grey色,线宽为0.5
  101. # ('SPAN', (0, 1), (0, 2)), # 合并第一列二三行
  102. # ('SPAN', (0, 3), (0, 4)), # 合并第一列三四行
  103. # ('SPAN', (0, 5), (0, 6)), # 合并第一列五六行
  104. # ('SPAN', (0, 7), (0, 8)), # 合并第一列五六行
  105. ]
  106. # table = Table(args, colWidths=col_width, style=style)
  107. table = Table(args, style=style)
  108. return table
  109. # 创建图表
  110. @staticmethod
  111. def draw_bar(bar_data: list, ax: list, items: list):
  112. drawing = Drawing(500, 250)
  113. bc = VerticalBarChart()
  114. bc.x = 45 # 整个图表的x坐标
  115. bc.y = 45 # 整个图表的y坐标
  116. bc.height = 200 # 图表的高度
  117. bc.width = 350 # 图表的宽度
  118. bc.data = bar_data
  119. bc.strokeColor = colors.black # 顶部和右边轴线的颜色
  120. bc.valueAxis.valueMin = 5000 # 设置y坐标的最小值
  121. bc.valueAxis.valueMax = 26000 # 设置y坐标的最大值
  122. bc.valueAxis.valueStep = 2000 # 设置y坐标的步长
  123. bc.categoryAxis.labels.dx = 2
  124. bc.categoryAxis.labels.dy = -8
  125. bc.categoryAxis.labels.angle = 20
  126. bc.categoryAxis.categoryNames = ax
  127. # 图示
  128. leg = Legend()
  129. leg.fontName = 'SimSun'
  130. leg.alignment = 'right'
  131. leg.boxAnchor = 'ne'
  132. leg.x = 475 # 图例的x坐标
  133. leg.y = 240
  134. leg.dxTextSpace = 10
  135. leg.columnMaximum = 3
  136. leg.colorNamePairs = items
  137. drawing.add(leg)
  138. drawing.add(bc)
  139. return drawing
  140. # 绘制图片
  141. @staticmethod
  142. def draw_img(path):
  143. img = Image(path) # 读取指定路径下的图片
  144. img.drawWidth = 0.8 * cm # 设置图片的宽度
  145. img.drawHeight = 0.8 * cm # 设置图片的高度
  146. img.hAlign = 0
  147. return img
  148. def report_generate(reportDict, reportPdf):
  149. # with open(f'{reportJson}', 'r', encoding='utf-8') as f:
  150. # data = json.load(f)
  151. data = reportDict # dict
  152. # 创建PDF文档
  153. styles = getSampleStyleSheet()
  154. # 提取数据
  155. name = data["name"]
  156. algorithm_score = data["algorithmComprehensiveScore"]
  157. algorithm_level = data["algorithmLevel"]
  158. test_mileage = data["testMileage"]
  159. test_duration = data["testDuration"]
  160. algorithm_result_description = data["algorithmResultDescription"]
  161. efficient_description = data["details"]["efficient"]["description"]
  162. comfort_description = data["details"]["comfort"]["description"]
  163. efficient_description1 = data["details"]["efficient"]["description1"]
  164. efficient_description2 = data["details"]["efficient"]["description2"]
  165. comfort_description1 = data["details"]["comfort"]["description1"]
  166. comfort_description2 = data["details"]["comfort"]["description2"]
  167. # 创建表格数据
  168. # table_data = [
  169. # ["评价维度", "评价指标", "指标描述"],
  170. # ["高效性", "无障碍物停止", efficient_description1],
  171. # ["高效性", "速度", efficient_description2],
  172. # ["平顺性", "线加速度", comfort_description1],
  173. # ["平顺性", "角加速度", comfort_description2]
  174. # ]
  175. table_data = [
  176. ("评价维度", "评价指标", "指标描述"),
  177. ("高效性", "无障碍物停止", efficient_description1),
  178. ("高效性", "速度", efficient_description2),
  179. ("平顺性", "线加速度", comfort_description1),
  180. ("平顺性", "角加速度", comfort_description2)
  181. ]
  182. # 创建内容对应的空列表
  183. content = list()
  184. content.append(ReportPDF.draw_img('Pji.png'))
  185. content.append(ReportPDF.draw_title('朴津AMR算法评价报告'))
  186. infos = f"数据包: {name}, 行驶时长: {test_duration}, 行驶里程: {test_mileage}"
  187. content.append(ReportPDF.draw_text(infos))
  188. content.append(ReportPDF.draw_text(algorithm_result_description))
  189. content.append(ReportPDF.draw_text(efficient_description))
  190. content.append(ReportPDF.draw_text(comfort_description))
  191. content.append(ReportPDF.draw_line_feed("换行"))
  192. content.append(ReportPDF.draw_table(*table_data))
  193. content.append(ReportPDF.draw_line_feed("换行"))
  194. # 添加图片到PDF文档
  195. for key, value in data["graphPath"].items():
  196. content.append(Paragraph(key, styles['Heading5']))
  197. content.append(Image(value, width=480, height=120))
  198. # 创建PDF文档
  199. # pdf_file = "./report123.pdf"
  200. pdf_file = reportPdf
  201. doc = SimpleDocTemplate(pdf_file, pagesize=A4)
  202. doc.build(content)
  203. print("PDF报告已生成!")
  204. if __name__ == '__main__':
  205. reportJson = './report.json'
  206. reportPdf = "./report123.pdf"
  207. report_generate(reportJson, reportPdf)
  208. print('over')