Saltar al pie de página
USO DE IRONBARCODE

Cómo Generar Código QR en Blazor

This article shows how developers can use the IronBarcode library to make QR codes in C# projects.

IronBarcode - C#

IronBarcode is a C# Barcode & QR code Library that allows you to read and generate barcodes and QR codes easily in any .NET C# applications. It prioritizes speed, accuracy, and ease of use for C#

IronBarcode is a user-friendly library that allows developers to easily add, read, and style QR codes in C# projects, usually within minutes. It enables developers to create QR codes in formats like Aztec, Data Matrix, MaxiCode. Different barcode types are available using IronBarcode, e.g., Code 39, Code 128, RSS14, etc.

IronBarcode is compatible with all .NET Framework languages, i.e., C#, F#, and VB.NET. It supports all .NET platforms listed below:

  • .NET 7, 6 & 5
  • .NET Core 2x & 3x
  • .NET Standard 2
  • .NET Framework 4.6.2+

How to Generate QR Code in Blazor Server Application?

Prerequisites

To create QR codes in Blazor web apps in C#, we require the following components:

  1. Visual Studio - It is an Integrated Development Environment (IDE) used for C# development. It can be downloaded from the Visual Studio website. Or you can use any other IDE supported for C#
  2. Blazor Server App: Creating Blazor Server app is the primary task. Follow the given steps below to create a Blazor server web application.

    • Open your IDE or Visual Studio. Click Create a new project.

      How to Generate QR Code in Blazor: Figure 1

    • Choose Blazor Server App from the available project options.

      How to Generate QR Code in Blazor: Figure 2

    • Next, set the location and name your project.

      How to Generate QR Code in Blazor: Figure 3

    • Next, set the additional information for your project. Select an appropriate .NET Framework Version. IronBarcode supports .NET versions 2 through 7, with .NET 7 being the latest.

      How to Generate QR Code in Blazor: Figure 4

  3. IronBarcode - The .NET QR code and Barcode library that helps to generate and read different barcode types. Following are the different ways to install IronBarcode:
    • Direct download IronBarcode from the NuGet website.
    • Install via Manage NuGet packages for solution in Visual Studio tools or right-click on solution explorer to choose NuGet Package Manager.
    • Download IronBarcode DLL directly from the Iron Software website.

Adding IronBarcode Namespace

Once everything is installed and ready, add the following assembly reference to your Blazor barcode application's "Imports.razor" file:

@using IronBarCode

How to Generate QR Code in Blazor: Figure 5

Add License Key

IronBarcode must be licensed to be used for deployment. You can get your free trial license key from here. Add the following lines of code to the Program.cs file:

using IronBarCode;

// Set the license key for IronBarcode here.
License.LicenseKey = "YOUR-KEY-HERE";
using IronBarCode;

// Set the license key for IronBarcode here.
License.LicenseKey = "YOUR-KEY-HERE";
Imports IronBarCode

' Set the license key for IronBarcode here.
License.LicenseKey = "YOUR-KEY-HERE"
$vbLabelText   $csharpLabel

Steps to Generate QR Code

The following steps will help generate QR codes in the best possible way in Blazor Server application:

Adding Blazor HTML Components

First, we are going to add some HTML code to the "Index.razor" page. The code consists of some headings, an input field, and buttons.

Use the code below to add the components to the Blazor barcode app:

<h4>Welcome to Blazor QR Code Generator</h4>
<p>Enter the value to Generate QR Code:</p>

<!-- Input field for QR code text -->
<input @bind="text" />

<!-- Button to trigger QR code generation -->
<button @onclick="QRCodeGenerater">Generate QR Code</button>

<p>Generated QR Code:</p>
<h4>Welcome to Blazor QR Code Generator</h4>
<p>Enter the value to Generate QR Code:</p>

<!-- Input field for QR code text -->
<input @bind="text" />

<!-- Button to trigger QR code generation -->
<button @onclick="QRCodeGenerater">Generate QR Code</button>

<p>Generated QR Code:</p>
HTML

The output is as follows:

How to Generate QR Code in Blazor: Figure 6

The text field is used to get input from the user, and the generate button will call the QRCodeGenerater method to create a QR code. The created QR code will be displayed under the "Generated QR Code:" heading. Now, let's create the QRCodeGenerater method.

Create the QRCodeGenerater Method

It's time to use the powerful IronBarcode library in Visual Studio to generate QR codes. The @code section is added to the "Index.razor" page. Let's first see the complete code below:

@code {
    // Variable to hold the generated QR code HTML
    private string qrCode = "";

    // Variable to hold user input text
    private string text = "";

    // Method to generate QR code from user input
    private void QRCodeGenerater()
    {
        // Create a QR code from the input text
        GeneratedBarcode myQRCode = QRCodeWriter.CreateQrCode(text);

        // Convert the generated QR code to HTML tag
        qrCode = Convert.ToString(myQRCode.ToHtmlTag());
    }
}

In the above code, there are two private string variables. qrCode will display the generated QR code, and text will get the user input from the input field. Then, in the QRCodeGenerater method, myQRCode is created using the QRCodeWriter class's CreateQrCode method. The CreateQrCode method provides several parameters to enhance the code output. You can customize the size of the QR code, set error correction code words to maintain the error correction level, and change the QrVersion. The code below helps you work with other parameters as well:

