USING IRONBARCODE

Creating a Razor Barcode Generator Web App

Published April 7, 2024
Share:

Razor Barcode Generator is a handy tool that simplifies the creation of barcodes for developers and businesses alike. Integrating barcode generation into web applications enhances the functionality and user experience, making it straightforward to produce a variety of barcode types. Whether you're managing inventory, tracking assets, or streamlining checkout processes, utilizing a Razor Barcode Generator can significantly improve efficiency and accuracy. We'll use IronBarcode in this tutorial for creating a barcode generator.

Introduction to IronBarcode

IronBarcode is an essential tool for developers working with .NET Core, offering an easy-to-use library for barcode generation and reading. It stands out because of its simplicity in integrating into your projects, requiring minimal code to produce or decipher barcodes and QR codes. This makes IronBarcode a versatile choice for enhancing applications with both barcode generation and barcode reading functionality, from web applications using Razor pages to desktop and mobile applications. Its broad range of supported barcode formats ensures that it can meet diverse project requirements, including those for .NET MVC, Blazor WebAssembly app, and Blazor App making it a reliable choice for developers.

Steps to Create a Barcode Generator

Step 1: Create ASP.NET Core Web app (Razor Pages)

We can choose the Blazor application or the Blazor server application for this project. But for this tutorial, I'll use ASP.NET Core Web App (Razor Pages). Creating an ASP.NET Core Web App with Razor Pages in Visual Studio involves a series of straightforward steps. This guide will help you set up your project from scratch:

Open Visual Studio: Start Visual Studio. On the start window, select "Create a new project" to begin the process of setting up your new web application.

Choose Project Type: In the "Create a new project" window, you'll need to select the project type. Type "Razor" into the search box to narrow down the options, and then select "ASP.NET Core Web App" from the list of project templates. After selecting it, click the "Next" button to proceed.

Creating a new Razor project Configure Your Project: You'll now be prompted to configure your new project.

  • Enter a "Project Name" for your web application.
  • Choose a suitable "Location" on your computer where the project files will be stored.
  • Optionally, adjust the "Solution name" if you want it to be different from the project name.
  • Click "Next" to continue.

Configuring the project name, solution name, and file path

Set Up Project Details: In the "Additional Information" window, make sure to:

  • Select the appropriate version of .NET in the dropdown. For the latest features, select the highest available version.
  • Verify that "Configure for HTTPS" is checked to enable secure HTTP connections.
  • Click "Create" to initiate the creation of your new Razor Pages web application.

Setting additional information

Step 2: Install the IronBarcode Library

To install IronBarcode using the NuGet Package Manager in Visual Studio, follow these steps to seamlessly integrate it into your ASP.NET Core Web App or any other .NET project:

Access the NuGet Package Manager: Right-click on your project name in the Solution Explorer pane, which is typically on the right side of the Visual Studio interface. From the context menu that appears, select "Manage NuGet Packages…" This will open the NuGet Package Manager tab.

Search for IronBarcode: In the NuGet Package Manager tab, click on the "Browse" tab to search for packages online. In the search box, type "IronBarcode" to find the IronBarcode library.

Install IronBarcode: From the search results, locate the "IronBarCode" package. Make sure you select the correct package as there might be similarly named packages. Click on the "IronBarCode" package to select it, and then click on the "Install" button. Visual Studio may show a dialog box listing the changes that will be made, including any additional dependencies that will be installed along with IronBarcode. Review the changes and click "OK" or "Accept" to proceed with the installation. If any license agreements appear, review and accept them to continue.

Installing IronBarcode through the NuGet package manager

Step 3: Design UI

It's time to focus on the visual aspect of our web application. We'll start by enhancing the Index page. To do this, open the index.cshtml file in your project. This file is where the markup for the homepage resides. To make our page more visually appealing and user-friendly, we'll apply some custom styling.

CSS for designing: Insert the following CSS into the <head> section of your index.cshtml file or within a <style> tag if you're embedding it directly within the HTML:

