導覽

Python

在 Python 中建立圖片和 PDF

用 Python SDK 從範本生成圖片、PDF 或託管的圖片網址。

每個方法都接受範本 ID 和關鍵字引數。除了範本 ID 之外,所有引數都是選填。

建立圖片

create_image 會渲染範本,並回傳圖片的位元組。

#template_idstrrequired

範本 ID,例如 tpl_xxx。

#modificationslist[dict]

要放進範本圖層的值。每個項目用 name 指定一個圖層。你沒有列出的圖層會保留範本中的值。每種圖層接受哪些欄位,請見 Modifications。

#formatstrdefault: png

圖片格式:png、jpeg 或 webp。

result = client.create_image(
    "tpl_xxx",
    modifications=[
        {"name": "headline", "text": "Launch promo"},
        {"name": "price", "text": "$29"},
    ],
    format="webp",
)

if "error" in result:
    raise RuntimeError(result["error"]["message"])

with open("launch-promo.webp", "wb") as file:
    file.write(result["result"])

建立 PDF

create_pdf 接受相同的 template_id 和 modifications,沒有 format 引數。

result = client.create_pdf(
    "tpl_invoice",
    modifications=[
        {"name": "customer", "text": "Acme Studio"},
        {
            "name": "line-items",
            "columns": ["Item", "Qty", "Total"],
            "rows": [{"Item": "Automate plan", "Qty": 1, "Total": "$29.00"}],
        },
    ],
)

if "error" in result:
    raise RuntimeError(result["error"]["message"])

with open("invoice.pdf", "wb") as file:
    file.write(result["result"])

建立已儲存的圖片

create_stored_image 會渲染圖片並儲存在 Bannerify 的 CDN,回傳網址而不是位元組。網址以 https://images.bannerify.co/files/ 開頭。當你想把連結放進電子郵件、資料庫的資料列或無程式碼工具時,就可以使用它。

它接受與 create_image 相同的引數。

result = client.create_stored_image(
    "tpl_xxx",
    modifications=[{"name": "headline", "text": "Welcome back"}],
)

if "error" in result:
    raise RuntimeError(result["error"]["message"])

print(result["result"])

Python SDK 無法傳送 s3Config。若要把檔案儲存到你自己的儲存貯體,請透過 REST 呼叫建立已儲存的圖片。

處理結果

三個方法都會回傳 {"result": ...} 或 {"error": ...}。請見處理錯誤。