Click here to Skip to main content
Click here to Skip to main content

Tagged as

Print a Label to Zebra Printer from ASP.NET

, 12 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Print a label to Zebra printer from ASP.NET

Introduction

In this tip, we shall see how ASP.NET can print a label to Zebra printer using itextsharp.dll.

Background

My job involves printing texts and images on Zebra labels. So I create a C# application using RawPrinterHelper class from Microsoft to produce labels.

It works for me from time to time but when new requests demand to print labels from web page, I have absolutely no idea how it could work.
So I Googled again but no luck, there is no such an example to do so, only component of Neodynamic.SDK.ThermalLabel.dll version 5.0 can do it, but the price is not cheap at all.
Some guys suggested that I use itextsharp.dll and after a week I found the solution to print label on Zebra printer via web page. So I am posting here in the hope that somebody might be interested.

Understand How Web Page Prints

In order to print a web page, client browser will output all render tags of current page to printer. If you can create a portion of page with texts and images small enough to fix on Zebra label, then you can print it on Zebra label. It does not require any kind of Zebra languages as EPL or ZPL.

So the idea is to render a small web page to fix its content on Zebra label and I will use itextsharp.dll to create a PDF page having a tool bar which can be embedded into a web control as asp:Literal and print this page to Zebra printer via PDF tool bar.

Using the Code

The attached code is built using C# 2008. It has C# syntax.

Let's break it down.

We will create a web page to hold PDF tag.

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Test.aspx.cs" Inherits="Test" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="frequest" runat="server">
        <table border="0">
            <tr>
                <td>
                    <div id="pdf" style="height:600px; overflow:auto">
                        <asp:Literal ID="pdfViewer" runat="server" ></asp:Literal>
                    </div>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Code behind:

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        pdfViewer.Text = CreatePdfTag("LabelGen.ashx?dpi=203");
    }
    private string CreatePdfTag(string pdfUrl)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<object type=\"application/pdf\" ");
        sb.Append("data=\"" + pdfUrl + "\" width=\"400px\" height=\"600px\" ");
        sb.Append("</object>");
        return sb.ToString();
    }
}

Create a label page by using itextsharp.dll:

I use generic handle to create a PDF page, but you can have any kind of page as web page or web control. All information in this page has been made up for an example, you can replace it with your own data.
In this example, I use default DPI of 203 (dot per inch) to scale image into 72 pixels. In addition, the barcode I chose is Codebar, but you can use any kind of barcodes.