<style>
    body {
        font-family: 'Poppins', sans-serif;
    }
    .container {
        padding-top: 30px;
        max-width: 900px;
    }
    .row.justify-content-center {
        margin-right: 0;
        margin-left: 0;
    }
    .text-center {
        text-align: center;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: bold;
    }
    .mb-4 {
        margin-bottom: 2rem;
    }
    .form-group {
        margin-bottom: 20px;
    }
    .btn-primary {
        background-color: #0056b3;
        border-color: #004b9b;
        padding: 10px 15px;
        border-radius: 5px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: background-color 0.3s, box-shadow 0.3s;
    }
        .btn-primary:hover {
            background-color: #004b9b;
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
    .btn-block {
        display: block;
        width: 100%;
    }
    .form-control {
        border: 1px solid #ced4da;
        border-radius: 4px;
        box-shadow: inset 0 1px 2px rgba(0,0,0,0.075);
        transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    }
        .form-control:focus {
            border-color: #80bdff;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
    label {
        color: #495057;
        font-weight: bold;
    }
    datalist option {
        background-color: white;
        color: black;
    }
    #message {
        display: block;
        margin-top: 20px;
        font-size: 1rem;
    }
    #messageContainer {
        text-align: center;
        padding: 10px;
        margin-top: 20px;
    }
    #imageContainer {
        text-align: center;
        padding: 10px;
        margin-top: 20px;
        display: none;
    }
    #barcodeImage {
        max-width: 100%;
        padding: 10px;
        height: auto;
        display: inline-block;
        margin: 0 auto;
    }
    .divider {
        border-right: 2px solid #dee2e6;
    }
    .divider {
        border-right: 2px solid #dee2e6;
        padding-right: 30px;
    }
    .image-padding {
        padding-left: 30px;
    }

    #fileName,
    #customDownloadBtn {
        height: calc(1.5em + .75rem + 2px);
    }

    #customDownloadBtn {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .row.mt-3 > div [class*="col-"] {
        padding-right: .15rem;
        padding-left: .15rem;
    }
    .pr-1 {
        padding-right: .5rem;
    }
    .pl-1 {
        padding-left: .5rem;
    }
    .svg-container {
        text-align: center;
    }
    .barcode-logo {
        width: 40%;
        height: auto;
        display: block;
        margin-left: auto;
        margin-right: auto;
    }
</style>
<style>
    body {
        font-family: 'Poppins', sans-serif;
    }
    .container {
        padding-top: 30px;
        max-width: 900px;
    }
    .row.justify-content-center {
        margin-right: 0;
        margin-left: 0;
    }
    .text-center {
        text-align: center;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: bold;
    }
    .mb-4 {
        margin-bottom: 2rem;
    }
    .form-group {
        margin-bottom: 20px;
    }
    .btn-primary {
        background-color: #0056b3;
        border-color: #004b9b;
        padding: 10px 15px;
        border-radius: 5px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: background-color 0.3s, box-shadow 0.3s;
    }
        .btn-primary:hover {
            background-color: #004b9b;
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
    .btn-block {
        display: block;
        width: 100%;
    }
    .form-control {
        border: 1px solid #ced4da;
        border-radius: 4px;
        box-shadow: inset 0 1px 2px rgba(0,0,0,0.075);
        transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    }
        .form-control:focus {
            border-color: #80bdff;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
    label {
        color: #495057;
        font-weight: bold;
    }
    datalist option {
        background-color: white;
        color: black;
    }
    #message {
        display: block;
        margin-top: 20px;
        font-size: 1rem;
    }
    #messageContainer {
        text-align: center;
        padding: 10px;
        margin-top: 20px;
    }
    #imageContainer {
        text-align: center;
        padding: 10px;
        margin-top: 20px;
        display: none;
    }
    #barcodeImage {
        max-width: 100%;
        padding: 10px;
        height: auto;
        display: inline-block;
        margin: 0 auto;
    }
    .divider {
        border-right: 2px solid #dee2e6;
    }
    .divider {
        border-right: 2px solid #dee2e6;
        padding-right: 30px;
    }
    .image-padding {
        padding-left: 30px;
    }

    #fileName,
    #customDownloadBtn {
        height: calc(1.5em + .75rem + 2px);
    }

    #customDownloadBtn {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .row.mt-3 > div [class*="col-"] {
        padding-right: .15rem;
        padding-left: .15rem;
    }
    .pr-1 {
        padding-right: .5rem;
    }
    .pl-1 {
        padding-left: .5rem;
    }
    .svg-container {
        text-align: center;
    }
    .barcode-logo {
        width: 40%;
        height: auto;
        display: block;
        margin-left: auto;
        margin-right: auto;
    }
