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

如何将Bokeh HTML文件中多幅图存为独立PNG并打包成单Zip下载

将Bokeh网格图中的多幅图打包为Zip文件下载的解决方案

下面提供两种可行方案,分别适用于服务器端渲染和纯前端静态页面场景:

方案一:服务器端生成并打包(适合Bokeh Server项目)

通过Python的zipfile模块将导出的PNG文件打包,再提供下载触发:

from bokeh.plotting import figure, gridplot
from bokeh.io import export_png
import zipfile
import os
from tempfile import TemporaryDirectory
from bokeh.models import Button
from bokeh.events import ButtonClick
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
from flask import send_file

# 生成示例网格图的多个子图
fig1 = figure(title="图1", width=300, height=300)
fig1.line([1,2,3], [4,5,6])

fig2 = figure(title="图2", width=300, height=300)
fig2.circle([1,2,3], [6,5,4])

fig3 = figure(title="图3", width=300, height=300)
fig3.vbar(x=[1,2,3], top=[2,4,6], width=0.5)

grid = gridplot([[fig1, fig2], [fig3, None]])

def modify_doc(doc):
    doc.add_root(grid)

    # 定义下载Zip的逻辑
    def download_zip(event):
        with TemporaryDirectory() as tmpdir:
            # 逐个导出子图为PNG
            png_paths = []
            for idx, fig in enumerate([fig1, fig2, fig3], 1):
                png_path = os.path.join(tmpdir, f"子图_{idx}.png")
                export_png(fig, filename=png_path)
                png_paths.append(png_path)
            
            # 打包成Zip文件
            zip_path = "所有子图.zip"
            with zipfile.ZipFile(zip_path, 'w') as zipf:
                for path in png_paths:
                    zipf.write(path, os.path.basename(path))
            
            # 触发下载
            return send_file(zip_path, as_attachment=True)

    # 添加下载按钮
    download_btn = Button(label="下载所有子图为Zip", button_type="success")
    download_btn.on_event(ButtonClick, download_zip)
    doc.add_root(download_btn)

# 启动Bokeh Server
app = Application(FunctionHandler(modify_doc))
server = Server({'/': app}, port=5000)
server.start()
server.io_loop.add_callback(server.show, "/")
server.io_loop.start()

注意事项

  • 需安装依赖:pip install bokeh selenium flask,其中selenium是export_png依赖的渲染工具,需要配合对应浏览器驱动(如ChromeDriver)
  • 临时目录会自动清理,避免残留文件

方案二:浏览器端生成并打包(适合静态Bokeh页面)

借助前端JS库JSZip和FileSaver,直接在浏览器中完成PNG生成与Zip打包:

<!DOCTYPE html>
<html>
<head>
    <title>Bokeh网格图Zip下载</title>
    <!-- 引入Bokeh及依赖库 -->
    <script src="https://cdn.bokeh.org/bokeh/release/bokeh-3.3.4.min.js"></script>
    <script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-3.3.4.min.js"></script>
    <!-- 引入Zip处理和文件保存库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
</head>
<body>
    <div id="grid-container"></div>
    <button id="download-btn" style="margin-top:10px;">下载所有子图为Zip</button>

    <script>
        // 生成示例网格图
        const fig1 = Bokeh.Figure({title: "图1", width: 300, height: 300});
        fig1.line([1,2,3], [4,5,6]);

        const fig2 = Bokeh.Figure({title: "图2", width: 300, height: 300});
        fig2.circle([1,2,3], [6,5,4]);

        const fig3 = Bokeh.Figure({title: "图3", width: 300, height: 300});
        fig3.vbar({x: [1,2,3], top: [2,4,6], width: 0.5});

        const grid = Bokeh.GridPlot({children: [[fig1, fig2], [fig3, null]]});
        Bokeh.embed.add_document(grid, document.getElementById("grid-container"));

        // 绑定下载按钮事件
        document.getElementById("download-btn").addEventListener("click", async () => {
            const zip = new JSZip();
            const figures = [fig1, fig2, fig3];

            // 逐个导出子图为PNG Blob并添加到Zip
            for (let i = 0; i < figures.length; i++) {
                const blob = await Bokeh.export_png(figures[i]);
                zip.file(`子图_${i+1}.png`, blob);
            }

            // 生成Zip文件并触发下载
            const zipBlob = await zip.generateAsync({type: "blob"});
            saveAs(zipBlob, "所有子图.zip");
        });
    </script>
</body>
</html>

注意事项

  • 无需后端服务,直接打开HTML文件即可运行
  • 依赖外部CDN资源,需确保网络可访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:00:35