<%@ WebHandler Language="C#" Class="LabelGen" %>
using System;
using System.Web;
using System.Threading;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class LabelGen : IHttpHandler
{
    byte[] buffer = null;
    float dpi = 203;
    //give this page with dummy database
    string strXml = "<root><data Contact="Contact name"
    Department="Department name" Company="Company name"
    Address1="Address1" Address2="Address2"<br />
                     Address3="Address3" City="City name"
                     State="State name" Country="Country name"
                     Postcode="Post code client" Phone="Phone No client" <br />
                     Email="Email client" Pieces="3" Val="100"
                     Weight="5.20" Inst="Instructions for this shipment." /> </root>";
    public void ProcessRequest (HttpContext context) {
        try
        {
            dpi = float.Parse(context.Request["dpi"]);
        }
        catch { }
        CreateThermal();
        context.Response.ContentType = "application/pdf";
        context.Response.BufferOutput = true;
        context.Response.BinaryWrite(buffer);
        context.Response.Flush();
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
    private void CreateThermal()
    {
        Thread thread = new Thread(new ThreadStart(CreateThermalLabel));
        thread.SetApartmentState(ApartmentState.STA);
        thread.Name = "CreateThermalLabel";
        thread.Start();
        thread.Join();
    }
    private void CreateThermalLabel()
    {
        XDocument doc = XDocument.Parse(strXml);
        XElement ele = doc.Root.Element("data");
        Document document = new Document
        (new iTextSharp.text.Rectangle(288f, 432f));//iTextSharp uses 72 pixels per inch
        //using memory to hold a binary data
        MemoryStream m = new MemoryStream();
        PdfWriter pdfWriter = PdfWriter.GetInstance(document, m);
        pdfWriter.CloseStream = false;
        document.Open();
        PdfContentByte cb = pdfWriter.DirectContent;
        for (int i = 1; i <= Convert.ToInt32(ele.Attribute("Pieces").Value); i++)
        {
            int hold;
            int y = 370;
            iTextSharp.text.Image logo =
            iTextSharp.text.Image.GetInstance("http://yourdomain/images/yourlogo.gif");
            logo.SetAbsolutePosition(5, y);
            // scale image to match its dpi
            float scale = 72 * 100 / dpi;
            logo.ScalePercent(scale);
            cb.AddImage(logo);
            y -= 70;
            iTextSharp.text.Image barcode =
            iTextSharp.text.Image.GetInstance(Barcode("99999999999"));
            barcode.SetAbsolutePosition(59, y);
            cb.AddImage(barcode);
            BaseFont font1 = BaseFont.CreateFont
            (BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            BaseFont font = BaseFont.CreateFont
            (BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            cb.BeginText();
            cb.SetFontAndSize(font, 10);
            hold = y;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Contact", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Department", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Company", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Address", 10, y, 0); y -= 3 * 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "City", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "State", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Country", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Post code", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Phone No", 10, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Email", 10, y, 0); y -= 25;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Type", 10, y, 0);
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Value", 180, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Pieces", 10, y, 0);
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Weight", 180, y, 0);
            cb.SetFontAndSize(font1, 10); y = hold;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Contact").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Department").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Company").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Address1").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Address2").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Address3").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("City").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("State").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Country").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Postcode").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Phone").Value, 65, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Email").Value, 65, y, 0);
            cb.MoveTo(10, y - 10);
            cb.LineTo(278, y - 10);
            cb.Stroke();
            hold = y - 10;
            y -= 25;
            cb.ShowTextAligned(Element.ALIGN_LEFT, "Non-commercial", 45, y, 0);
            cb.ShowTextAligned(Element.ALIGN_LEFT, "GBP " + ele.Attribute("Val").Value, 225, y, 0); y -= 15;
            cb.ShowTextAligned(Element.ALIGN_LEFT, i.ToString(), 45, y, 0);
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Weight").Value + " Kgs", 225, y, 0);
            cb.MoveTo(10, y - 10);
            cb.LineTo(278, y - 10);
            cb.MoveTo(150, hold);
            cb.LineTo(150, y - 10);
            cb.Stroke();
            y -= 25;
            cb.ShowTextAligned(Element.ALIGN_LEFT, ele.Attribute("Inst").Value, 10, y, 0);
            cb.EndText();
            document.NewPage();
        }
        document.Close();
        m.Position = 0;
        buffer = m.ToArray();
        m.Close();
    }
    byte[] Barcode(string barcodenumber)
    {
        Bitmap bmp = DrawLinearbarcode(barcodenumber);
        MemoryStream ms = new MemoryStream();
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        byte[] ImageBytes = ms.GetBuffer();
        return ImageBytes;
    }
    Bitmap DrawLinearbarcode(string barcodenumber)
    {
        Bitmap codeBitmap = new Bitmap(340, 70, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage(codeBitmap);
        g.Clear(System.Drawing.Color.White);
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
        g.PageUnit = GraphicsUnit.Pixel;
        SolidBrush brush = new SolidBrush(System.Drawing.Color.Black);
        int barheight = 35;
        int leftposition = 10;
        int topposition = 5;
        int narrowbarwidth = 1;
        string encodebinarystr = CodabarEncoding(barcodenumber);
        for (int i = 0; i < encodebinarystr.Length; i++)
        {
            if (encodebinarystr[i] == '1') g.FillRectangle
            (brush, leftposition, topposition, narrowbarwidth, barheight);
            leftposition += narrowbarwidth;
        }
        brush.Dispose();
        g.Dispose();
        return codeBitmap;
    }
    //this example I will use codebar
    string CodabarEncoding(string barcodenumber)
    {
        string CodabarIndex = "0123456789$-./:+ABCD";
        string[] CodabarMapTable = new string[20]
        { "nnnnnwwn", "nnnnwwnn", "nnnwnnwn", "wwnnnnnn", "nnwnnwnn",
        "wnnnnwnn", "nwnnnnwn", "nwnnwnnn", "nwwnnnnn", "wnnwnnnn",
        "nnwwnnnn", "nnnwwnnn", "wnwnwnnn", "wnwnnnwn", "wnnnwnwn",
        "nnwwwwwn", "nnwwnwnn", "nwnwnnwn", "nnnwnwwn", "nnnwwwnn" };
        string result = "";
        string controlandbarcode = 'A' + barcodenumber + 'B';
        for (int i = 0; i < controlandbarcode.Length; i++)
            result += codeTobinary(CodabarMapTable[CodabarIndex.IndexOf(controlandbarcode[i])]);
        return result;
    }
    string codeTobinary(string strmap)
    {
        int ratio = 3;
        string ret = "";
        strmap = strmap.ToLower();
        for (int i = 0; i < strmap.Length; i++)
        {
            if (((i + 1) % 2) != 0)
            {
                if (strmap[i] == 'n')
                {
                    ret +=  "1";
                }
                else if (strmap[i] == 'w')
                {
                    for (int num2 = 0; num2 < ratio; num2++)
                    {
                        ret +=  '1';
                    }
                }
            }
            else if (strmap[i] == 'n')
            {
                ret +=  "0";
            }
            else if (strmap[i] == 'w')
            {
                for (int num3 = 0; num3 < ratio; num3++)
                {
                    ret += '0';
                }
            }
        }
        return ret;
    }
}

Points of Interest

What we want to know in this article is to understand how to render a PDF page in a kind of binary array. It is useful not just for this example, but we can use this logic for anything else.

History

  • 11th August, 2014: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Martin Ton
Software Developer (Senior)
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
QuestionError in CreateThermalLabel function PinmemberMadchen193-Oct-14 8:56 
AnswerRe: Error in CreateThermalLabel function PinmemberMartin Ton6-Oct-14 5:26 
QuestionOne request PinmemberTridip Bhattacharjee12-Aug-14 22:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411023.1 | Last Updated 12 Aug 2014
Article Copyright 2014 by Martin Ton
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid