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

使用WeasyPrint生成PDF并存储到Google Bucket遇无效文件问题

解决Google Functions生成PDF并存储到Google Bucket的无效文件问题

错误原因

你之前的代码存在两个关键问题:

  1. 错误地将WeasyPrint的HTML对象直接转为字符串(str(document))写入,写入的是对象的描述文本而非实际PDF二进制数据;
  2. 以文本模式("w")打开Blob,PDF属于二进制文件,文本模式会破坏字节结构导致文件损坏。

正确解决方案

以下两种方法均可生成有效的PDF并存储到Google Bucket:

方法一:让WeasyPrint直接写入Blob文件对象

以二进制写入模式打开Blob,调用write_pdf直接将PDF内容写入:

# 定义HTML内容
html_content = "<html><title>Hello</title><body><p>Hi!</p></body></html>"

# 初始化WeasyPrint HTML对象
document = weasyprint.HTML(string=html_content, encoding='UTF-8')

# 连接Google Cloud Storage
client = storage.Client()
bucket = client.get_bucket("monthly-customer-reports")
blob = bucket.blob("Hello.pdf")

# 二进制模式打开Blob,写入PDF内容
with blob.open("wb") as f:
    document.write_pdf(f)

方法二:先生成PDF字节数据再上传

先通过write_pdf()获取PDF的二进制字节串,再使用upload_from_bytes上传:

# 定义HTML内容
html_content = "<html><title>Hello</title><body><p>Hi!</p></body></html>"

# 生成PDF字节数据
document = weasyprint.HTML(string=html_content, encoding='UTF-8')
pdf_bytes = document.write_pdf()

# 连接Google Cloud Storage并上传
client = storage.Client()
bucket = client.get_bucket("monthly-customer-reports")
blob = bucket.blob("Hello.pdf")
blob.upload_from_bytes(pdf_bytes)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:32:41