In this article, we will learn how to generate a QR code in C#.
QR code (stands for Quick Response code) is the trademark for a type of matrix barcode and a Barcode is a method of representing data in a visual, machine-readable form.
The Zen.Barcode.Rendering.Framework is a .NET library for generating Barcodes. Extremely fast, flexible, and easy to use.
Install Zen Barcode Rendering Framework, to install this you need to execute below command in Package Manager Console or find Zen.Barcode.Rendering.Framework in Nuget-Solution.
Package Manager Console
PM> Install-Package Zen.Barcode.Rendering.Framework
.NET CLI Console
> dotnet add package Zen.Barcode.Rendering.Framework
Also, we must have to install System.Drawing.Common package to generate a barcode as an Image.
Package Manager Console
PM> Install-Package System.Drawing.Common
.NET CLI Console
> dotnet add package System.Drawing.Common
Generating a QR Code
Firstly we design a form with some input fields for accepting data to generate barcode.
Open the Index.cshtml file and add the code in it.
<form method="post" class="form-inline"> <input class="form-control mr-2" name="txtQRCode" required /> <button class="btn btn-primary">GENERATE</button> </form> <br /> <img src="@ViewBag.QRCodeImage" />
Open the HomeController.cs file and add the code in it.
using Microsoft.AspNetCore.Mvc; using System; using System.Drawing.Imaging; using System.IO; using Zen.Barcode; namespace Generate_QRCode.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } [HttpPost] public ActionResult Index(string txtQRCode) { if (!string.IsNullOrEmpty(txtQRCode)) { var qrCodeImage = BarcodeDrawFactory.CodeQr.Draw(txtQRCode, 50); using (MemoryStream memoryStream = new MemoryStream()) { qrCodeImage.Save(memoryStream, ImageFormat.Png); ViewBag.QRCodeImage = "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray()); } } return View(); } } }
Output:
Please give your valuable feedback and if you have any questions or issues about this article, please let me know.
Also, check How To Generate Barcode In C#