</style>
HTML

This CSS code is designed to give the Index page a clean and modern look, using the 'Poppins' font for a sleek appearance and defining styles for containers, buttons, form controls, and more for a cohesive user interface. Feel free to customize these styles further to match the specific design requirements of your web application.

Adding a Welcome Message: To greet users and introduce the purpose of our application, we'll place a prominent welcome message on the page. We'll also adjust its color to match our design theme. We'll include a logo image centered on the page, just below the welcome message. Here is how you can do it:

<h1 class="text-center mb-4" style="color:#004b9b">Welcome to Barode Generator</h1>
<div class="svg-container text-center">
    <img src="~/images/logo.svg" class="barcode-logo" alt="Barcode" />
</div>
<h1 class="text-center mb-4" style="color:#004b9b">Welcome to Barode Generator</h1>
<div class="svg-container text-center">
    <img src="~/images/logo.svg" class="barcode-logo" alt="Barcode" />
</div>
HTML

To continue designing the user interface of your Barcode Generator, let's focus on structuring the main content within a centered layout. The following snippet demonstrates how to use Bootstrap's grid system to center content and prepare for further UI components, such as forms, buttons, or informational text areas.

<div class="container">

    <div class="row justify-content-center">

    </div>
</div>
<div class="container">

    <div class="row justify-content-center">

    </div>
</div>
HTML

Design Input form

Now, in the above structure, we'll design our form to get the input from the user to design their Barcode. We'll take the input of the following fields: Data for the barcode, Type of barcode, Max width, Max Height, and color of the barcode. Here is the code:

<div class="col-md-6 divider col-padding">
    <form method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="barcodeText">Data for Barcode</label>
            <input type="text" class="form-control" id="barcodeText" name="barcodeText" placeholder="Enter URL or text" required>
        </div>

        <div class="form-group">
            <label for="barcodeType">Type of Barcode</label>
            <input class="form-control" list="typeOptions" id="barcodeType" name="barcodeType" placeholder="Type to search...">
            <datalist id="typeOptions">
                @foreach (var type in Enum.GetNames(typeof(IndexModel.BarcodeTypes)))
                {
                    <option value="@type">@type</option>
                }
            </datalist>
        </div>

        <div class="row">
            <div class="form-group col-6">
                <label for="maxWidth">Max Width (px)</label>
                <input type="number" class="form-control" id="maxWidth" name="maxWidth" placeholder="e.g., 300" min="0">
            </div>
            <div class="form-group col-6">
                <label for="maxHeight">Max Height (px)</label>
                <input type="number" class="form-control" id="maxHeight" name="maxHeight" placeholder="e.g., 300" min="0">
            </div>
        </div>

        <div class="form-group">
            <label for="barcodeColor">Color for Barcode</label>
            <input class="form-control" list="colorOptions" id="barcodeColor" name="barcodeColor" placeholder="Type to search...">
            <datalist id="colorOptions">
                @foreach (var color in Enum.GetNames(typeof(IndexModel.BarcodeColors)))
                {
                    <option value="@color">@color</option>
                }
            </datalist>
        </div>

        <button type="submit" asp-page-handler="Upload" class="btn btn-primary btn-block">Generate  Barcode</button>
    </form>
    <div id="messageContainer">
        <span id="message" style="color:green;">@Html.Raw(Model.Message)</span>
    </div>
</div>
<div class="col-md-6 divider col-padding">
    <form method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="barcodeText">Data for Barcode</label>
            <input type="text" class="form-control" id="barcodeText" name="barcodeText" placeholder="Enter URL or text" required>
        </div>

        <div class="form-group">
            <label for="barcodeType">Type of Barcode</label>
            <input class="form-control" list="typeOptions" id="barcodeType" name="barcodeType" placeholder="Type to search...">
            <datalist id="typeOptions">
                @foreach (var type in Enum.GetNames(typeof(IndexModel.BarcodeTypes)))
                {
                    <option value="@type">@type</option>
                }
            </datalist>
        </div>

        <div class="row">
            <div class="form-group col-6">
                <label for="maxWidth">Max Width (px)</label>
                <input type="number" class="form-control" id="maxWidth" name="maxWidth" placeholder="e.g., 300" min="0">
            </div>
            <div class="form-group col-6">
                <label for="maxHeight">Max Height (px)</label>
                <input type="number" class="form-control" id="maxHeight" name="maxHeight" placeholder="e.g., 300" min="0">
            </div>
        </div>

        <div class="form-group">
            <label for="barcodeColor">Color for Barcode</label>
            <input class="form-control" list="colorOptions" id="barcodeColor" name="barcodeColor" placeholder="Type to search...">
            <datalist id="colorOptions">
                @foreach (var color in Enum.GetNames(typeof(IndexModel.BarcodeColors)))
                {
                    <option value="@color">@color</option>
                }
            </datalist>
        </div>

        <button type="submit" asp-page-handler="Upload" class="btn btn-primary btn-block">Generate  Barcode</button>
    </form>
    <div id="messageContainer">
        <span id="message" style="color:green;">@Html.Raw(Model.Message)</span>
    </div>
