Trong môi trường kinh doanh nhanh chóng ngày nay, công nghệ mã thanh đóng một vai trò quan trọng trong việc đơn giản hóa hoạt động và cải thiện quản lý dữ liệu. Trong số các tiêu chuẩn mã vạch khác nhau, GS1-128 được sử dụng rộng rãi trên toàn ngành vì sự đa dạng và khả năng mã hóa thông tin sản phẩm chi tiết. Hướng dẫn này hướng dẫn bạn thông qua việc tạo mã Vạch GS1-128, với Aspose.BarCode cho .NET – từ sự hiểu biết về Application Identifiers (AIs) để tùy chỉnh ngoại hình và xuất khẩu hình ảnh.

Một ví dụ đầy đủ

Ví dụ cuối cùng này:

  • Xây dựng một dòng GS1 có hiệu lực bằng cách sử dụng AIs thông thường: (01) GTIN-14, (17) Expiry YYMMDD* , () Batch/Lot* và (21) Serial*.
  • Chứng nhận chiều dài / định dạng.
  • Render một GS1-128 hình ảnh với kích thước / margin thân thiện với in.
  • Tiết kiệm file PNG Bạn có thể mã hóa các giá trị cứng hoặc chuyển chúng thông qua dòng lệnh args.
// File: Program.cs
// Compile: dotnet add package Aspose.BarCode && dotnet build
// Run (examples):
//   dotnet run --project . -- 1234567890123 260930 ABC123 SN-00987
//   dotnet run --project . -- 400638133393 260930 LOT-77 SER-42   (GTIN will be padded to 14 digits)

using System;
using Aspose.BarCode.Generation;

namespace GS1_128_BarcodeExample
{
    class Program
    {
        static int Main(string[] args)
        {
            try
            {
                // ---------------------------
                // 1) Read inputs (or defaults)
                // ---------------------------
                // Args: [0]=GTIN (≤14 digits), [1]=EXP YYMMDD, [2]=BATCH (var len), [3]=SERIAL (var len)
                string gtinRaw    = args.Length > 0 ? args[0] : "1234567890123";
                string expYyMmDd  = args.Length > 1 ? args[1] : "260930";       // 2026-09-30
                string batchLot   = args.Length > 2 ? args[2] : "ABC123";
                string serial     = args.Length > 3 ? args[3] : "SN-00987";

                // ---------------------------
                // 2) Normalize & validate
                // ---------------------------
                // Ensure GTIN is 14 digits (pad left with zeros when shorter)
                if (gtinRaw.Length > 14 || !IsAllDigits(gtinRaw))
                    throw new ArgumentException("GTIN must be numeric and ≤ 14 digits.");

                string gtin14 = gtinRaw.PadLeft(14, '0');
                if (gtin14.Length != 14) throw new ArgumentException("GTIN must be exactly 14 digits after padding.");

                // Optional (advanced): you can calculate or verify GTIN check digit here if desired.

                if (!IsValidYyMmDd(expYyMmDd))
                    throw new ArgumentException("(17) Expiration must be YYMMDD and represent a valid calendar date.");

                // Variable-length AIs (10) & (21) can be any non-empty strings; keep them short & scanner-friendly.
                if (string.IsNullOrWhiteSpace(batchLot)) throw new ArgumentException("(10) Batch/Lot cannot be empty.");
                if (string.IsNullOrWhiteSpace(serial))   throw new ArgumentException("(21) Serial cannot be empty.");

                // ---------------------------
                // 3) Compose GS1 code text
                // ---------------------------
                // Parentheses are human-readable; the library handles FNC1 as needed.
                string gs1Text = $"(01){gtin14}(17){expYyMmDd}(10){batchLot}(21){serial}";

                // ---------------------------
                // 4) Configure generator
                // ---------------------------
                using (var generator = new BarCodeGenerator(EncodeTypes.GS1_128, gs1Text))
                {
                    // Minimum module (bar) thickness — increase for thermal printers / rough media
                    generator.Parameters.Barcode.XDimension.Pixels = 3;

                    // Symbol height (for 1D-like linear symbol height inside GS1-128 area)
                    generator.Parameters.Barcode.BarHeight.Millimeters = 22f;

                    // Target output size (entire image). Adjust per label stock / DPI.
                    generator.Parameters.Barcode.ImageWidth.Inches  = 2.8f;
                    generator.Parameters.Barcode.ImageHeight.Inches = 1.2f;

                    // Quiet zones (margins) — critical for scan reliability
                    generator.Parameters.Barcode.LeftMargin.Millimeters   = 4f;
                    generator.Parameters.Barcode.RightMargin.Millimeters  = 4f;
                    generator.Parameters.Barcode.TopMargin.Millimeters    = 2f;
                    generator.Parameters.Barcode.BottomMargin.Millimeters = 2f;

                    // Human-readable text placement and formatting
                    generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
                    generator.Parameters.Barcode.CodeTextParameters.FontSize.Point = 8f;
                    generator.Parameters.Barcode.CodeTextParameters.Space.Millimeters = 1.0f;

                    // ---------------------------
                    // 5) Save image (by extension)
                    // ---------------------------
                    string fileName = $"GS1_128_{gtin14}_{batchLot}_{serial}.png";
                    generator.Save(fileName);
                    Console.WriteLine($"✅ GS1-128 barcode saved: {fileName}");
                }

                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("❌ Error: " + ex.Message);
                Console.Error.WriteLine("Usage: <exe> <gtin≤14digits> <expYYMMDD> <batch> <serial>");
                return 1;
            }
        }

