Razor Barcode Generator (Code Example Tutorial)

A barcode is a method of encoding data in a visual, machine-readable format. The most common type of barcode is the one-dimensional (1D) barcode, which is a series of parallel lines of varying widths and spacings. One-dimensional barcodes are used in a wide variety of applications, including retail, healthcare, and manufacturing.

A Razor barcode generator is a tool that is used to create and print 1D barcodes. These generators typically consist of software and a barcode printer, and are designed to be used in a wide variety of settings, including retail stores, warehouses, and manufacturing facilities.

One of the main advantages of using a Razor barcode generator is that it allows for the efficient and accurate tracking of products and inventory. By attaching a barcode to each item, businesses can quickly and easily scan and track the movement of products throughout their supply chain. This can help to reduce costs associated with lost or misplaced items, and can also help to improve the overall efficiency and profitability of a business.

IronBarcode C# Library

IronBarcode is a barcode generator library that is compatible with the Razor Framework, a web development platform for ASP.NET Core. It generates barcode images within Visual Studio using the .NET Core framework. The package can be installed through the NuGet Package Manager and offers support for various barcode formats, including QR code, as well as the option to use custom barcode fonts. It also includes an example of how to use the library in an ASP.NET Core project, complete with an action method in a controller and a button to generate the barcode. The generated barcode can be displayed in the HTML output, saved to a file, or printed. Additionally, the library supports adjustable parameters such as width and error correction level, and can be easily incorporated into existing projects by referencing and following the provided documentation.

Here's an example of how to use IronBarcode to generate a QR code:

using IronBarCode; 
var qr = new IronBarCode.Barcode("Hello World!"); 
qr.SaveImage("qr-code.png");
using IronBarCode; 
var qr = new IronBarCode.Barcode("Hello World!"); 
qr.SaveImage("qr-code.png");
Imports IronBarCode
Private qr = New IronBarCode.Barcode("Hello World!")
qr.SaveImage("qr-code.png")
VB   C#

This example creates a new barcode object with the message "Hello World!" and saves it as a PNG image with the filename "qr-code.png".

IronBarcode also provides a variety of options for customizing the appearance of the barcode such as color, rotation, and size. Also, it can generate barcodes with different types like Code128, Code39, and many more. The library provides detailed documentation that explains all the available options and how to use them.

Why Choose IronBarcode?

IronBarcode is a great option for several reasons.

First, IronBarcode is fully compatible with the .NET Core Framework, making it easy to integrate into a Razor web application using Visual Studio. This allows developers to easily create barcode images and display them on their web pages.

Second, IronBarcode offers a wide range of barcode formats and encoding options, making it a versatile tool for generating barcodes in any project. This includes popular formats such as QR codes and support for customizing the font of the barcode text.

Third, IronBarcode provides a user-friendly NuGet Package Manager, making it easy for developers to install and update the library. This allows developers to quickly and easily get started with barcode generation in their projects.

Fourth, IronBarcode has detailed documentation and examples for developers to easily understand and implement the library in their projects. This helps developers to avoid errors and implement the library in a smooth way.

Finally, IronBarcode is a lightweight library that offers high-quality barcode images with minimal resources, making it an efficient option for generating barcodes in web applications.

Overall, IronBarcode is a reliable and efficient option for creating and displaying barcodes in a Razor web application. Its compatibility with the .NET Core framework, wide range of barcode formats, user-friendly Nuget package manager, detailed documentation, and efficient use of resources make it a great choice for developers.

Set Up and Configure IronBarcode within a Razor Project

Prerequisites

For creating barcode-generated files in Razor Pages, there are some prerequisites.

  1. Visual Studio 2022 (Latest Version)
  2. .NET Framework 6 or 7
  3. .NET Core Web Application in Visual Studio

Install the IronBarcode Library

Before we begin, we need to install the Barcode NuGet Package. You can install it by using one of the following three methods:

