report_generate.py 10 KB

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