</div>
HTML

Here's a breakdown of what each part does in simpler terms:

The <div> container: This is like a box on the webpage that holds everything related to creating a barcode. It's half the width of its parent container because of the class col-md-6.

The <form> element: This is the part of the page where users input data. The method ="post" attribute means that when the form is submitted, the information is sent to the server in a way that others can't see. The enctype ="multipart/form-data" attribute allows the form to send files, which could be useful if you're uploading an image or file to generate a barcode.

Data for Barcode: This is a field where users can type the information they want to turn into a barcode, like a URL or some text. It's marked as required, so the form can't be submitted without filling this in.

Type of Barcode: Here, users can choose what kind of barcode they want to create. The choices come from an enumeration (a special list) defined in code not shown here. Users can type to search through the available options.

Max Width and Max Height: These fields let users specify the maximum size for the barcode in pixels. They prevent the barcode from being too big for the intended use.

Color for Barcode: Similar to the barcode type, users can pick a color for their barcode from a list defined in the code. This allows for customization of the barcode's appearance.

Generate Barcode button: After filling out the form, clicking this button sends the information to the server, where the barcode is created based on the provided details. The asp-page-handler attribute indicates a specific method in the server code that handles this action.

Message Container: This is where messages (like success or error messages) will appear after the form is submitted. These messages are set on the server side and displayed to the user to provide feedback on the action taken.

Image Column

Now it's time to create a column where the generated barcode will show and the download button will appear. The download button will help to download the generated button. There will be an input field where you can add the barcode name before downloading. Here is the code to implement this:

<!-- Image Column -->
<div class="col-md-6 image-padding">
    <div id="imageContainer">
        <img id="barcodeImage" src="" alt="Generated Barcode" />
        <div class="row mt-3">
            <div class="col-sm-8 pr-1">
                <input type="text" class="form-control" id="fileName" placeholder="Enter file name">
            </div>
            <div class="col-sm-4 pl-1">
                <button type="button" class="btn btn-primary btn-block" id="customDownloadBtn" style="height: 38px;">Download</button>
            </div>
        </div>
    </div>
</div>
<!-- Image Column -->
<div class="col-md-6 image-padding">
    <div id="imageContainer">
        <img id="barcodeImage" src="" alt="Generated Barcode" />
        <div class="row mt-3">
            <div class="col-sm-8 pr-1">
                <input type="text" class="form-control" id="fileName" placeholder="Enter file name">
            </div>
            <div class="col-sm-4 pl-1">
                <button type="button" class="btn btn-primary btn-block" id="customDownloadBtn" style="height: 38px;">Download</button>
            </div>
        </div>
    </div>
</div>
HTML

Image Column (col-md-6 image-padding): This div creates a column alongside the form column (if following a two-column layout). The image-padding class likely adds some padding around the column for spacing.

Image Container (imageContainer): This div is specifically for encapsulating the barcode image and related controls. Initially hidden, it's typically made visible via JavaScript once a barcode is generated.

Barcode Image (barcodeImage): An <img> tag is used to display the generated barcode. Initially, the src attribute is empty because the image source will be dynamically set after the barcode is generated. The alt attribute provides an alternative text description of the image.

File Name Input: Below the barcode image, there's an input field where users can enter a name for the file they wish to save the barcode image as. This is useful for personalizing the file before downloading.

Download Button: Accompanying the file name input is a button labeled "Download". This button is designed to trigger the download of the generated barcode image, using the file name provided by the user if specified.

