BinaryKits.ZPL Documentation

repository·develop·Indexed 19 days ago

https://github.com/binarykits/binarykits.zpl

A library for programmatically generating ZPL (Zebra Programming Language) code for label printing. It includes BinaryKits.Zpl.Viewer for parsing ZPL strings via ZplAnalyzer and rendering them into PNG images using ZplElementDrawer. The library supports a wide range of 1D and 2D barcodes (such as Code 128, QR Code, and Data Matrix), text elements, graphic elements, and layout controls. It provides a framework for implementing custom ZPL commands by extending the CommandBase class.

Tokens
9.6K
Snippets
35
Records
47
Agent score
59%

What's inside BinaryKits.ZPL

  1. Use CustomTest.cs for rapid feature development

    develop

    For quick development and testing of new ZPL features, use the CustomTest.cs file. You can load your specific ZPL data into Data/Zpl/custom.zpl2 to test changes.

    Note: Changes to custom.zpl2 are not tracked by source control by default. If you need to track changes to this file, use the following Git commands:

    • To enable tracking: git update-index --no-skip-worktree custom.zpl2
    • To disable tracking: git update-index --skip-worktree custom.zpl2
    git update-index --no-skip-worktree Data/Zpl/custom.zpl2
  2. Render ZPL data as images using BinaryKits.Zpl.Viewer

    develop

    To preview ZPL data, use the ZplAnalyzer to parse the ZPL string into label information, and then use ZplElementDrawer to render those elements into image bytes (PNG format).

    IPrinterStorage printerStorage = new PrinterStorage();
    var drawer = new ZplElementDrawer(printerStorage);
    
    var analyzer = new ZplAnalyzer(printerStorage);
    var analyzeInfo = analyzer.Analyze(request.ZplData);
    
    foreach (var labelInfo in analyzeInfo.LabelInfos)
    {
    	var imageData = drawer.Draw(labelInfo.ZplElements);
    	// imageData is bytes of png image
    }
  3. Supported Label Elements in BinaryKits.Zpl.Viewer

    develop

    The viewer supports various ZPL elements for rendering:

    Text Elements

    • Text Field (^FD with ^A or ^CF)
    • Field Block (^FB) - Multi-line text with justification
    • Field Typeset (^FT) - Typeset field positioning
    • Scalable/Bitmapped Font (^A, ^CF)
    • Change International Font (^CI)
    • Hexadecimal Indicator (^FH)
    • Field Reverse Print (^FR)
    • Field Number (^FN) - Variable field for templates
    • Recall Field Number

    Graphic Elements

    • Graphic Box (^GB) - Rectangle with optional fill
    • Graphic Circle (^GC)
    • Graphic Field (^GF) - Raster graphics
    • Image Move (^IM) - Recall stored image
    • Recall Graphic (^XG) - Recall stored graphic with scaling

    Positioning & Layout

    • Field Origin (^FO) - Set field position
    • Field Separator (^FS)
    • Field Orientation (^FW) - Rotate fields
    • Label Home (^LH) - Set label home position
    • Label Reverse Print (^LR) - Reverse entire label

    Storage & Templates

    • Download Graphics (~DG) - Store graphic to memory
    • Download Objects (~DY) - Store objects/fonts to memory
    • Download Format (^DF) - Store label template
    • Recall Format (^XF) - Recall label template

    Control Elements

    • Comment (^FX)
    • Barcode Field Default (^BY) - Set barcode module width
  4. Generate Interleaved 2 of 5 barcodes with Interleaved2Of5BarCodeCommand

    develop

    The Interleaved2Of5BarCodeCommand class generates the ^B2 ZPL command, which produces an Interleaved 2 of 5 barcode. This is a high-density, self-checking, continuous, numeric symbology.

    Parameters

    ParameterTypeDefaultDescription
    orientationOrientationOrientation.NormalThe orientation of the barcode.
    barCodeHeightint?nullThe height of the barcode (valid range: 1 to 32000).
    printInterpretationLinebooltrueWhether to print an interpretation line (the human-readable text below/above the code).
    printInterpretationLineAboveCodeboolfalseIf true, the interpretation line is printed above the barcode instead of below.
    calculateAndPrintMod10CheckDigitboolfalseWhether to calculate and print a Mod 10 check digit.

    Usage

    To generate the ZPL string, call the ToZpl() method on an instance of the command.

    var command = new Interleaved2Of5BarCodeCommand(
        orientation: Orientation.Normal,
        barCodeHeight: 100,
        printInterpretationLine: true,
        printInterpretationLineAboveCode: false,
        calculateAndPrintMod10CheckDigit: false
    );
    
    string zpl = command.ToZpl();
    // Output format: ^B2[orientation],[height],[printLine],[aboveCode],[mod10]
  5. Convert domain types to ZPL characters

    develop

    The CommandBase provides several protected and public utility methods to convert high-level domain types (enums) into the specific single-character codes used by the ZPL protocol. These are useful when implementing ToZpl():

    • Boolean: RenderBoolean(bool value) converts true to "Y" and false to "N".
    • Line Color: RenderLineColor(LineColor lineColor) converts to "B" (Black) or "W" (White).
    • Orientation: RenderOrientation(Orientation orientation) converts to "N" (Normal), "R" (Rotated90), "I" (Rotated180), or "B" (Rotated270).
    • Error Correction: RenderErrorCorrectionLevel(ErrorCorrectionLevel level) converts to "H" (UltraHigh), "Q" (High), "M" (Standard), or "L" (HighDensity).
    • Text Justification: RenderTextJustification(TextJustification justification) converts to "L" (Left), "C" (Center), "R" (Right), or "J" (Justified).
  6. Implement a custom ZPL command by extending CommandBase

    develop

    To create a new ZPL command, you must inherit from the CommandBase abstract class. You are required to implement two primary methods:

    1. ToZpl(): Returns the string representation of the command in ZPL format.
    2. ParseCommand(string zplCommand): Logic to parse an existing ZPL command string back into the object's properties.

    When initializing the base class, you must provide a commandPrefix (e.g., the specific ZPL command identifier like ^A or ^B).

    public class MyCustomCommand : CommandBase
    {
        public MyCustomCommand(string commandPrefix) : base(commandPrefix) { }
    
        public override string ToZpl()
        {
            // Return the formatted ZPL string
            return $"{CommandPrefix}DATA...";
        }
    
        public override void ParseCommand(string zplCommand)
        {
            // Implement parsing logic here
        }
    }
  7. Parse ZPL characters back to domain types

    develop

    When implementing ParseCommand, use the following helper methods to convert ZPL character codes back into usable C# types:

    • ConvertBoolean(string value): Returns true for "Y", false for "N" (defaults to false).
    • ConvertOrientation(string orientation): Returns Orientation enum (defaults to Orientation.Normal).
    • ConvertErrorCorrectionLevel(string errorCorrectionLevel): Returns ErrorCorrectionLevel enum (defaults to ErrorCorrectionLevel.HighReliability).
  8. Use the ~DY command to download objects

    develop

    The ~DY command is used to download graphic objects or fonts to the printer in any supported format. It is the preferred command for downloading TrueType fonts on printers with firmware version X.13 or later, as it is faster than ~DU and offers more saving/loading options than ~DG. It also supports downloading wireless certificate files.

    In the BinaryKits.Zpl.Protocol library, you can use the DownloadObjectsCommand class to construct this command programmatically.

    var command = new DownloadObjectsCommand(
        "R:",               // storageDevice
        "MYFONT",            // fileName
        'A',                 // formatDownloadedInDataField
        ".TTF",             // extensionOfStoredFile
        1024,                // totalNumberOfBytesInFile
        256,                 // totalNumberOfBytesPerRow
        "DATA_STRING"
    );
    
    string zpl = command.ToZpl();
  9. Change the default alphanumeric font with ChangeAlphanumericDefaultFontCommand

    develop

    The ChangeAlphanumericDefaultFontCommand (ZPL ^CF command) sets the default font used by the printer. This is useful for simplifying ZPL programs by establishing a baseline font for text elements.

    Parameters

    • specifiedDefaultFont (char): The character representing the specified default font.
    • individualCharacterHeight (int?, optional): The height of individual characters. Valid range is 0 to 32000.
    • individualCharacterWidth (int?, optional): The width of individual characters. Valid range is 0 to 32000.

    Usage

    When calling the constructor, you can provide the font and optional dimensions. The ToZpl() method will generate the formatted ^CF command string.

    // Example: Set default font to 'A' with height 30 and width 40
    var command = new ChangeAlphanumericDefaultFontCommand('A', 30, 40);
    string zpl = command.ToZpl(); // Returns "^CFA,30,40"
  10. Set the label home position with LabelHomeCommand

    develop

    The LabelHomeCommand (ZPL ^LH command) sets the label home position, which serves as the axis reference point for all subsequent printing. By default, the home position is the upper-left corner (0,0).

    Use this command to adjust the reference point, which is particularly useful when working with preprinted labels to ensure the print area starts below the preprinted section.

    Important: This command only affects fields that appear after it in the ZPL stream. It is recommended to place ^LH near the beginning of your label format.

    // Example: Setting the home position to X=10, Y=20
    var labelHome = new LabelHomeCommand(x: 10, y: 20);
    string zpl = labelHome.ToZpl(); // Returns "^LH10,20"