python生成pdf带标题、副标题、折线图,柱状图、饼图
时间: 2023-10-20 10:19:59 浏览: 32
要使用 Python 生成 PDF 文件,可以使用 ReportLab 库。而要在 PDF 文件中加入标题、副标题、折线图、柱状图和饼图,则需要使用其他库来生成这些图形,比如 Matplotlib 和 Seaborn。
以下是一份简单的示例代码,它使用 ReportLab、Matplotlib 和 Seaborn 来生成包含标题、副标题、折线图、柱状图和饼图的 PDF 文件:
```python
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.pagesizes import letter, landscape
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Paragraph, SimpleDocTemplate
import matplotlib.pyplot as plt
import seaborn as sns
# Generate data for the charts
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [5, 3, 8, 1, 6]
labels = ['A', 'B', 'C', 'D', 'E']
sizes = [20, 30, 40, 5, 5]
# Generate the charts
fig, ax = plt.subplots()
ax.plot(x, y1, label='Line 1')
ax.plot(x, y2, label='Line 2')
ax.legend()
plt.savefig('line_chart.png')
fig, ax = plt.subplots()
ax.bar(x, y1, label='Bar 1')
ax.bar(x, y2, bottom=y1, label='Bar 2')
ax.legend()
plt.savefig('bar_chart.png')
plt.figure()
plt.pie(sizes, labels=labels)
plt.axis('equal')
plt.savefig('pie_chart.png')
# Generate the PDF
doc = SimpleDocTemplate('report.pdf', pagesize=landscape(letter))
styles = getSampleStyleSheet()
title_style = ParagraphStyle(name='Title', fontSize=20, alignment=TA_CENTER)
subtitle_style = ParagraphStyle(name='Subtitle', fontSize=16, alignment=TA_CENTER)
# Add the title
title = Paragraph('Report Title', title_style)
doc.build([title])
# Add the subtitle
subtitle = Paragraph('Report Subtitle', subtitle_style)
doc.build([subtitle])
# Add the line chart
canvas = Canvas('report.pdf', pagesize=landscape(letter))
canvas.drawImage('line_chart.png', inch, inch, width=6*inch, height=4*inch)
canvas.showPage()
# Add the bar chart
canvas.drawImage('bar_chart.png', inch, inch, width=6*inch, height=4*inch)
canvas.showPage()
# Add the pie chart
canvas.drawImage('pie_chart.png', inch, inch, width=6*inch, height=4*inch)
canvas.showPage()
canvas.save()
```
这份示例代码会生成一个名为 `report.pdf` 的 PDF 文件,其中包含了一个标题、一个副标题、一个折线图、一个柱状图和一个饼图。请注意,这份代码可能需要根据你的具体需求进行修改。