Package Manager Console

Write the following command in the Package Manager console. It will download and install the package for you.

Install-Package Barcode
Razor Barcode Generator - Figure 1: Install IronBarcode with the Package Manager Console

Installing IronBarcode via the NuGet Package Manager Console

NuGet Package Manager Solution

  1. Open Visual Studio and create a new ASP.NET Core Web Application project using the Razor Framework.
  2. In the Solution Explorer, right-click on the project and select "Manage NuGet Packages."
  3. In the NuGet Package Manager, search for "IronBarcode" and click on the "Install" button to add the package to your project.
Razor Barcode Generator - Figure 2: Install IronBarcode with Visual Studio's NuGet Package Manager UI

Installing IronBarcode Via the NuGet Package Manager UI in Visual Studio

Code for Generating Razor Pages in C#

  1. In the "Controllers" folder, add a new class file named "HomeController" and add the following code to the class:

    using IronBarcode; 
    using System.IO; 
    public class HomeController : Controller { 
        public IActionResult Generate() { 
            var barcode = new Barcode("IronBarcode"); 
            var image = barcode.ToImage(); 
            return File(image, "image/png"); 
        } 
    }
    using IronBarcode; 
    using System.IO; 
    public class HomeController : Controller { 
        public IActionResult Generate() { 
            var barcode = new Barcode("IronBarcode"); 
            var image = barcode.ToImage(); 
            return File(image, "image/png"); 
        } 
    }
    Imports IronBarcode
    Imports System.IO
    Public Class HomeController
    	Inherits Controller
    
    	Public Function Generate() As IActionResult
    		Dim barcode As New Barcode("IronBarcode")
    		Dim image = barcode.ToImage()
    		Return File(image, "image/png")
    	End Function
    End Class
    VB   C#
  2. In the "Views" folder, add a new Razor page named "Index" and add the following code to the page:

    <form method="post"> <button class="btn btn-primary" type="submit">Generate</button> </form>
    <form method="post"> <button class="btn btn-primary" type="submit">Generate</button> </form>
    HTML
  3. In the "Startup" class, in the "Configure" method, add the following line of code to map the "Index" page to the root URL:

    app.UseEndpoints(
        endpoints => 
        { 
            endpoints.MapControllerRoute( 
            name: "default", 
            pattern: "{controller=Home}/{action=Index}/{id?}"); 
        }
    );
    app.UseEndpoints(
        endpoints => 
        { 
            endpoints.MapControllerRoute( 
            name: "default", 
            pattern: "{controller=Home}/{action=Index}/{id?}"); 
        }
    );
    app.UseEndpoints(Sub(endpoints)
    		endpoints.MapControllerRoute(name:= "default", pattern:= "{controller=Home}/{action=Index}/{id?}")
    End Sub)
    VB   C#
  4. Run the project. You should see a button labelled "Generate" on the home page. When you click the button, a barcode image will be generated and displayed on the page.

Note: the sample code above is generating a barcode with the text "IronBarcode" and will output it in PNG format. You can change the text, file, and image format by modifying the appropriate parameters in the Generate action method.

Additionally, you can also customize the width, error correction level and other properties of the barcode by using the properties provided by the IronBarcode library. You should also refer to the documentation for more information on how to use the library and the different options it provides.

Creating a New Barcode Object

The IronBarcode API provides a simple and easy-to-use interface for creating and configuring barcode objects.

