In today’s fast-paced business environment, barcode technology plays a crucial role in streamlining operations and enhancing data management. Among various barcode standards, GS1-128 is widely used across industries for its versatility and ability to encode detailed product information. This guide walks you through generating GS1-128 barcodes with Aspose.BarCode for .NET—from understanding Application Identifiers (AIs) to customizing appearance and exporting images.


Complete Example

This end-to-end example:

  • Builds a valid GS1 string using common AIs: (01) GTIN-14, (17) Expiry YYMMDD, (10) Batch/Lot, (21) Serial.
  • Validates lengths/formats.
  • Renders a GS1-128 image with print-friendly sizing/margins.
  • Saves a PNG file.
    You can hardcode values or pass them via command-line 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) { ... }
    }
}

Build & Run

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

The output PNG will be written to your working directory.


Step-by-Step Guide

Step 1: Understanding GS1-128 Basics

GS1-128 is a Code 128–based symbology that encodes data using Application Identifiers (AIs). Each AI defines what follows (data type & length).

Common AIs:

  • (01) GTIN-14 (fixed 14 digits; pad with zeros on the left if shorter)
  • (17) Expiration date (YYMMDD)
  • (10) Batch/Lot (variable length)
  • (21) Serial (variable length)

FNC1 handling: When you pass a human-readable string with parentheses (e.g., (01)1234...(10)LOT), the library automatically inserts FNC1 separators per GS1 rules—especially needed when a variable-length AI is followed by another AI.

Step 2: Configure Barcode Settings

Use XDimension (module thickness), BarHeight, and margins to balance print density and scanner tolerance. For thermal labels, slightly higher XDimension and generous quiet zones improve first-pass read rates.

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;

Step 3: Define Application Identifiers (AIs)

Pad GTIN to 14 digits, format dates as YYMMDD, and keep variable-length AIs concise (avoid spaces/control chars).

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

Step 4: Set Barcode Text

You can set the GS1 text in the constructor or later via generator.CodeText. The example sets it in the constructor and shows how to reassign if needed.

Step 5: Customize Appearance

Decide whether to display the human-readable code text under the bars (CodeLocation.Below) or suppress it if your label layout prints text elsewhere.

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

Step 6: Generate & Save

Save by extension (.png, .jpg, .bmp, etc.). For label workflows, PNG is usually best (lossless).

generator.Save("GS1_128_ProductLabel.png");

Practical Tips & Gotchas

  • Quiet zones matter: If a scanner struggles, increase left/right margins and XDimension slightly.
  • Thermal printers: Age/wear can blur fine bars. Bump XDimension (e.g., 3–4 px) and keep media clean.
  • GTIN check digit: If constructing GTINs, compute/verify the Mod10 check digit to prevent field errors.
  • Date windows: The YY windowing in the example is simplistic; align with your business rules (e.g., 20xx only).
  • Version control: Store sizing/margin parameters in config so barcodes are reproducible across environments.

Conclusion

With Aspose.BarCode for .NET, creating standards-compliant GS1-128 barcodes is straightforward. Define your AIs, validate formats, tune print parameters, and export a clean PNG ready for labeling. Use the complete example above as a solid starting point, then adjust sizing/margins and validation rules to match your printers, materials, and scanners.

More in this category