Code39 是常見一維條碼規格,支援數字、大寫字母及少數符號。本文採用免費 Code39 字體 + GDI+ 繪圖方式,無需第三方元件即可在 WebForm/WinForm 產生條碼圖片。
下載 Free 3 of 9 Extended 字體(.ttf),安裝至伺服器/開發機的 C:\Windows\Fonts。IIS 應用程式集區身分需有字體讀取權限(通常預設即可)。
public sealed class Code39
{
private const int SPACE_HEIGHT = 3;
// ... 屬性:Label, LabelFont, BarCodeValue, ShowBarCodeValue, BarCodeFontSize 等 ...
// 關鍵:BarCodeValue 自動補上起止符 '*'
public string BarCodeValue
{
set { _barCodeValue = value.StartsWith("*") && value.EndsWith("*") ? value : "*" + value + "*"; }
}
// 計算圖片尺寸
private Bitmap BlankBackImage
{
get
{
using (var bmp = new Bitmap(1, 1, PixelFormat.Format32bppArgb))
using (var g = Graphics.FromImage(bmp))
{
// 量測 Label、BarCode、BarCodeString 寬高
// 回傳符合尺寸的空白 Bitmap
}
}
}
// WebForm 輸出至 Response.OutputStream
public Bitmap CreateWebForm(Stream ms, ImageFormat imageFormat)
{
using (var bmp = this.BlankBackImage)
using (var g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.SmoothingMode = SmoothingMode.HighQuality;
int vPos = 0;
// 1. 繪製 Label
// 2. 繪製條碼 (使用 "Free 3 of 9 Extended" 字體)
// 3. 可選:繪製條碼數值字串
bmp.Save(ms, imageFormat);
return bmp;
}
}
// WinForm 回傳 MemoryStream
public Stream CreateWinForm(ImageFormat imageFormat) { /* 類似邏輯 */ }
private static int XCenter(int subWidth, int globalWidth) => (globalWidth - subWidth) / 2;
}
// Barcode.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
var code39 = new Code39();
code39.BarCodeValue = "LDSO-001";
code39.BarCodeFontSzie = 60;
code39.ShowBarCodeValue = true; // 底部顯示數值
// 直接輸出至瀏覽器
code39.CreateWebForm(Response.OutputStream, ImageFormat.Gif);
}
前端嵌入:<img src="Barcode.aspx" />
var code39 = new Code39();
code39.BarCodeValue = "WIN-12345";
code39.BarCodeFontSzie = 48;
using (var ms = code39.CreateWinForm(ImageFormat.Png))
{
pictureBox1.Image = Image.FromStream(ms);
}
| 問題 | 原因與解決 |
|---|---|
| 條碼無法掃描 | 1. 字體未安裝 2. 字體大小過小(建議 ≥ 36pt) 3. 缺少起止符 '*'(本類別自動補齊) 4. 解析度不足(列印時需 300 DPI 以上) |
| Web 伺服器部署後不顯示 | 檢查 IIS 應用程式集區身分是否有字體讀取權限;或將字體檔放在專案目錄用 PrivateFontCollection 載入 |
| 中文/特殊符號掃描失敗 | Code39 原生不支援中文,需改用 Code128 或 QR Code |
ZXing.Net(開源、支援 Code128/QR/PDF417、純 managed、高效能)。