The following is an example of how to create a new barcode object and configure it with desired settings:

  1. First, create a new instance of the Barcode class with the desired text to be encoded in the barcode. For example:

    var barcode = new Barcode("IronBarcode");
    var barcode = new Barcode("IronBarcode");
    Dim barcode As New Barcode("IronBarcode")
    VB   C#
  2. To configure the barcode with desired settings, you can use the properties included in the new Barcode object. For example, to change the barcode format to QR Code, you can set the BarcodeType property as follows:

    barcode.BarcodeType = BarcodeType.QR;
    barcode.BarcodeType = BarcodeType.QR;
    barcode.BarcodeType = BarcodeType.QR
    VB   C#
  3. You can also customize the width, height and error correction level of the barcode by using the Width, Height and ErrorCorrectionLevel properties. For example, to set the width of the barcode to 200 pixels, you can set the Width property as follows:

    barcode.Width = 200;
    barcode.Width = 200;
    barcode.Width = 200
    VB   C#
  4. To change the font of the barcode text, you can use the TextFont property. For example, you can set the text font to Arial:

    barcode.TextFont = new System.Drawing.Font("Arial", 10);
    barcode.TextFont = new System.Drawing.Font("Arial", 10);
    barcode.TextFont = New System.Drawing.Font("Arial", 10)
    VB   C#

When using the above code, you need to make sure that the IronBarcode package is correctly installed and referenced in your project.

Saving or Displaying the Generated Barcode Image

  1. Once the barcode object is configured with the desired settings, you can generate the barcode image by calling the Encode method. For example:

    var barcodeImage = barcode.Encode();
    var barcodeImage = barcode.Encode();
    Dim barcodeImage = barcode.Encode()
    VB   C#
  2. The Encode method returns a System.Drawing.Bitmap object, which can then be saved to a file, displayed on a web page, or printed. For example, to save the barcode image to a file, you can use the following code:

    barcodeImage.Save("barcode.png", System.Drawing.Imaging.ImageFormat.Png);
    barcodeImage.Save("barcode.png", System.Drawing.Imaging.ImageFormat.Png);
    barcodeImage.Save("barcode.png", System.Drawing.Imaging.ImageFormat.Png)
    VB   C#
    Razor Barcode Generator - Figure 3: The result of calling QrCodeWriter.createQrCode using the aforementioned parameters.

    The result of calling QrCodeWriter.createQrCode using the aforementioned parameters.

  3. To display the barcode image on a web page using Razor, you can use the following code in your Razor view:

    <img src="@Url.Content("~/barcode.png")" alt="Barcode" />
    <img src="@Url.Content("~/barcode.png")" alt="Barcode" />
    HTML
    Razor Barcode Generator - Figure 4: A Razor Barcode Generator Interface

    A Razor Barcode Generator Interface

  4. You can also display the barcode image in your Razor view by converting the bitmap image to a byte array and then converting it to a base64 string.

    using (var ms = new MemoryStream()) { 
        barcodeImage.Save(ms, ImageFormat.Png); 
        var imageBytes = ms.ToArray(); 
        var base64String = Convert.ToBase64String(imageBytes); 
        <img src="data:image/png;base64,@base64String" alt="Barcode" /> 
    }
    using (var ms = new MemoryStream()) { 
        barcodeImage.Save(ms, ImageFormat.Png); 
        var imageBytes = ms.ToArray(); 
        var base64String = Convert.ToBase64String(imageBytes); 
        <img src="data:image/png;base64,@base64String" alt="Barcode" /> 
    }
    Using ms = New MemoryStream()
    	barcodeImage.Save(ms, ImageFormat.Png)
    	Dim imageBytes = ms.ToArray()
    	Dim base64String = Convert.ToBase64String(imageBytes)
    'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
    'ORIGINAL LINE: <img src="data:image/png;base64,@base64String" alt="Barcode" />
    	"data:image/png;base64,@base64String" alt="Barcode" />
    	<img src="data:image/png;base64,@base64String" alt
    End Using
    VB   C#

Note: The GetImage and Save methods of the Barcode class will handle the conversion of the barcode to the specified format. If you don't specify a format, it will save the barcode in PNG format by default.

Also, for a more professional look, you can consider using CSS and JavaScript to customize the appearance of the barcode on the web page.

Razor Barcode Generator - Figure 5: Output of the Razor Barcode Generator

The output that the Razor Barcode Generator displays post generation