// Creating a QR code with custom parameters
QRCodeWriter.CreateQrCode(
    "https://ironsoftware.com/csharp/barcode/", // URL for the QR code
    500, // Size of the QR code
    QRCodeWriter.QrErrorCorrectionLevel.High, // Error correction level
    0 // QrVersion
)
// Creating a QR code with custom parameters
QRCodeWriter.CreateQrCode(
    "https://ironsoftware.com/csharp/barcode/", // URL for the QR code
    500, // Size of the QR code
    QRCodeWriter.QrErrorCorrectionLevel.High, // Error correction level
    0 // QrVersion
)
' Creating a QR code with custom parameters
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'QRCodeWriter.CreateQrCode("https://ironsoftware.com/csharp/barcode/", 500, QRCodeWriter.QrErrorCorrectionLevel.High, 0)
$vbLabelText   $csharpLabel

Finally, the generated Blazor barcode is converted to an HTML tag and then to a qrCode string.

Get more detail on IronBarcode features from this code examples page.

Display on the Blazor Server Application Home Page

Add the code below in HTML components in the "Index.razor" page, after the H4 heading to display qrCode:

@((MarkupString)qrCode)

Save As a PNG File

You can also save it to a PNG file using the SaveAsPng method:

// Save the generated QR code as a PNG file
myQRCode.SaveAsPng("myQRCode.png");
// Save the generated QR code as a PNG file
myQRCode.SaveAsPng("myQRCode.png");
' Save the generated QR code as a PNG file
myQRCode.SaveAsPng("myQRCode.png")
$vbLabelText   $csharpLabel

How to Generate QR Code in Blazor: Figure 7

Generate QR Code on Page Load

You can also create a QR code on page load and display it for the users to scan for data. The following code helps you achieve this task asynchronously:

@((MarkupString)qrCode)

@code {
    // Variable to hold the generated QR code HTML
    private string qrCode = "";

    // Method called when the page is initialized
    protected override async Task OnInitializedAsync()
    {
        // Asynchronously generate a QR code on page load
        await Task.Run(() =>
            qrCode = Convert.ToString(QRCodeWriter.CreateQrCode(
                "https://ironsoftware.com/csharp/barcode/", 
                500, 
                QRCodeWriter.QrErrorCorrectionLevel.High, 
                0).ToHtmlTag())
        );
    }
}

How to Generate QR Code in Blazor: Figure 8

Summary

In this article, we learned how to generate QR codes in a Blazor Server application using IronBarcode in C#. IronBarcode is a flexible library and provides all necessary methods and support for Blazor apps.

IronBarcode easily converts plain text, images, videos, or any other data to QR codes. You can control the code size, error correction levels, and its version. You can use IronBarcode to scan barcodes in Blazor applications. A complete example is here.

IronBarcode is free for development but must be licensed for commercial and deployment purposes. You can try the free trial to test all its functionality.

Preguntas Frecuentes

¿Cómo puedo generar un código QR en una aplicación Blazor usando C#?

Puedes generar un código QR en una aplicación Blazor usando la biblioteca IronBarcode. Instala IronBarcode a través de NuGet o descargando el DLL, y luego usa el método QRCodeGenerater para convertir la entrada del usuario en códigos QR.

¿Cuáles son los pasos para instalar una biblioteca de generación de códigos QR en una aplicación Blazor Server?

Para instalar una biblioteca de generación de códigos QR en una aplicación Blazor Server, descarga IronBarcode desde NuGet, agrega el espacio de nombres @using IronBarCode en tu archivo Imports.razor y configura una clave de licencia si es necesario.

¿Cómo puedo personalizar los códigos QR generados en un proyecto Blazor?

IronBarcode permite la personalización de códigos QR en un proyecto Blazor modificando elementos como el color, el margen y el tamaño. Usa los métodos de IronBarcode para ajustar estas propiedades al generar códigos QR.

¿Qué método se puede usar para guardar un código QR generado como un archivo de imagen?

Usa el método SaveAsPng de la biblioteca IronBarcode para guardar los códigos QR generados como archivos de imagen PNG en tu aplicación Blazor.

¿Cómo se pueden mostrar códigos QR en una aplicación Blazor?

Los códigos QR se pueden mostrar en una aplicación Blazor convirtiéndolos en una cadena de etiqueta HTML y usando MarkupString para renderizar el código QR en la página.

¿Es posible generar un código QR cuando se carga una página Blazor?

Sí, puedes generar un código QR al cargar una página Blazor utilizando métodos asincrónicos en el evento de ciclo de vida OnInitializedAsync.

¿Cuáles son los requisitos de licencia para usar una biblioteca de códigos QR en una aplicación .NET?

IronBarcode es gratuito para desarrollo, pero requiere una licencia comercial para su implementación. Una licencia de prueba está disponible para fines de prueba.

¿Se puede usar IronBarcode con diferentes plataformas .NET para la generación de códigos QR?

Sí, IronBarcode es compatible con una amplia gama de plataformas .NET, incluyendo .NET 7, .NET 6, .NET 5, .NET Core 2x & 3x, .NET Standard 2, y .NET Framework 4.6.2+.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más