Responsive Layout (row and column classes): The layout uses Bootstrap's grid system (row, col-sm-8, col-sm-4) to ensure that the file name input and the download button are aligned horizontally and respond well to different screen sizes. The pr-1 and pl-1 classes add padding to the right and left of these elements, respectively, for proper spacing.

Upon generating a barcode, the source (src) of the barcodeImage <img> tag is updated to display the image. Users can then type a file name of their choice in the input field. Clicking the "Download" button should trigger a download of the image, ideally using the name entered by the user. The specifics of the download functionality (e.g., setting the file name and handling the download action) would be implemented using JavaScript or server-side logic tied to the button's click event.

Scripts

Now it's time to add the functionality of the download button, input handling, and handling of success or error messages. We can achieve it using jQuery. Here is the script to add to the index.cshtml file:

@section Scripts {
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            var messageTimeout;

            $("form").submit(function (event) {
                event.preventDefault();
                clearTimeout(messageTimeout);
                var formData = new FormData($(this)[0]);
                $.ajax({
                    url: '@Url.Page("Index", "Upload")',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        $("#messageContainer").show();
                        $("#message").html(data.message);

                        if (data.success && data.imagePath) {
                            $("#barcodeImage").attr("src", data.imagePath).show();
                            $("#imageContainer").show();
                        } else {
                            console.error("Barcode generation failed or no image path provided.");
                        }

                        messageTimeout = setTimeout(function () {
                            $("#messageContainer").fadeOut("slow");
                        }, 3000);
                    },

                    error: function (xhr, status, error) {
                        console.error("Error: " + error);
                    }
                });
            });

            $("#customDownloadBtn").click(function () {
                var fileName = $("#fileName").val().trim();
                if (fileName === "") {
                    fileName = "Generated Barcode";
                }
                var downloadLink = $("<a>").attr({
                    href: $("#barcodeImage").attr("src"),
                    download: fileName + ".png",
                    style: "display: none;"
                }).appendTo("body");
                downloadLink [0].click();
                downloadLink.remove();
            });
        });
    </script>
}
JAVASCRIPT

Prevent Default Form Submission: When the form is submitted, the default action (which would reload the page) is prevented. This allows for an asynchronous request to be made instead, keeping the user on the same page for a smoother experience.

Form Data Collection: The form data, including inputs for barcode data, type, dimensions, and color, are collected into a FormData object. This approach is particularly useful for handling file uploads or data that includes special characters without needing to manually encode the data.

AJAX Request: An asynchronous request is made to the server using jQuery's $.ajax method. The url is dynamically generated to match the Razor Page's handler for uploading ("Index", "Upload"), ensuring that the form data is processed by the correct server-side method. The options processData: false and contentType: false is necessary when submitting FormData objects to prevent jQuery from transforming the data, allowing the server to correctly interpret the multipart/form-data format.

Success Handling: On successful response, the script shows the message container and updates its content based on the server's response. If the response indicates success and includes an image path, the script updates the src attribute of the barcode image and displays it. A timeout is set to automatically hide the message after 3 seconds, providing user feedback that fades out to clean up the UI.

Error Handling: In case of an error with the request, an error message is logged to the console. This basic handling could be expanded to provide user feedback directly in the UI.

Download Button Click: When the download button is clicked, the script checks if a file name has been entered by the user. If not, it defaults to "Generated Barcode".

Creating a Download Link: A temporary <a> element is created and configured with the href attribute pointing to the barcode image's source and the download attribute set to the desired file name (appending ".png" to match the expected image format). The link is hidden from view since it's not meant to be displayed as part of the page layout.

Triggering the Download: The script programmatically clicks the link, prompting the browser to download the image file. Afterward, the temporary link is removed from the document to clean up.

This script directly interacts with the HTML elements defined in the previous snippets, such as the form for inputting barcode data, the message container for feedback, and the image container for displaying the generated barcode. It makes the application dynamic, allowing for the asynchronous generation and retrieval of barcodes without page reloads, and provides an intuitive mechanism for users to download the generated barcode images.

Step 4: Writing Functional Code

Define Color

At the top of the page, we'll add the following line:

using Color = IronSoftware.Drawing.Color;

It'll help to understand the code that we're using, thus, understanding IronSoftware.Drawing.Color that we use to put Color in our code.