Razor Barcode Generator - Figure 6: C# Create QR Code With Logo Image

IronBarcode can also create QR Codes in C#, similar to the one shown above.

Tips and Best Practices

IronBarcode is a powerful tool for generating and displaying barcodes in a Razor web application. By using the IronBarcode library, developers can easily create barcode images and display them on their web pages.

We will discuss some tips and best practices for integrating IronBarcode into a Razor web application using Visual Studio and the .NET Core Framework.

  1. Install the IronBarcode Nuget package: The first step in integrating IronBarcode into your project is to install the Nuget package. This can be done by searching for "IronBarcode" in the Nuget Package Manager and clicking the "Install" button.
  2. Create a new project: Open Visual Studio and create a new ASP.NET Core web project. This will be the foundation for your barcode generation application.
  3. Reference the IronBarcode library: Next, you will need to reference the IronBarcode library in your project. This can be done by adding the following line of code to the top of your project file:

    using IronBarcode;
    using IronBarcode;
    Imports IronBarcode
    VB   C#
  4. Create an action method: In your project, create a new public class called "HomeController". Inside this class, create a new action method called "GenerateBarcode". This method will be responsible for generating the barcode image, and reference the ironbarcode.dll

    Razor Barcode Generator - Figure 7: Inserting the IronBarcode DLL as a new COM reference in your project.

    Inserting the IronBarcode DLL as a new COM reference in your project.

  5. Add a barcode generator: In the GenerateBarcode method, create a new instance of the barcode generator. This can be done by using the following code:

    var barcode = new Barcode();
    var barcode = new Barcode();
    Dim barcode As New Barcode()
    VB   C#
  6. Set the barcode text: The next step is to set the text that will be encoded in the barcode. This can be done by using the following code:

    barcode.Text = "Enter your barcode text here";
    barcode.Text = "Enter your barcode text here";
    barcode.Text = "Enter your barcode text here"
    VB   C#
  7. Set the barcode format: You can choose the format of the barcode by using the following code:

    barcode.Format = BarcodeFormat.QR_CODE;
    barcode.Format = BarcodeFormat.QR_CODE;
    barcode.Format = BarcodeFormat.QR_CODE
    VB   C#
  8. Set the barcode font: You can also set the font of the barcode text by using the following code:

    barcode.Font = new Font("Arial", 12);
    barcode.Font = new Font("Arial", 12);
    barcode.Font = New Font("Arial", 12)
    VB   C#
  9. Generate the barcode image: Once you have set the text, format, and font, you can generate the barcode image by using the following code:

    var barcodeImage = barcode.Generate();
    var barcodeImage = barcode.Generate();
    Dim barcodeImage = barcode.Generate()
    VB   C#
  10. Display the barcode image: Finally, you can display the generated barcode image on your web page by using the following code:

    return File(barcodeImage, "image/png");
    return File(barcodeImage, "image/png");
    Return File(barcodeImage, "image/png")
    VB   C#
  11. Add a "Generate" button: To make it easy for users to generate barcodes, you can add a "Generate" button to your web page. This can be done by using the following code:

    <button class="btn btn-primary" type="submit">Generate</button>
    <button class="btn btn-primary" type="submit">Generate</button>
    HTML
    Razor Barcode Generator - Figure 8

    Follow the best practices listed above to integrate Barcode/QR Code functionality into your own Razor Web Applications!

By following these tips and best practices, developers can easily integrate IronBarcode into a Razor web application. With the IronBarcode library, developers can easily create barcode images and display them on their web pages. The library supports a wide range of barcode formats and encoding options, making it a versatile tool for generating barcodes in any project.

Conclusion

IronBarcode is a reliable and efficient option for creating and displaying barcodes in a Razor web application. Try using IronBarcode to generate barcode images in your next project!

IronXL is totally free tool for development. You can also get a 30-day free trial for testing in production. To find out more, check out the pricing plans.