Easy QR Code Creation in ASP.NET MVC

Today I was rebuilding a URL shortener site I wrote in ASP.NET Web Forms 4 years ago (as usual, I hated all of my old code). One part of the site is QR Code generation. I was using a (paid) library and it generated gif files that were stored on the server.

As part of the rewrite, I moved to ASP.NET MVC and I wanted the QR Code generation to be easy. How easy? In the end, when I need a QR code, all it takes is this:

@Html.GenerateQrCode(someUrlString)

Here's how to make it happen. This example uses Data URIs to directly embed the image (I picked up some pointers and from this post). Nothing is saved to the server. In my next post, I cover an alternative way to generate a QR code using a vanilla img tag -- good for building QR codes on the fly, like in an Angular.js repeater or something, where this solution wouldn't work.

If you've read my previous post, The Easiest Ways To Fail at QR Codes, you'll know I'm not a QR code evangelist... but hey, sometimes they have their purpose.

Step 1. Install the ZXing.Net Nuget Package

This does most of the hard work. Ok, it does pretty much all of the hard work. Just go to your package manager console and install it:

PM> Install-Package ZXing.Net

Step 2. Make a custom helper to generate your QR code.

I added a subfolder to my project called Helpers, and then inside that added a class called QRHelper.cs.

using System;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using ZXing;
using ZXing.Common;

namespace YourSite.Helpers
{
    public static class QRHelper
    {
        public static IHtmlString GenerateQrCode(this HtmlHelper html, string url, string alt = "QR code", int height = 500, int width = 500, 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(url))
            {
                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));
                }
            }
        }
    }
}

Step 3. Use the Helper

At the top of the chstml file, I added a reference to the custom helper:

@using YourSite.Helpers

And then

@Html.GenerateQrCode(Model.urlForQR)
or simply
@Html.GenerateQrCode("http://www.mikesmithdev.com")

That's it! You can now easily generate and embed QR Codes in your site. Much better than managing QR image files on your server. Next up, how to do the same from the client-side using an img tag.