        // ---- Helpers ---------------------------------------------------------

        // Minimal YYMMDD validation (1900–2099 windowing for simplicity)
        static bool IsValidYyMmDd(string yymmdd)
        {
            if (string.IsNullOrWhiteSpace(yymmdd) || yymmdd.Length != 6) return false;
            if (!IsAllDigits(yymmdd)) return false;

            int yy = int.Parse(yymmdd.Substring(0, 2));
            int mm = int.Parse(yymmdd.Substring(2, 2));
            int dd = int.Parse(yymmdd.Substring(4, 2));

            int year = (yy >= 0 && yy <= 79) ? 2000 + yy : 1900 + yy; // simple window
            try
            {
                var _ = new DateTime(year, mm, dd);
                return true;
            }
            catch
            {
                return false;
            }
        }

        static bool IsAllDigits(string s)
        {
            foreach (char c in s)
                if (c < '0' || c > '9') return false;
            return true;
        }

        // Optional: GTIN-14 check digit calculator (Mod10). Use if you build GTIN from the first 13 digits.
        // static char CalcGtin14CheckDigit(string first13Digits) { ... }
    }
}
  • Xây dựng & chạy *
dotnet new console -n GS1_128_BarcodeExample -f net8.0
cd GS1_128_BarcodeExample
dotnet add package Aspose.BarCode
# Replace Program.cs with the code above, then:
dotnet run -- 1234567890123 260930 ABC123 SN-00987

Kết quả PNG sẽ được viết vào thư mục làm việc của bạn.

Hướng dẫn Step-by-Step

Bước 1: Hiểu GS1-128

GS1-128 là một biểu tượng Code 128-based mà mã hóa dữ liệu bằng cách sử dụng Application Identifiers (AIs).

chung AIS:

  • (01) GTIN-14 (cài 14 chữ số; dán với zeros ở bên trái nếu ngắn hơn)
  • (17) Ngày hết hạn (YYMMDD)
  • (10) Batch/Lot (** chiều dài thay đổi**)
  • (21) Serial (** chiều dài thay đổi**)

FNC1 xử lý: Khi bạn vượt qua một chuỗi có thể đọc bởi con người với parentheses (ví dụ: (01)1234...(10)LOTThư viện sẽ tự động nhập các bộ phân chia FNC1 theo các quy tắc GS1 – đặc biệt cần thiết khi AI có chiều dài thay đổi được theo sau bởi AI khác.

Bước 2: Cài đặt Barcode

Sử dụng XDimension (tinh độ mô-đun), BarHeight, và margins để cân bằng mật độ in và dung nạp quét. Đối với các nhãn nhiệt, XDdimension cao hơn một chút và vùng yên tĩnh rộng rãi cải thiện tỷ lệ đọc lần đầu tiên.

generator.Parameters.Barcode.XDimension.Pixels = 3;
generator.Parameters.Barcode.BarHeight.Millimeters = 22f;
generator.Parameters.Barcode.LeftMargin.Millimeters = 4f;
generator.Parameters.Barcode.RightMargin.Millimeters = 4f;
generator.Parameters.Barcode.TopMargin.Millimeters = 2f;
generator.Parameters.Barcode.BottomMargin.Millimeters = 2f;

Bước 3: Định nghĩa ID ứng dụng (AIs)

Nhấn GTIN đến 14 chữ số, định dạng ngày là YYMMDD và giữ cho AIs chiều dài thay đổi mỏng manh (không tránh không gian/chế độ điều khiển).

string gtin14 = gtinRaw.PadLeft(14, '0');
string gs1Text = $"(01){gtin14}(17){expYyMmDd}(10){batchLot}(21){serial}";

Bước 4: Thiết lập Barcode Text

Bạn có thể đặt văn bản GS1 trong máy xây dựng hoặc sau đó thông qua generator.CodeTextVí dụ đặt nó trong nhà xây dựng và cho thấy làm thế nào để phân bổ lại nếu cần thiết.

Bước 5: Tùy chỉnh xuất hiện

Quyết định xem bạn có thể hiển thị văn bản mã người đọc** dưới các thanh (CodeLocation.Belowhoặc xóa nó nếu bố trí nhãn của bạn in văn bản ở nơi khác.

generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
generator.Parameters.Barcode.CodeTextParameters.FontSize.Point = 8f;
generator.Parameters.Barcode.CodeTextParameters.Space.Millimeters = 1.0f;

Bước 6: Tạo và tiết kiệm

Tiết kiệm bằng cách mở rộng (.png, .jpg, .bmpĐối với dòng công việc nhãn, PNG thường là tốt nhất (không thua lỗ).

generator.Save("GS1_128_ProductLabel.png");

Hướng dẫn & Gotchas

  • Quiet zones matter: Nếu một scanner chiến đấu, tăng giới hạn trái / phải và XDimension một chút.
  • ** Máy in nhiệt:** Tuổi / quần áo có thể mọc thanh tốt. XDimension (ví dụ, 3-4 px) và giữ cho phương tiện truyền thông sạch sẽ.
  • GTIN kiểm số: Nếu bạn đang xây dựng GTIN, tính toán / kiểm tra số kiểm Mod10 để ngăn chặn lỗi trường.
  • Cửa sổ ngày: Các cửa sổ YY trong ví dụ là đơn giản; phù hợp với các quy tắc kinh doanh của bạn (ví dụ, chỉ 20xx).
  • Kiểm soát phiên bản: Lưu trữ các thông số kích thước/thanh trong cấu hình để mã thanh có thể được tái tạo trên khắp môi trường.

Kết luận

Với Aspose.BarCode cho .NET, việc tạo mã vạch GS1-128** phù hợp với tiêu chuẩn là đơn giản. Thiết lập AIs của bạn, xác nhận định dạng, thông số in tune, và xuất một PNG sạch đã sẵn sàng để nhãn. Sử dụng ví dụ đầy đủ ở trên như là một điểm khởi đầu vững chắc, sau đó điều chỉnh quy tắc kích thước / ranh giới và xác minh để tương thích với máy in, vật liệu và quét.

More in this category