오늘날의 빠른 비즈니스 환경에서 바코드 기술은 운영을 단순화하고 데이터 관리를 향상시키는 데 중요한 역할을합니다. GS1-128는 다양성과 상세한 제품 정보를 암호화 할 수있는 능력 때문에 다양한 산업에서 널리 사용됩니다.이 가이드는 Aspose.BarCode for .NET* - Application Identifiers (AIs)를 이해하여 외관을 사용자 정의하고 이미지를 내보내는 것을 통해 GS1-128.

완전한 예제

이 끝에서 끝까지의 예:

  • 일반 AIs를 사용하여 유효한 GS1 스트립을 구축합니다: (01) GTIN-14,**(17) Expiry YYMMDD****, () Batch/Lot(21) Serial.
  • 길이 / 형식을 확인합니다.
  • GS1-128 이미지를 인쇄 친화적 인 크기 / 마진을 제공합니다.
  • PNG 파일을 저장합니다. 하드 코드 값을 입력하거나 명령 라인 아그를 통해 통과할 수 있습니다.
// 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) { ... }
    }
}
  • 건설 및 실행*
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

PNG 출력은 작업 디렉토리에 작성됩니다.

단계별 가이드

단계 1 : GS1-128의 기본 사항을 이해합니다.

GS1-128은 ** 코드 128- 기반** 상징으로 데이터를 암호화하는 ** 애플리케이션 식별자 (AI)**. 각 AI는 다음을 정의합니다 (데이터 유형 및 길이).

일반적인 AIS :

  • (01) GTIN-14 (정확한 14 숫자; 왼쪽에 제로가있는 패드 더 짧은 경우)
  • (17) 종료 날짜 (** YYMMDD**)
  • (10) 배치 / 로트 (** 변수 길이**)
  • (21) 시리즈 (** 변수 길이**)

FNC1 처리: 인간이 읽을 수 있는 링을 통과할 때 (예를 들어, (01)1234...(10)LOT도서관은 GS1 규칙에 따라 FNC1 분리기를 자동으로 입력합니다 - 특히 변형 길이 AI가 다른 AI에 의해 추적되는 경우에 필요합니다.

2단계 : 바코드 설정 설정

XDimension (모듈 두께), BarHeightmargins를 사용하여 인쇄 밀도와 스캐너 관용을 균형 잡으십시오. 열 라벨의 경우, 조금 더 높은 XDdimension 및 광범위한 조용한 영역은 첫 번째 통과 읽기 속도를 향상시킵니다.

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;

단계 3 : 응용 프로그램 식별자 (AI)를 정의합니다.

GTIN을 14 숫자로 패드하고, 형식 날짜는 YYMMDD이며, 변수 길이의 AIs를 조화롭게 유지합니다 (공간/컨트롤 탱크를 피하십시오).

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

단계 4 : 바코드 텍스트 설정

GS1 텍스트를 건축기 또는 나중에 설정할 수 있습니다. generator.CodeText예제는 그것을 건축기에 넣고 필요한 경우 재배치하는 방법을 보여줍니다.

단계 5 : 사용자 정의

  • 인간 읽을 수 있는 코드 텍스트**를 표시하는지 여부를 결정하십시오(CodeLocation.Below) 또는 레이블 레이아웃이 다른 곳에서 텍스트를 인쇄하는 경우 삭제합니다.
generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
generator.Parameters.Barcode.CodeTextParameters.FontSize.Point = 8f;
generator.Parameters.Barcode.CodeTextParameters.Space.Millimeters = 1.0f;

단계 6 : 생성 및 저장

확장에 의해 저장 (.png, .jpg, .bmp라벨 작업 흐름의 경우 PNG는 일반적으로 최고입니다 (실패가 없습니다).

generator.Save("GS1_128_ProductLabel.png");

실용적인 팁 & Gotchas

  • Quiet zones matter: 스캐너가 싸우면 왼쪽/오른쪽 경계선과 XDimension을 약간 늘리십시오.
  • 열 프린터: 나이 / 옷은 얇은 바를 갈아 넣을 수 있습니다. XDimension (예를 들어 3 ~ 4 px) 그리고 미디어를 깨끗하게 유지합니다.
  • GTIN 체크 디지털: GTIN을 구축하는 경우, 필드 오류를 방지하기 위해 Mod10 검사 디지를 계산/검증합니다.
  • ** 날짜 창:** 예제의 YY 창은 단순합니다; 비즈니스 규칙과 일치합니다 (예를 들어, 20xx만).
  • ** 버전 컨트롤:** 크기/마진 매개 변수를 구성하여 바코드가 환경 내에서 재생할 수 있도록 저장합니다.

결론

Aspose.BarCode for .NET를 사용하여 standards-compliant GS1-128 바코드를 만드는 것은 간단합니다. AIs를 정의하고, 형식을 검증하며, 톤 인쇄 매개 변수를 내보내고, 라벨링 할 준비가 된 깨끗한 PNG를 수출하십시오. 위의 완전한 예를 견고한 출발점으로 사용한 다음 크기/마진 및 인증 규칙을 조정하여 프린터, 재료 및 스캐너와 일치시킵니다.

More in this category