You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python变量传入wkhtmltopdf渲染的HTML的script标签?

解决Python传递变量到HTML script标签给Google Charts的问题

核心思路

将Python中的图表数据转换为JSON格式,直接注入到HTML的script代码中——JSON语法与JavaScript数组/对象语法兼容,可让Google Charts直接调用动态数据。

具体实现步骤

1. Python端处理数据

以Jinja2模板引擎为例(pdfkit常用模板方案),先整理图表数据,用json.dumps()序列化为JSON字符串,再传入模板上下文:

import json
import pdfkit
from jinja2 import Template

# 准备动态图表数据(可替换为你的业务数据)
chart_data = [
    ["Price", "Size"],
    [50, 7],
    [60, 8],
    [70, 8],
    [80, 9],
    [90, 9],
]

# 转换为JSON字符串
chart_data_json = json.dumps(chart_data)

# 加载并渲染HTML模板
with open("template.html", "r", encoding="utf-8") as f:
    template_content = f.read()

template = Template(template_content)
rendered_html = template.render(chart_data=chart_data_json)

# 生成PDF,可添加额外配置确保图表渲染
options = {
    'javascript-delay': 1500,  # 给足JS加载和渲染时间
    'enable-local-file-access': None
}
pdfkit.from_string(rendered_html, "output.pdf", options=options)

2. 修改HTML模板的script部分

在script标签中直接注入模板变量,替换原硬编码的数组:

<head>
  <meta charset="utf-8" />
  <script src="http://www.gstatic.com/charts/loader.js"></script>
  <script>
    function init() {
      google.charts.load("44", { packages: ["corechart"] });
      var interval = setInterval(function () {
        if (
          google.visualization !== undefined &&
          google.visualization.DataTable !== undefined &&
          google.visualization.AreaChart !== undefined
        ) {
          clearInterval(interval);
          window.status = "ready";
          drawChart();
        }
      }, 100);
    }

    function drawChart() {
      // 注入Python传递的JSON数据
      var chartData = {{ chart_data|safe }};
      var data = google.visualization.arrayToDataTable(chartData);

      var chart = new google.visualization.AreaChart(
        document.getElementById("myChart")
      );
      chart.draw(data, null);
    }
  </script>
</head>

<body onload="init()">
  <div style="width: 950px; height: 500px" id="myChart"></div>
</body>

关键说明

  • |safe过滤器:Jinja2默认会转义HTML特殊字符,添加该过滤器可确保JSON字符串被正确解析为JavaScript数组。
  • 数据结构匹配:确保Python中chart_data的结构符合Google Charts要求(首行是列名,后续为数据行)。
  • 渲染延迟配置:如果图表未正常显示,可调整javascript-delay参数延长等待时间,保证Google Charts资源加载完成。

内容的提问来源于stack exchange,提问作者Anan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:45:34