Tuesday 19 September 2017

QR code generation in C# and CShtml

Libraries Required.

Install these packages into project file or service file using NuGet Package manager.
using System;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using ZXing;
using ZXing.Common;
//Helper class file for generate QR code
namespace QRHelper
{
    public static class QRHelper
    {
        public static IHtmlString GenerateQrCode(this HtmlHelper html, string Content, string alt = "QR code", int height = 150, int width = 150, int margin = 0)
        {
            var qrWriter = new BarcodeWriter();
            qrWriter.Format = BarcodeFormat.QR_CODE;
            qrWriter.Options = new EncodingOptions() { Height = height, Width = width, Margin = margin };

            using (var q = qrWriter.Write(Content))
            {
                using (var ms = new MemoryStream())
                {
                    q.Save(ms, ImageFormat.Png);
                    var img = new TagBuilder("img");
                    img.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
                    img.Attributes.Add("alt", alt);
                    return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
                }
            }
        }

        public static IHtmlString GenerateQrCode(string Content, string alt = "QR code", int height = 150, int width = 150, int margin = 0)
        {
            var qrWriter = new BarcodeWriter();
            qrWriter.Format = BarcodeFormat.QR_CODE;
            qrWriter.Options = new EncodingOptions() { Height = height, Width = width, Margin = margin };

            using (var q = qrWriter.Write(Content))
            {
                using (var ms = new MemoryStream())
                {
                    q.Save(ms, ImageFormat.Png);
                    var img = new TagBuilder("img");
                    img.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
                    img.Attributes.Add("alt", alt);
                    return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
                }
            }
        }
    }
}
----------------------------------------------View Part(CShtml page)--------------------------------------------
@using QRHelper

 <!--Directly call from Html elements it will call first function-->
@Html.GenerateQrCode("{\"BookingID\":\"2541-12454-0154-545121855\"}", "QR code", 150, 150)<span>QR Code</span>

---------------------------------------------Call from controller--------------------------------------------
using System.Web;
 public class HomeController : Controller
    {
              public ActionResult Index()
        {
//It will second method in helper class
IHtmlString  _qrCode=
GenerateQrCode("Your text here", "QR code", 150, 150);
        }
}

No comments:

Post a Comment