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

如何将Great Tables生成的表格保存为PDF文件?

解决Great Tables生成PDF的问题

问题1:生成PNG而非PDF的解决方法

Great Tables的save方法默认会生成图片格式,要导出PDF需使用专门的save_as_pdf方法,同时配置Selenium驱动支持PDF打印功能:

  1. 给FirefoxOptions添加PDF打印的偏好设置
  2. 将原代码中的save方法替换为save_as_pdf

修改后的完整代码:

from great_tables import GT
from great_tables.data import sp500

# Selenium 4, Firefox
from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager

options = webdriver.FirefoxOptions()
options.add_argument("--headless")
# 配置PDF打印相关偏好
options.set_preference("print.print_to_file", True)
options.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_file", True)
options.set_preference("print.printer_Mozilla_Save_to_PDF.print_settings", '{"isLandscape": false}')

driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options)

# 定义数据日期范围
start_date = "2010-06-07"
end_date = "2010-06-14"

# 筛选数据
sp500_mini = sp500[(sp500["date"] >= start_date) & (sp500["date"] <= end_date)]

# 创建表格并导出PDF
(
    GT(sp500_mini)
    .tab_header(title="S&P 500", subtitle=f"{start_date} to {end_date}")
    .fmt_currency(columns=["open", "high", "low", "close"])
    .fmt_date(columns="date", date_style="wd_m_day_year")
    .fmt_number(columns="volume", compact=True)
    .cols_hide(columns="adj_close")
).save_as_pdf(
    file="test.pdf",
    web_driver=driver,
    window_size=(6000, 6000)
)

# 关闭浏览器驱动,释放资源
driver.quit()

问题2:webdriver="firefox"报错的解决方法

报错InvalidArgumentException: Message: binary is not a Firefox executable是因为系统无法自动定位Firefox的可执行文件,需手动指定binary路径:

  • Windows路径示例:options.binary_location = "C:\\Program Files\\Mozilla Firefox\\firefox.exe"
  • Linux路径示例:options.binary_location = "/usr/bin/firefox"
  • macOS路径示例:options.binary_location = "/Applications/Firefox.app/Contents/MacOS/firefox"

将上述配置加入FirefoxOptions后,再使用自定义驱动即可解决报错问题。

额外注意事项

  • 确保已安装Firefox浏览器,webdriver-manager会自动匹配兼容的GeckoDriver版本
  • 安装必要依赖:pip install great-tables selenium webdriver-manager pandas
  • 导出PDF后务必调用driver.quit()关闭浏览器进程,避免资源浪费

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:12:45