將產品識別碼、庫存標籤或運送標籤轉換為機器可讀的符號是許多 Python 應用程式的常見需求。 Aspose.BarCode for Python via .NET 提供強大的 SDK,讓您僅需幾行程式碼即可生成 Code 39 條碼。在本指南中,您將學習如何安裝庫、建立與自訂 Code 39 條碼,並套用效能最佳實踐,所有內容皆以完整的可執行範例為支援。

在 Python 中建立 Code 39 條碼的步驟

  1. 安裝 SDK: 執行 pip install aspose-barcode-for-python-via-net 以將此函式庫加入您的環境。
    • API 參考 顯示您將使用的 BarCodeGenerator 類別。
  2. 建立產生器實例: 初始化 BarCodeGenerator 並將 EncodeType 設為 Code39Standard。這告訴 SDK 使用 Code 39 符號。
    • 範例: generator = barcode.BarCodeGenerator()generator.encode_type = barcode.EncodeTypes.CODE39
  3. 指派條碼文字: 提供您想要編碼的資料,例如 "ABC123"
    • 產生器會根據 Code 39 規則驗證文字,並拒絕不支援的字元。
  4. 設定外觀(可選): 調整 bar_heightbar_colorback_color 等屬性,以符合您的 UI 需求。
  5. 儲存影像: 呼叫 save 並指定所需的檔名與格式(PNGJPG 等)。SDK 會將條碼寫入磁碟,隨時可供使用。

在 Python 中建立 Code 39 條碼 - 完整程式範例

以下程式碼片段展示了從安裝到儲存 PNG 檔案的完整端對端實作。

# 完整的工作範例,用於在 Python 中生成 Code 39 條碼
from aspose.barcode import generation
from aspose.pydrawing import Color

def generate_code39(text: str, output_path: str): # Initialize the barcode generator generator = generation.BarcodeGenerator( generation.EncodeTypes.CODE39, text )

將文字指派給編碼(必須是大寫字母、數字,或 - . $ / + % 空格)

generator.code_text = text.upper()

可選的外觀設定

# Fore color / bar color
generator.parameters.barcode.bar_color = Color.blue  # Blue

背景顏色 / 圖像背景顏色

generator.parameters.back_color = Color.red  # 淺黃色

條碼高度

generator.parameters.barcode.bar_height.pixels = 80.0

將條碼保存為 PNG

generator.save(output_path, generation.BarCodeImageFormat.PNG)

if name == “main”: # 示例用法 generate_code39(“ABC123”, “output/code39_barcode.png”)