Design Barcode Colors Enum

In your index.cshtml file, defining an enum named BarcodeColors serves as a crucial component for specifying the color options available for generating barcodes. This enumeration lists various color names, which correspond to predefined colors in IronDrawing.

public enum BarcodeColors
{
    AliceBlue,
    AntiqueWhite,
    Aqua,
    Aquamarine,
    Azure,
    Beige,
    Bisque,
    // Note: IronDRAWING supports a wide selection of colors for barcodes. For a complete list, please refer to the official documentation.
}

In the HTML form within your Razor Page (index.cshtml), you've included an input field for barcode color with an associated data list. This data list is dynamically populated with options based on the BarcodeColors enum.

Barcode Types Enum

The BarcodeTypes enum, similar to the BarcodeColors enum, serves a critical role in defining the different types of barcodes that users can generate in your application. This enum lists a variety of barcode formats, including both one-dimensional (1D) and two-dimensional (2D) barcodes, catering to a wide range of use cases and industry standards.

public enum BarcodeTypes
{
    Aztec,
    Codabar,
    Code128,
    Code39,
    Code93,
    DataMatrix,
    EAN13,
    EAN8,
    ITF,
    MSI,
    PDF417,
    Plessey,
    QRCode,
    UPCA,
    UPCE
}

In the frontend, particularly in your Razor Page (index.cshtml), this enum is used to populate a dropdown menu (via a datalist) that allows users to select the desired barcode format to generate.

EnumToColor Helper Function

This helper function, EnumToColor, is designed to convert enum values from BarcodeColors into their corresponding IronSoftware.Drawing objects. This conversion is essential for the backend processing in your application, where the selected color for a barcode needs to be translated from a user's selection into a color that can be applied to the barcode image generation process.

private Color EnumToColor(BarcodeColors colorEnum)
{
    return colorEnum switch
    {
        BarcodeColors.AliceBlue => Color.AliceBlue,
        BarcodeColors.AntiqueWhite => Color.AntiqueWhite,
        BarcodeColors.Aqua => Color.Aqua,
        BarcodeColors.Aquamarine => Color.Aquamarine,
        BarcodeColors.Azure => Color.Azure,
        BarcodeColors.Beige => Color.Beige,
        BarcodeColors.Bisque => Color.Bisque,
        _ => Color.Black, // Default or fallback color
    //and so on!
    };
}

The function takes one parameter of type BarcodeColors, which is the enum representing the user's choice of color for the barcode. It returns an IronSoftware.Drawing object corresponding to the enum value passed to it.

The function uses a switch expression, a feature introduced in C# 8.0, to match the colorEnum parameter against each possible BarcodeColors enum value. For each case in the switch expression, it returns the System.Drawing.Color object that matches the name of the enum value. For example, if BarcodeColors.AliceBlue is passed, and it returns Color.AliceBlue.

The switch expression covers all defined colors in the BarcodeColors enum, ensuring that any selected color can be accurately translated to an IronSoftware.Drawing object. If the enum value does not match any case (which should not happen if all cases are covered), the default case returns Color.Black as a fallback.

Barcode Type Helper Function

The GetBarcodeEncoding function is a critical part of the backend logic in your application, designed to map the selected barcode type from a user-friendly enum (BarcodeTypes) to the specific encoding required by the barcode generation library (denoted here as BarcodeWriterEncoding).

private BarcodeWriterEncoding GetBarcodeEncoding(BarcodeTypes barcodeType)
{
    return barcodeType switch
    {
        BarcodeTypes.Aztec => BarcodeWriterEncoding.Aztec,
        BarcodeTypes.Codabar => BarcodeWriterEncoding.Codabar,
        BarcodeTypes.Code128 => BarcodeWriterEncoding.Code128,
        BarcodeTypes.Code39 => BarcodeWriterEncoding.Code39,
        BarcodeTypes.Code93 => BarcodeWriterEncoding.Code93,
        BarcodeTypes.DataMatrix => BarcodeWriterEncoding.DataMatrix,
        BarcodeTypes.EAN13 => BarcodeWriterEncoding.EAN13,
        BarcodeTypes.EAN8 => BarcodeWriterEncoding.EAN8,
        BarcodeTypes.ITF => BarcodeWriterEncoding.ITF,
        BarcodeTypes.MSI => BarcodeWriterEncoding.MSI,
        BarcodeTypes.PDF417 => BarcodeWriterEncoding.PDF417,
        BarcodeTypes.Plessey => BarcodeWriterEncoding.Plessey,
        BarcodeTypes.QRCode => BarcodeWriterEncoding.QRCode,
        BarcodeTypes.UPCA => BarcodeWriterEncoding.UPCA,
        BarcodeTypes.UPCE => BarcodeWriterEncoding.UPCE,
        _ => BarcodeWriterEncoding.QRCode, // Default or fallback encoding
    };
}

