Tuesday, October 30, 2012

asp.net Using WebHandler to generate images on Server Side and send to Client




I had to create dynamic 2D Data Matrix bar code images on the server and send to the client for MeadCo printing.  Found out you can do this by using Web Handlers. 

This is a simple example, the value of the bar code is hardcoded.  Since you can pass query strings from the client to the handler, there is the possibility of creating dynamic barcodes.  This I will be doing using this prototype as a framework.   




WebHandler:

<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;
using System.IO;
using System.Drawing;

public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {

        //NOTE:  You can get parameters from the client using Query Strings
        
        IEC16022Sharp.DataMatrix dm = new IEC16022Sharp.DataMatrix("<00007>");


        context.Response.ContentType = "image/bmp";
        

        using (Bitmap image = dm.Image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                ms.WriteTo(context.Response.OutputStream);
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}


Client code:
The code below shows embedded html being generated (This is used for printing).  The option is there just to place an img element within the html document and set it’s src attribute to the name of your handler.




No comments: