欢迎访问宙启技术站
智能推送

利用Python生成带图表的PDF文档

发布时间:2024-01-09 17:48:20

要用Python生成带图表的PDF文档,可以使用第三方库reportlab。reportlab可以用来创建PDF文档,并且提供了一些用于生成图表的功能。

首先,需要通过 pip 安装 reportlab:

pip install reportlab

接下来,可以通过以下示例代码来生成带图表的PDF文档:

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.graphics.charts.linecharts import HorizontalLineChart
from reportlab.graphics.shapes import Drawing
from reportlab.lib.chartthemes import getSampleTheme

def generate_pdf_with_chart(data):
    # 创建PDF文档
    doc = SimpleDocTemplate("chart.pdf", pagesize=letter)

    # 定义数据
    chart_data = []
    for item in data:
        chart_data.append(item['value'])

    # 创建图表
    drawing = Drawing(400, 200)

    chart = HorizontalLineChart()
    chart.x = 50
    chart.y = 50
    chart.width = 300
    chart.height = 100

    # 设置样式
    theme = getSampleTheme()
    theme.chartColors = [colors.blue, colors.red]  # 设置图表颜色
    chart.setProperties(theme)

    # 添加数据
    chart.data = [chart_data]
    chart.categoryAxis.labels.boxAnchor = 'n'
    chart.categoryAxis.labels.dx = 8
    chart.categoryAxis.labels.dy = -2
    chart.categoryAxis.labels.angle = 30
    chart.categoryAxis.categoryNames = [item['label'] for item in data]

    # 添加图表
    drawing.add(chart)

    # 创建PDF页面
    elements = []
    elements.append(drawing)

    # 将图表添加到PDF文档中
    doc.build(elements)

if __name__ == "__main__":
    # 测试数据
    data = [
            {'label': 'A', 'value': 10},
            {'label': 'B', 'value': 20},
            {'label': 'C', 'value': 30},
            {'label': 'D', 'value': 40}
        ]

    # 生成带图表的PDF文档
    generate_pdf_with_chart(data)

在上面的示例代码中,首先,我们导入了 reportlab 的相关模块。然后,我们定义了一个 generate_pdf_with_chart 函数,用于生成带图表的PDF文档。在该函数中,我们首先创建了一个PDF文档对象,然后定义了一个图表对象,并设置了图表的样式和数据。最后,我们将图表添加到PDF文档中,并保存生成的PDF文件。

以上是一个简单的例子,可以根据需要自定义更复杂的图表样式和数据。通过使用 reportlab 库,可以方便地使用Python生成带图表的PDF文档。