当前位置:   article > 正文

python Matplotlib Tkinter-->导出pdf报表

python Matplotlib Tkinter-->导出pdf报表
环境
python:python-3.12.0-amd64
包:
matplotlib 3.8.2
reportlab 4.0.9
  1. import matplotlib.pyplot as plt
  2. from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
  3. import tkinter as tk
  4. import tkinter.messagebox as messagebox
  5. import tkinter.ttk as ttk
  6. from reportlab.lib.pagesizes import letter
  7. from reportlab.lib import colors
  8. from reportlab.lib.units import inch
  9. from reportlab.platypus import Table, TableStyle, SimpleDocTemplate, Image
  10. from reportlab.pdfbase import pdfmetrics
  11. from reportlab.pdfbase.ttfonts import TTFont
  12. from io import BytesIO
  13. # 加载中文字体
  14. font_path = r'C:\Windows\Fonts\STZHONGS.TTF'
  15. pdfmetrics.registerFont(TTFont('SimHei', font_path))
  16. print(pdfmetrics.getRegisteredFontNames())
  17. # 导出 PDF 报表
  18. def export_pdf():
  19. # 将 matplotlib 图形转化为图像
  20. buf = BytesIO()
  21. fig1.savefig(buf, format='png', dpi=80)
  22. buf.seek(0)
  23. img = Image(buf, width=8 * inch, height=3 * inch)
  24. # 创建 PDF 表格
  25. data = [['堆体体积盘点报表', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8'],
  26. ['名称', '堆体长度', '堆体宽度', '堆体高度', '占地面积', '堆体体积', '堆体密度', '堆体重量'],
  27. ['1号仓', '36.022', '36.024', '35.063', '1019.495', '28105.247', '0.540', '15176.833'],
  28. ['制表人:', '', '审核人:', '', '经理:', '', '日期:', '2022-7-9'],
  29. ['堆体三维立体效果图', '', '', 'row4', '', '', '', ''],
  30. [img, '', '', '', 'row5', '', '', ''],
  31. ['内容7', '', '', '', '', 'row6', '', '']]
  32. table = Table(data, colWidths=[1 * inch] * 8, rowHeights=[0.5 * inch] * 5 + [3.1 * inch] * 2)
  33. table.setStyle(TableStyle([
  34. ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
  35. ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
  36. ('FONTNAME', (0, 0), (-1, 0), 'SimHei'),
  37. ('FONTSIZE', (0, 0), (-1, 0), 14),
  38. ('BOTTOMPADDING', (0, 0), (-1, 0), 16),
  39. ('SPAN', (0, 0), (7, 0)),
  40. ('SPAN', (0, 4), (7, 4)),
  41. ('SPAN', (0, 5), (7, 5)),
  42. ('SPAN', (0, 6), (7, 6)),
  43. ('TEXTCOLOR', (0, 1), (-1, -1), colors.black),
  44. ('ALIGN', (0, 1), (-1, -1), 'CENTER'),
  45. ('FONTNAME', (0, 1), (-1, -1), 'SimHei'),
  46. ('FONTSIZE', (0, 4), (-1, 4), 14),
  47. ('BOTTOMPADDING', (0, 1), (-1, -1), 16),
  48. ('GRID', (0, 0), (-1, -1), 1, colors.black)
  49. ]))
  50. # 保存 PDF 文件并显示导出成功的消息框
  51. pdf_file = SimpleDocTemplate("三维激光雷达 1号仓体积报表20220709.pdf", pagesize=letter)
  52. pdf_file.build([table])
  53. messagebox.showinfo('导出成功', 'PDF 文件已成功导出!')
  54. # 创建自定义工具栏类
  55. class MyNavigationToolbar(NavigationToolbar2Tk):
  56. toolitems = [('Home', '回到初始状态', 'home', 'home'),
  57. ('Back', '后退', 'back', 'back'),
  58. ('Home', '前进', 'forward', 'forward'),
  59. ('Pan', '平移', 'move', 'pan'),
  60. ('Zoom', '缩放', 'zoom_to_rect', 'zoom'),
  61. ('Save', '保存', 'filesave', 'save_figure')]
  62. def __init__(self, *args, **kwargs):
  63. show_toolbar = kwargs.pop('show_toolbar', True)
  64. super().__init__(*args, **kwargs)
  65. if not show_toolbar:
  66. self.pack_forget()
  67. self.custom_button_img1 = tk.PhotoImage(file='figure_pic1.png') # 创建第一个图片按钮
  68. self.custom_button1 = ttk.Button(self, image=self.custom_button_img1, command=lambda: print('111.'))
  69. self.custom_button1.pack(side=tk.LEFT) # 添加按钮到工具栏上
  70. self.custom_button_img2 = tk.PhotoImage(file='figure_pic2.png') # 创建第二个图片按钮
  71. self.custom_button2 = ttk.Button(self, image=self.custom_button_img2, command=export_pdf)
  72. self.custom_button2.pack(side=tk.LEFT) # 添加按钮到工具栏上
  73. # 创建 Tkinter 窗口
  74. window = tk.Tk()
  75. window.title("Matplotlib in Tkinter")
  76. # 设置窗口大小和位置
  77. window.geometry('800x600')
  78. # 创建选项卡控件
  79. notebook = ttk.Notebook(window)
  80. # 创建第一个选项卡
  81. tab1 = ttk.Frame(notebook)
  82. fig1 = plt.figure()
  83. plt.plot([1, 2, 3], [4, 5, 6])
  84. canvas1 = FigureCanvasTkAgg(fig1, master=tab1)
  85. canvas1.draw()
  86. toolbar1 = MyNavigationToolbar(canvas1, tab1)
  87. toolbar1.update()
  88. toolbar1.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
  89. canvas1.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
  90. notebook.add(tab1, text='图表1')
  91. # 创建第二个选项卡
  92. tab2 = ttk.Frame(notebook)
  93. fig2 = plt.figure()
  94. plt.plot([3, 2, 1], [6, 5, 4])
  95. canvas2 = FigureCanvasTkAgg(fig2, master=tab2)
  96. canvas2.draw()
  97. toolbar2 = MyNavigationToolbar(canvas2, tab2, show_toolbar=False)
  98. toolbar2.update()
  99. canvas2.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
  100. notebook.add(tab2, text='图表2')
  101. notebook.pack(fill=tk.BOTH, expand=True)
  102. window.mainloop()

 注:

C:\Windows\Fonts\STZHONGS.TTF

STZHONGS.TTF 此名称是文件夹C:\Windows\Fonts\下面的文件属性里面的名称

 

图片资源下载(分享-->python Matplotlib  Tkinter图片):

链接:https://pan.baidu.com/s/1vFOU52gG0bgK8RYuj-dzOg 
提取码:2oy0 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/153604
推荐阅读
相关标签
  

闽ICP备14008679号