The function accepts one parameter of type BarcodeTypes, which represents the user's selection of the barcode format. It returns a value of BarcodeWriterEncoding, which corresponds directly to the encoding types supported by the barcode generation library.

Utilizing a switch expression, this function matches the barcodeType parameter against each defined value in the BarcodeTypes enum. For each case in the switch expression, it returns the equivalent BarcodeWriterEncoding value. For instance, if BarcodeTypes.Code128 is passed, and the function returns BarcodeWriterEncoding.Code128.

This comprehensive switch expression ensures every barcode format selectable by the user has a corresponding encoding type that the barcode generation library can utilize. The default case returns BarcodeWriterEncoding.QRCode as a fallback. This choice of default assumes that QR codes are a common and widely applicable choice; however, the default behavior could be tailored to match the requirements of your application or even throw an exception if an unsupported barcode type is encountered.

Adding Message and BarcodeImageUrl properties

These properties are used to communicate the outcome of operations (such as barcode generation) back to the Razor Page (the .cshtml file) and to hold the URL of the generated barcode image, respectively. In your Razor Page, you can access these properties to display the message and the barcode image to the user.

public string Message { get; set; }
public string BarcodeImageUrl { get; set; }

OnPostUpload Function Signature

This is the signature of an HTTP POST handler in an ASP.NET Core Razor Pages application. It's designed to respond to a form submission for barcode generation.

public JsonResult OnPostUpload(string barcodeText, string barcodeType, int? maxWidth, int? maxHeight, string barcodeColor, string correctionLevel)
{
}

The function receives several parameters from the form:

barcodeText: The data to be encoded into the barcode.

barcodeType: The type of barcode to generate (e.g., QR Code, Code128).

maxWidth and maxHeight: Optional parameters to specify the dimensions of the generated barcode.

barcodeColor: The color for the barcode.

correctionLevel: Not used in the provided snippet, but typically relates to the error correction level for certain barcode types like QR Codes.

Encoding Selection and Barcode Generation

Now it's time to start implementing logic. Here is the code script:

BarcodeWriterEncoding encoding = BarcodeWriterEncoding.QRCode; // Default to QRCode

// Attempt to parse the barcodeType to the corresponding BarcodeTypes enum
if (Enum.TryParse<BarcodeTypes>(barcodeType, true, out var barcodeTypeEnum))
{
    encoding = GetBarcodeEncoding(barcodeTypeEnum);
}
else
{
    // Handle the case where barcodeType does not match any enum value
    return new JsonResult(new { success = false, message = "Invalid barcode type selected." });
}
var myBarcode = BarcodeWriter.CreateBarcode(barcodeText, encoding);

Initially, a default barcode encoding is set. The function attempts to parse the barcodeType string to the BarcodeTypes enum. If successful, it calls GetBarcodeEncoding, a helper function that maps BarcodeTypes to the specific encoding required by the barcode writer library (BarcodeWriterEncoding). If the barcodeType is invalid, it returns an error. Then, it generates the barcode with the specified text and encoding.

Color Conversion and Barcode Customization

This part handles the barcode's color and size customization. It first checks if a color has been specified. If so, it tries to parse this color to the BarcodeColors enum and then convert it to a System.Drawing.Color object using the EnumToColor helper function. If the color is invalid, an error is returned. Next, if both maxWidth and maxHeight are provided, it resizes the barcode to these dimensions.

// Convert the barcodeColor string to a Color object
if (!string.IsNullOrEmpty(barcodeColor))
{
    // Attempt to parse the barcodeColor to the corresponding BarcodeColors enum
    if (Enum.TryParse<BarcodeColors>(barcodeColor, true, out var barcodeColorEnum))
    {
        // Convert the enum to a Color object
        var color = EnumToColor(barcodeColorEnum);
        myBarcode.ChangeBarCodeColor(color, true);
    }
    else
    {
        // Handle the case where barcodeType does not match any enum value
        return new JsonResult(new { success = false, message = "Invalid Color selected." });
    }
}

if (maxWidth.HasValue && maxHeight.HasValue)
{
    myBarcode.ResizeTo(maxWidth.Value, maxHeight.Value);
}

Saving and Returning the Barcode Image

Finally, the generated barcode image is saved to the server. A unique filename is created using the current timestamp to avoid naming conflicts. The barcode is saved in a specific directory (wwwroot/barcodes), which is created if it doesn't already exist. After saving the image, a success message is prepared, and a JSON response is returned, including the success status, message, and the path to the generated barcode image. This allows the client-side application to display the generated barcode or provide a link for the user to download it.

// The rest of your code for saving and returning the barcode image...
var barcodesFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "barcodes");
Directory.CreateDirectory(barcodesFolderPath);
var fileName = $"barcode_{DateTime.Now:yyyyMMddHHmmssfff}.png";
var filePath = Path.Combine(barcodesFolderPath, fileName);
myBarcode.SaveAsImage(filePath);
this.Message = $"QR Code generated successfully. File name: {fileName}";

return new JsonResult(new { success = true, message = Message, imagePath = $"/barcodes/{fileName}" });

Edit _Layout.cshtml

In the _Layout.cshtml file, we remove the header and footer tags to make our application look good and minimalist. This is what the final _Layout.cshtml file will look like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData ["Title"] - Barcode_Generator_Razor</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/Barcode_Generator_Razor.styles.css" asp-append-version="true" />
</head>
<body>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData ["Title"] - Barcode_Generator_Razor</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/Barcode_Generator_Razor.styles.css" asp-append-version="true" />
</head>
<body>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>
HTML

Run Application

You can run your application by clicking the green 'Start' arrow or pressing F5 to start debugging. If you prefer to run without attaching the debugger, press Ctrl + F5.

Outputted web application Start by typing the information you want to encode into the barcode. This can be any text or a URL you wish to convert into a barcode format. Click on the dropdown menu labeled "Type of Barcode". A list will appear with different barcode formats. You can type here to filter through the list and select the barcode type that fits your needs. For example, you might select "Aztec" or "QR Code" from the list.

Selecting the barcode type Look for the fields labeled "Max Width (px)" and "Max Height (px)." Here, you'll enter the maximum dimensions for your barcode to ensure it's the right size for your application. Try entering 300 for both to keep the barcode large enough to scan easily, but not too large to fit on your desired medium.

Having set the width and height of the barcode Click on the "Color for Barcode" dropdown. A list with color options will pop up, similar to the barcode type selection. You can scroll to see all the colors or start typing to find a particular color like "AliceBlue".

Having selected a barcode colour After filling out all the fields, click on the "Generate Barcode" button. The web application will use the data you've provided to create a barcode image that appears on the screen. It'll show on the side of the input form. We called this section the image column in our frontend code.

Outputed barcode in the image column You can again change the color of the barcode by selecting a different color and clicking the Generate Barcode button.

Having changed the colour to dark magenta If you're happy with the generated barcode displayed on the screen, you'll see an option to enter a file name. After naming your file, click the "Download" button to save the barcode image onto your computer. When you check the barcodes folder in your project, you'll see the generated barcodes in this folder.

Downloaded barcode image within files

Conclusion

In conclusion, the barcode generator web application provides a straightforward way to create custom barcodes. Users can easily input data, choose a barcode type, set the size, and pick a color before generating a barcode that fits their specific needs. This tool is designed for simplicity, allowing for quick creation and customization of barcodes. IronBarcode, the library powering this application, offers a free trial for users to test its features. If you find the tool fits your requirements, you can acquire a license starting at $749, which unlocks the full capabilities of IronBarcode for your projects.

To generate QR Code images in your web application, I suggest using IronQR for this purpose as it is tailored specifically for handling QR codes.

< PREVIOUS
How to Use a Document Scanner SDK in a .NET MAUI Application
NEXT >
How to Generate Barcodes in VB .NET

Ready to get started? Version: 2024.11 just released

Free NuGet Download Total downloads: 1,290,353 View Licenses >