En el entorno de negocios de hoy en día, la tecnología de código de barras juega un papel crucial en la simplificación de las operaciones y la mejora de la gestión de datos. Entre los diferentes estándares de codificación de Barras, GS1-128 se utiliza ampliamente en todas las industrias por su versatilidad y capacidad de encodificar información detallada del producto. Esta guía le lleva a través de generar códigos de barra GS1-128, con Aspose.BarCode para .NET—desde la comprensión de Identificadores de Aplicaciones (AIs) a la personalización del aspecto e exportación de imágenes.

Ejemplo completo

Este ejemplo de fin a fin:

  • Construye una cadena de GS1 válida utilizando los AIs comunes: (01) GTIN-14, (17) Expiry YYMMDD* , () Batch/Lot* y (21) Serial*.
  • Valida las longitudes/formatos.
  • Rendera una imagen GS1-128 con tamaño/marginaje de impresión amigable.
  • Salva un archivo PNG. Puedes ver valores de código duro o pasarlos a través de argas de línea de comando.
// 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) { ... }
    }
}
  • Construir y correr*
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

La salida de PNG se escribirá en su directorio de trabajo.

Guía paso a paso

Paso 1: Comprender los principios básicos de GS1-128

GS1-128 es una simbología basada en el código 128** que codifica los datos utilizando los identificadores de aplicaciones (AI)**. Cada AI define lo que sigue (tipo y longitud de datos).

Los AIS comunes:

  • (01) GTIN-14 (fixtos 14 dígitos; en la izquierda con cero si más corto)
  • (17) Fecha de expiración (** YYMMDD**)
  • (10) Batch/Lot (** longitud variable**)
  • (21) Serial (** longitud variable**)

FNC1 manejo: Cuando usted pasa una cadena de lectura humana con parentesas (por ejemplo, (01)1234...(10)LOT), la biblioteca inserta automáticamente los separadores FNC1 según las reglas de GS1 - especialmente necesario cuando un AI de longitud variable** es seguido por otro AI.

Paso 2: Configure la configuración de barcode

Utilice XDimension (densidad de módulo), BarHeight, y margin para equilibrar la densidad del impreso y la tolerancia del escáner.Para las etiquetas térmicas, la XDimensión ligeramente superior y las generosas zonas silenciosas mejoran las tasas de lectura de primer paso.

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;

Paso 3: Definición de Identificadores de Aplicaciones (AIs)

Pad GTIN a 14 dígitos, datas de formato como YYMMDD y mantenga los AIs de longitud variable concis (evitar espacios/carros de control).

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

Paso 4: Configurar el código de barras

Puede configurar el texto GS1 en el constructor o más tarde a través de generator.CodeTextEl ejemplo lo coloca en el constructor y muestra cómo reajustar si es necesario.

Paso 5: Personalizar la apariencia

Decide si mostrar el texto de código humano-leerable** debajo de las barras (CodeLocation.Belowo suprimirlo si su layout de etiqueta imprime texto en otro lugar.

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

Paso 6: Generar y salvar

Salvación por extensión (.png, .jpg, .bmpPara los flujos de trabajo de etiqueta, PNG suele ser el mejor (sin pérdida).

generator.Save("GS1_128_ProductLabel.png");

Consejos y Gotchas

  • Quiet zonas materia: Si un escáner lucha, aumentar las margen izquierda/derecha y XDimension ligeramente.
  • Primeras térmicas: La edad/la ropa puede derretir barras finas. XDimension (por ejemplo, 3-4 px) y mantener los medios limpios.
  • Digital de verificación de GTIN: Si está construyendo GTINS, computa/verifique el número de control de Mod10 para evitar errores de campo.
  • Las ventanas de fecha: La ventana YY en el ejemplo es simplificada; alineada con sus reglas de negocio (por ejemplo, sólo 20xx).
  • Control de versión: Almacenar los parámetros de tamaño/margen en configuración para que los códigos de barras sean reproducibles en todos los entornos.

Conclusión

Con Aspose.BarCode para .NET, la creación de los códigos de barras GS1-128** conforme a los estándares es sencilla. Define sus AIs, valida los formatos, los parámetros de impresión de toneladas y exporta un PNG limpio preparado para la etiquetación. Utilice el ejemplo completo anteriormente como un punto de partida sólido, luego ajuste las reglas de tamaño/margen y validación para ajustar sus impresoras, materiales y escáneres.

More in this category