Write QR Codes in C#

Introduction

With IronQR, developers can create QR codes for popular image formats and customize them with background colors, margins, logos, and even add them to PDFs. For advanced use, it also offers control over error correction and versions.

This article will explore key features of IronQR with examples, helping you understand how to use it for writing QR codes in C# and apply it effectively in your projects.

Table of Contents

Start using IronQR in your project today with a free trial.

First Step:
green arrow pointer

Input Data

Text, URLs, Numbers

IronQR can convert a wide range of data types, including text, URLs, and numbers, into QR codes. Whether you're creating QR code links or text for marketing and communication, numeric codes for inventory management, or encoding binary data or streams into readable QR codes, IronQR provides all the support you need.

Additionally, the API is straightforward. The QrWriter class offers several overloads, enabling different types of data as input, reducing complexity and streamlining the process.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-1.cs
using IronQr;
using IronSoftware.Drawing;

// Define text to embed in QR codes
string text = "Hello, World!";
string url = "https://ironsoftware.com/csharp/qr/";
string alphanumeric = "WATERSKU-12356";

// Create and save a QR code from a plain text string
QrCode textQr = QrWriter.CreateQrCode(text);
AnyBitmap textQrImage = textQr.ToBitmap(); // Convert the QR code to an image
textQrImage.SaveAs("textQr.png"); // Save image as a PNG file

// Create and save a QR code from a URL
QrCode urlQr = QrWriter.CreateQrCode(url);
AnyBitmap urlQrImage = urlQr.ToBitmap(); // Convert the QR code to an image
urlQrImage.SaveAs("urlQr.png"); // Save image as a PNG file

// Create and save a QR code from an alphanumeric string
QrCode alphanumericQr = QrWriter.CreateQrCode(alphanumeric);
AnyBitmap alphanumericQrImage = alphanumericQr.ToBitmap(); // Convert the QR code to an image
alphanumericQrImage.SaveAs("alphanumericQr.png"); // Save image as a PNG file
Imports IronQr
Imports IronSoftware.Drawing

' Define text to embed in QR codes
Private text As String = "Hello, World!"
Private url As String = "https://ironsoftware.com/csharp/qr/"
Private alphanumeric As String = "WATERSKU-12356"

' Create and save a QR code from a plain text string
Private textQr As QrCode = QrWriter.CreateQrCode(text)
Private textQrImage As AnyBitmap = textQr.ToBitmap() ' Convert the QR code to an image
textQrImage.SaveAs("textQr.png") ' Save image as a PNG file

' Create and save a QR code from a URL
Dim urlQr As QrCode = QrWriter.CreateQrCode(url)
Dim urlQrImage As AnyBitmap = urlQr.ToBitmap() ' Convert the QR code to an image
urlQrImage.SaveAs("urlQr.png") ' Save image as a PNG file

' Create and save a QR code from an alphanumeric string
Dim alphanumericQr As QrCode = QrWriter.CreateQrCode(alphanumeric)
Dim alphanumericQrImage As AnyBitmap = alphanumericQr.ToBitmap() ' Convert the QR code to an image
alphanumericQrImage.SaveAs("alphanumericQr.png") ' Save image as a PNG file
$vbLabelText   $csharpLabel

Binary & Streams

Similarly, we can convert binary data and streams into QR codes using the same Write method as mentioned earlier.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-2.cs
// Import necessary namespaces
using IronQr;
using IronSoftware.Drawing;
using System.Text;

// Main level code for creating a QR code from a URL
// and saving it as an image file.

// Convert the URL string into a byte array using UTF-8 encoding
byte[] bytes = Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/qr/");

// Create a QR code from the byte array
// Ensure that the QrWriter is correctly invoked from the IronQr namespace
QrCode bytesQr = QrWriter.CreateQrCode(bytes);

// Convert the QR code into a bitmap image
AnyBitmap qrImage = bytesQr.ToBitmap();

// Save the QR code bitmap to a file with a specified file name
// The image is saved in PNG format
qrImage.SaveAsPng("bytesQr.png");
' Import necessary namespaces
Imports IronQr
Imports IronSoftware.Drawing
Imports System.Text

' Main level code for creating a QR code from a URL
' and saving it as an image file.

' Convert the URL string into a byte array using UTF-8 encoding
Private bytes() As Byte = Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/qr/")

' Create a QR code from the byte array
' Ensure that the QrWriter is correctly invoked from the IronQr namespace
Private bytesQr As QrCode = QrWriter.CreateQrCode(bytes)

' Convert the QR code into a bitmap image
Private qrImage As AnyBitmap = bytesQr.ToBitmap()

' Save the QR code bitmap to a file with a specified file name
' The image is saved in PNG format
qrImage.SaveAsPng("bytesQr.png")
$vbLabelText   $csharpLabel

class Program { static void Main() { // Create a QR code writer instance QrWriter writer = QrWriter.CreateQrCode();

    // Example binary data
    byte[] data = { 0x01, 0x02, 0x03, 0x04 };

    // Write binary data to QR code
    writer.Write(data)
          .SaveAs("binary-qr.png");

    // Example using a memory stream
    using (MemoryStream stream = new MemoryStream(data))
    {
        writer.Write(stream)
              .SaveAs("stream-qr.png");
    }
}

}


The `Write` method has overloads that accept both byte arrays and streams as inputs. For streams, we can create a `MemoryStream` from the byte array and then convert it into a QR code. This is useful when users require more fine-grained control over data chunks, as streams can be more memory-efficient.

```cs
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-3.cs

Export QR Codes

IronQR is flexible and adaptable to various use cases that require different file formats. You can save QR codes in multiple formats such as JPG, PNG, GIF, and TIFF using the SaveAs method.

Save as Image

The SaveAs method from AnyBitmap automatically detects the file format based on the provided file path. In this example, I specified a file path ending with .png.

Please note
When using the SaveAs method, please note that there is no default image format. If you enter an unrecognized extension or make a typo in the file path, the image will be saved with the incorrect extension.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-4.cs
using IronBarCode; // Ensure IronBarCode is the correct namespace; IronQr might not exist
using IronSoftware.Drawing; // This might be necessary for specific drawing operations

// This code snippet generates a QR code from a given text and saves it as an image file.
// It uses the IronBarCode library to facilitate the QR code creation and image manipulation.

// Create a QR code object using the desired content
// "hello world" is the text that will be embedded within the generated QR code
QrCode qr = QrCodeWriter.CreateQrCode("hello world"); // Correct method name may vary depending on the library version

// Convert the QR code to a bitmap format for easy manipulation and saving
AnyBitmap qrImage = qr.ToBitmap();

// Save the QR code bitmap as an image file; specify the file format by the extension (e.g., .png)
qrImage.SaveAs("qr.png"); // Ensure that the path and file permissions are correct
Imports IronBarCode ' Ensure IronBarCode is the correct namespace; IronQr might not exist
Imports IronSoftware.Drawing ' This might be necessary for specific drawing operations

' This code snippet generates a QR code from a given text and saves it as an image file.
' It uses the IronBarCode library to facilitate the QR code creation and image manipulation.

' Create a QR code object using the desired content
' "hello world" is the text that will be embedded within the generated QR code
Private qr As QrCode = QrCodeWriter.CreateQrCode("hello world") ' Correct method name may vary depending on the library version

' Convert the QR code to a bitmap format for easy manipulation and saving
Private qrImage As AnyBitmap = qr.ToBitmap()

' Save the QR code bitmap as an image file; specify the file format by the extension (e.g., .png)
qrImage.SaveAs("qr.png") ' Ensure that the path and file permissions are correct
$vbLabelText   $csharpLabel

System.Drawing.Images

Converting images to the System.Drawing.Images object from Microsoft allows you to use the Bitmap class to save the QR code to a file path. In this example, the Save method saves the QR code as a PNG file to the path qrBitmap.png.

Please note
System.Drawing.Common is only supported on the Windows platform.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-5.cs
using IronQr;
using System.Drawing;

// This class contains the Main entry point for the application,
// which generates a QR code from a given string and saves it as an image file.
class Program
{
    static void Main()
    {
        // Create a QR code from the string "hello world"
        // The CreateQrCode method initializes a QrCode object with the specified data.
        QrCode qr = QrWriter.CreateQrCode("hello world");

        // Convert the QR code into a bitmap image
        // The ToBitmap method generates a Bitmap object that visually represents the QR code.
        Bitmap qrImage = qr.ToBitmap();

        // Save the generated QR code bitmap as a PNG file
        // The Save method writes the Bitmap image to the file "qrBitmap.png" in the current directory.
        qrImage.Save("qrBitmap.png");
    }
}
Imports IronQr
Imports System.Drawing

' This class contains the Main entry point for the application,
' which generates a QR code from a given string and saves it as an image file.
Friend Class Program
	Shared Sub Main()
		' Create a QR code from the string "hello world"
		' The CreateQrCode method initializes a QrCode object with the specified data.
		Dim qr As QrCode = QrWriter.CreateQrCode("hello world")

		' Convert the QR code into a bitmap image
		' The ToBitmap method generates a Bitmap object that visually represents the QR code.
		Dim qrImage As Bitmap = qr.ToBitmap()

		' Save the generated QR code bitmap as a PNG file
		' The Save method writes the Bitmap image to the file "qrBitmap.png" in the current directory.
		qrImage.Save("qrBitmap.png")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronSoftware.Drawing

Due to the lack of cross-platform compatibility of System.Drawing.Common, developers may encounter issues when maintaining cross-platform applications. IronQR can utilize both System.Drawing.Common and IronSoftware.Drawing.

IronQR uses the AnyBitmap class from IronSoftware.Drawing, a universally compatible Bitmap class that implicitly casts to the following:

  • System.Drawing.Bitmap
  • System.Drawing.Image
  • SkiaSharp.SKBitmap
  • SixLabors.ImageSharp
  • Microsoft.Maui.Graphics.Platform.PlatformImage

With this powerful open-source library, IronQR achieves cross-platform support and compatibility with .NET 8, .NET 7, .NET 6, .NET 5, .NET Core, .NET Standard, and .NET Framework 4.6.2+. To learn more about the library, please refer to IronSoftware.Drawing website.

Stamp on PDF

IronQR allows developers to stamp QR codes onto existing PDF documents, making it easy for others to quickly access links or additional resources. Stamping QR codes on both single and multiple pages is supported.

Stamp to a Single Page

After creating the QR code, call the StampToExistingPdfPage method from the QrCode object. This method requires the file path, coordinates (x and y), page number, and an optional password if the PDF is password-protected. Once the arguments are provided, the method stamps the QR code and saves the PDF.

Please note
This method is based on the PDF pages, with page numbering starting at 1 instead of 0.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-6.cs
// Ensure you have the IronBarCode library included in your project by installing it through the NuGet package manager.
// You can do that by running the following command in the Package Manager Console:
// Install-Package IronBarCode

using System;
using System.IO;
using IronBarCode;

// This code snippet demonstrates how to create a QR code and stamp it onto an existing PDF file.
// Make sure to replace the 'filepath' with your own PDF file's path.

class Program
{
    static void Main()
    {
        // Create a QR code object with the specified message
        GeneratedBarcode qr = QRCodeWriter.CreateQrCode("hello world", 500);

        // Define the file path where the QR will be stamped
        string filepath = "example.pdf";

        // Define coordinates (x, y) and the page number where the QR code will be stamped
        int x = 100; // X-coordinate for the stamp position
        int y = 150; // Y-coordinate for the stamp position
        int page = 1; // Page number in the PDF where the QR code will be stamped

        // Ensure the file exists before stamping
        if (File.Exists(filepath))
        {
            try
            {
                // Stamp the QR code onto the specified PDF page at the given coordinates
                // Note: The StampToPdf method accesses the file directly and modifies it
                qr.StampToExistingPdf(filepath, page, x, y);
                Console.WriteLine("QR Code stamped successfully.");
            }
            catch (Exception ex)
            {
                // Handle any errors that might occur during the stamping process
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
        else
        {
            Console.WriteLine("The file does not exist. Please check the path and try again.");
        }
    }
}
' Ensure you have the IronBarCode library included in your project by installing it through the NuGet package manager.
' You can do that by running the following command in the Package Manager Console:
' Install-Package IronBarCode

Imports System
Imports System.IO
Imports IronBarCode

' This code snippet demonstrates how to create a QR code and stamp it onto an existing PDF file.
' Make sure to replace the 'filepath' with your own PDF file's path.

Friend Class Program
	Shared Sub Main()
		' Create a QR code object with the specified message
		Dim qr As GeneratedBarcode = QRCodeWriter.CreateQrCode("hello world", 500)

		' Define the file path where the QR will be stamped
		Dim filepath As String = "example.pdf"

		' Define coordinates (x, y) and the page number where the QR code will be stamped
		Dim x As Integer = 100 ' X-coordinate for the stamp position
		Dim y As Integer = 150 ' Y-coordinate for the stamp position
		Dim page As Integer = 1 ' Page number in the PDF where the QR code will be stamped

		' Ensure the file exists before stamping
		If File.Exists(filepath) Then
			Try
				' Stamp the QR code onto the specified PDF page at the given coordinates
				' Note: The StampToPdf method accesses the file directly and modifies it
				qr.StampToExistingPdf(filepath, page, x, y)
				Console.WriteLine("QR Code stamped successfully.")
			Catch ex As Exception
				' Handle any errors that might occur during the stamping process
				Console.WriteLine($"An error occurred: {ex.Message}")
			End Try
		Else
			Console.WriteLine("The file does not exist. Please check the path and try again.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

Stamp to Multiple Pages

Similar to the example above, the main difference is that the StampToExistingPdfPages method takes a list of page numbers instead of just one.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-7.cs
using IronQr;
using System.Collections.Generic;

// Generate a QR code object for the text "hello world".
// The IronQR library is assumed to be properly installed and referenced.
QrCode qr = QrWriter.CreateQrCode("hello world");

// Define the file path to the existing PDF on which the QR code will be stamped.
// Ensure that "example.pdf" exists in the specified path or update the path accordingly.
string filepath = "example.pdf";

// Define the coordinates (x, y) on the PDF pages where the QR code will be stamped.
// Adjust these values to position the QR code correctly on the PDF.
int x = 100;
int y = 150;

// Define a list of page numbers where the QR code will be stamped in the PDF.
// The pages are indexed starting with 1, representing the first page, and so on.
List<int> pages = new List<int> { 1, 2, 3, 4 };

// Stamp the QR code at position (100, 150) on pages 1-4 of the specified PDF.
// This method integrates the QR code into the selected pages of the PDF document.
qr.StampToExistingPdfPages(filepath, x, y, pages);
Imports IronQr
Imports System.Collections.Generic

' Generate a QR code object for the text "hello world".
' The IronQR library is assumed to be properly installed and referenced.
Private qr As QrCode = QrWriter.CreateQrCode("hello world")

' Define the file path to the existing PDF on which the QR code will be stamped.
' Ensure that "example.pdf" exists in the specified path or update the path accordingly.
Private filepath As String = "example.pdf"

' Define the coordinates (x, y) on the PDF pages where the QR code will be stamped.
' Adjust these values to position the QR code correctly on the PDF.
Private x As Integer = 100
Private y As Integer = 150

' Define a list of page numbers where the QR code will be stamped in the PDF.
' The pages are indexed starting with 1, representing the first page, and so on.
Private pages As New List(Of Integer) From {1, 2, 3, 4}

' Stamp the QR code at position (100, 150) on pages 1-4 of the specified PDF.
' This method integrates the QR code into the selected pages of the PDF document.
qr.StampToExistingPdfPages(filepath, x, y, pages)
$vbLabelText   $csharpLabel

Output from Both Examples

alt text


QR Code Options

IronQR offers extensive customization options for fine-tuning QR code behavior and functionality. The QrOptions class provides several parameters, such as version control, encoding type, character encoding, and error correction levels. Let’s explore these options in more detail.

Encoding

IronQR supports multiple types of QR codes for both creation and reading. Below are the supported types:

  • QRCode: This is the standard QR code, commonly used today. It can store up to 7,089 numeric characters or 4,296 alphanumeric characters.
  • MicroQRCode: A smaller version of the standard QR code, it can store up to 35 numeric characters or 21 alphanumeric characters.
  • RMQRCode: The Rectangular Micro QR Code is a compact version of the QR code, offering flexibility in its aspect ratio.
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-8.cs
// Import necessary namespaces from IronQrcode and IronSoftware.Drawing
using IronBarCode;
using IronSoftware.Drawing;

// Set up QR code options with desired configurations
QrCodeEncodingOptions options = new QrCodeEncodingOptions
{
    // Specify the use of Micro QR Code encoding
    Encoding = QrEncoding.MicroQrCode,
};

// Create a QR code with the specified content and options
QrCodeData qrData = QrCodeWriter.CreateQrCode("1234", options);

// Convert the QR code data to an AnyBitmap image format
AnyBitmap qrImage = qrData.ToBitmap();

// Save the QR code bitmap as a PNG file
qrImage.SaveAs("qrImage.png");
' Import necessary namespaces from IronQrcode and IronSoftware.Drawing
Imports IronBarCode
Imports IronSoftware.Drawing

' Set up QR code options with desired configurations
Private options As New QrCodeEncodingOptions With {.Encoding = QrEncoding.MicroQrCode}

' Create a QR code with the specified content and options
Private qrData As QrCodeData = QrCodeWriter.CreateQrCode("1234", options)

' Convert the QR code data to an AnyBitmap image format
Private qrImage As AnyBitmap = qrData.ToBitmap()

' Save the QR code bitmap as a PNG file
qrImage.SaveAs("qrImage.png")
$vbLabelText   $csharpLabel

Error Correction

IronQR uses standard QR error correction to ensure that all QR codes produced are fault-tolerant and reliable, even in harsh conditions. Additionally, IronQR allows you total control over error correction level for further fine-tuning.

There are four levels of error correction available, provided by QrErrorCorrectionLevel:

  • Highest: 30% error correction
  • High: 25% error correction
  • Medium: 15% error correction
  • Low: 7% error correction
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-9.cs
// Import necessary namespaces from IronQr and IronSoftware.Drawing
using IronQr;
using IronSoftware.Drawing;

// Define QR code options with custom settings
QrOptions options = new QrOptions
{
    // Set the error correction level to Medium for the QR code
    ErrorCorrectionLevel = QrErrorCorrectionLevel.Medium,
};

// Generate a QR code from the string "1234" using the defined options
QrCode qr = QrWriter.CreateQrCode("1234", options);

// Convert the generated QR code to a bitmap image
AnyBitmap qrImage = qr.ToBitmap();

// Save the QR code bitmap to a file named "qrImage.png"
qrImage.SaveAs("qrImage.png");
' Import necessary namespaces from IronQr and IronSoftware.Drawing
Imports IronQr
Imports IronSoftware.Drawing

' Define QR code options with custom settings
Private options As New QrOptions With {.ErrorCorrectionLevel = QrErrorCorrectionLevel.Medium}

' Generate a QR code from the string "1234" using the defined options
Private qr As QrCode = QrWriter.CreateQrCode("1234", options)

' Convert the generated QR code to a bitmap image
Private qrImage As AnyBitmap = qr.ToBitmap()

' Save the QR code bitmap to a file named "qrImage.png"
qrImage.SaveAs("qrImage.png")
$vbLabelText   $csharpLabel

Higher error correction provides greater fault tolerance when reading the QR code, making it more likely to be scanned at lower resolutions compared to one with low error correction. You may test out based on your use cases.

alt text

QR Code Version

You can adjust the QR code version to store more data. Higher versions are ideal for inventory or logistics, while lower versions work well for smaller data, like short URLs. Simply change the Version property in the QrOptions object and pass it to the Write method to generate the QR code as needed.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-10.cs
// Import necessary namespaces
using IronBarcode;
using IronSoftware.Drawing;

// Set QR code options with desired properties
QrCodeEncodingOptions options = new QrCodeEncodingOptions
{
    // Set QR code version to 40. This affects the size and data capacity of the QR code
    QrVersion = QRCodeVersion.Version40
};

// Create a QR code using the provided text and options
QRCodeWriter qrWriter = new QRCodeWriter();
System.Drawing.Bitmap qrCodeImage = qrWriter.Write("1234", options).ToBitmap();

// Save the created QR code as a bitmap image
AnyBitmap qrImage = new AnyBitmap(qrCodeImage);

// Save the bitmap image to a file as a PNG
qrImage.SaveAsPng("qrImage.png");

// Additional note:
// Ensure that the IronBarcode and IronSoftware.Drawing assemblies are referenced
// in your project to successfully compile and run this code.
' Import necessary namespaces
Imports IronBarcode
Imports IronSoftware.Drawing

' Set QR code options with desired properties
Private options As New QrCodeEncodingOptions With {.QrVersion = QRCodeVersion.Version40}

' Create a QR code using the provided text and options
Private qrWriter As New QRCodeWriter()
Private qrCodeImage As System.Drawing.Bitmap = qrWriter.Write("1234", options).ToBitmap()

' Save the created QR code as a bitmap image
Private qrImage As New AnyBitmap(qrCodeImage)

' Save the bitmap image to a file as a PNG
qrImage.SaveAsPng("qrImage.png")

' Additional note:
' Ensure that the IronBarcode and IronSoftware.Drawing assemblies are referenced
' in your project to successfully compile and run this code.
$vbLabelText   $csharpLabel

alt text

As you can see from the output, version 40 of the QR code is highly complex and dense compared to version 5.

Lower versions require more precise scanning and may be difficult to scan without higher-resolution scanners. However, higher versions are easier to scan, even with lower-resolution cameras. For a more detailed guide on choosing the QR version based on capacity, please refer to the QR version list.

Character Encoding

This option determines how the QR code is encoded. In our example, we changed it to 'UTF-32', while the default character encoding is 'ISO-8859-1.'

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-11.cs
// Import necessary namespaces for QR code generation and image handling
using IronBarCode; // Corrected namespace for QR code generation
using IronSoftware.Drawing; // Assuming this is the correct namespace for image operations

// Define QR code options with specific settings
QrCodeEncodingOptions options = new QrCodeEncodingOptions
{
    // Set the character encoding to UTF-8 for the QR code data
    // UTF-8 is common and supports a wide range of characters
    CharacterSet = "UTF-8"
};

try
{
    // Generate the QR code with the specified text and options
    GeneratedBarcode qr = IronBarCode.QRCodeWriter.CreateQrCode("1234", options);

    // Convert the QR code to an AnyBitmap instance for further manipulation if needed
    AnyBitmap qrImage = qr.ToBitmap();

    // Save the QR code image to a file in PNG format
    qrImage.SaveAsPng("qrImage.png");
}
catch (Exception ex)
{
    // Handle any exceptions that might occur during the QR code generation or saving process
    Console.WriteLine($"An error occurred: {ex.Message}");
}
' Import necessary namespaces for QR code generation and image handling
Imports IronBarCode ' Corrected namespace for QR code generation
Imports IronSoftware.Drawing ' Assuming this is the correct namespace for image operations

' Define QR code options with specific settings
Private options As New QrCodeEncodingOptions With {.CharacterSet = "UTF-8"}

Try
	' Generate the QR code with the specified text and options
	Dim qr As GeneratedBarcode = IronBarCode.QRCodeWriter.CreateQrCode("1234", options)

	' Convert the QR code to an AnyBitmap instance for further manipulation if needed
	Dim qrImage As AnyBitmap = qr.ToBitmap()

	' Save the QR code image to a file in PNG format
	qrImage.SaveAsPng("qrImage.png")
Catch ex As Exception
	' Handle any exceptions that might occur during the QR code generation or saving process
	Console.WriteLine($"An error occurred: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

QR Code Styling

In addition to its easy-to-use methods and flexibility in handling input data, IronQR offers many options for customizing and styling QR codes to make them unique. The QrStyleOptions class provides various parameters for customizing all aspects of a QR code. Let’s explore the available options.

Resize

To resize the QR code, you can set the Dimensions property of the QrStyleOptions object and then pass it to the Save method. By default, the QR code is saved at 300px. In this example, we saved the QR code at 600px instead of 300px.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-12.cs
// Ensure the necessary namespaces are included
using IronQr;
using IronSoftware.Drawing;

// Initialize QrStyleOptions with custom settings for the QR code
QrStyleOptions styleOptions = new QrStyleOptions()
{
    // Set the dimensions of the QR code to 600px x 600px
    // Note: Make sure the Dimensions property is correctly set according to IronQr library usage
    Dimensions = new System.Drawing.Size(600, 600)
};

// Define the URL to be encoded as a QR code
string url = "https://ironsoftware.com/csharp/qr/";

// Generate the QR code from the specified URL
// Ensure the method call correctly utilizes the IronQr library's functionality
QrCode qr = QrWriter.CreateQrCode(url, styleOptions);

// Save the generated QR code as a bitmap object with specified style options
AnyBitmap qrImage = qr.ToBitmap();

// Export the QR code image to a file on disk
// Ensure the file path is correctly specified and accessible
qrImage.SaveAs("qrURLResized.png");
' Ensure the necessary namespaces are included
Imports IronQr
Imports IronSoftware.Drawing

' Initialize QrStyleOptions with custom settings for the QR code
Private styleOptions As New QrStyleOptions() With {.Dimensions = New System.Drawing.Size(600, 600)}

' Define the URL to be encoded as a QR code
Private url As String = "https://ironsoftware.com/csharp/qr/"

' Generate the QR code from the specified URL
' Ensure the method call correctly utilizes the IronQr library's functionality
Private qr As QrCode = QrWriter.CreateQrCode(url, styleOptions)

' Save the generated QR code as a bitmap object with specified style options
Private qrImage As AnyBitmap = qr.ToBitmap()

' Export the QR code image to a file on disk
' Ensure the file path is correctly specified and accessible
qrImage.SaveAs("qrURLResized.png")
$vbLabelText   $csharpLabel

alt text

Margins & Borders

To adjust the margins and borders, we can use the Margins property of the QrStyleOptions class. This property controls the margins of the QR code on all sides, with a default value of 10px. In our example, we set the margin to 20px.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-13.cs
using IronQr;
using IronSoftware.Drawing;

// This script generates a QR code from a specified URL 
// and saves it as an image file with customized style options

// Define custom styling options for the QR code
QrStyleOptions styleOptions = new QrStyleOptions()
{
    // Set the margins of the QR code to 20 pixels
    Margins = 20
};

// URL to be encoded into the QR code
string url = "https://ironsoftware.com/csharp/qr/";

// Generate the QR code from the given URL using the specified style options
QrCode qr = QrWriter.CreateQr(url, styleOptions);

// Save the generated QR code into a bitmap image
AnyBitmap qrImage = qr.ToBitmap();

// Save the bitmap image as a file in the specified format
string filePath = "qrURLMarginMultiple.png";
qrImage.SaveAs(filePath);

// Note: If any cleanup or disposing is necessary, it should be added below.
// For example, calling Dispose on resources if the library's documentation specifies this.

// Always check library documentation for additional options, syntax, or memory management notes.
Imports IronQr
Imports IronSoftware.Drawing

' This script generates a QR code from a specified URL 
' and saves it as an image file with customized style options

' Define custom styling options for the QR code
Private styleOptions As New QrStyleOptions() With {.Margins = 20}

' URL to be encoded into the QR code
Private url As String = "https://ironsoftware.com/csharp/qr/"

' Generate the QR code from the given URL using the specified style options
Private qr As QrCode = QrWriter.CreateQr(url, styleOptions)

' Save the generated QR code into a bitmap image
Private qrImage As AnyBitmap = qr.ToBitmap()

' Save the bitmap image as a file in the specified format
Private filePath As String = "qrURLMarginMultiple.png"
qrImage.SaveAs(filePath)

' Note: If any cleanup or disposing is necessary, it should be added below.
' For example, calling Dispose on resources if the library's documentation specifies this.

' Always check library documentation for additional options, syntax, or memory management notes.
$vbLabelText   $csharpLabel

alt text

Change Margins for Each Side

IronQR also allows users to specify different margins for each side, providing more fine-grained control.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-14.cs
using IronSoftware.Drawing;
using IronSoftware.IronQr;

// This code creates a QR code for a specified URL and applies specific styling options to it

// Define styling options for the QR code
QrStyleOptions styleOptions = new QrStyleOptions()
{
    // Modify the margins to customize the appearance of the QR code
    MarginBottom = 30,  // Bottom margin of the QR code
    MarginTop = 100,    // Top margin of the QR code
    MarginRight = 40,   // Right margin of the QR code
    MarginLeft = 20,    // Left margin of the QR code
};

// URL to be encoded in the QR code
string url = "https://ironsoftware.com/csharp/qr/";

// Create a QR code with the provided URL
QrCode qr = QrWriter.CreateQrCode(url);

// Render the QR code as an image with the specified style options
AnyBitmap qrImage = qr.ToAnyBitmap(styleOptions);

// Save the generated QR code image to a file
qrImage.SaveAsPng("qrURLMarginMultiple.png");
Imports IronSoftware.Drawing
Imports IronSoftware.IronQr

' This code creates a QR code for a specified URL and applies specific styling options to it

' Define styling options for the QR code
Private styleOptions As New QrStyleOptions() With {
	.MarginBottom = 30,
	.MarginTop = 100,
	.MarginRight = 40,
	.MarginLeft = 20
}

' URL to be encoded in the QR code
Private url As String = "https://ironsoftware.com/csharp/qr/"

' Create a QR code with the provided URL
Private qr As QrCode = QrWriter.CreateQrCode(url)

' Render the QR code as an image with the specified style options
Private qrImage As AnyBitmap = qr.ToAnyBitmap(styleOptions)

' Save the generated QR code image to a file
qrImage.SaveAsPng("qrURLMarginMultiple.png")
$vbLabelText   $csharpLabel

Recolor

We can add colors to the QR code and its background using the QrStyleOptions class. Customizing colors makes the QR code more unique and eye-catching. You can change the color using the Color and BackgroundColor properties. Be sure to import IronSoftware.Drawing for a list of available colors to assign.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-15.cs
// Import necessary namespaces for QR code generation and image processing
using IronBarCode;
using IronSoftware.Drawing;

// Define style options for the QR Code
QrCodeStyling styleOptions = new QrCodeStyling()
{
    // Set the background color of the QR code to blue
    BackgroundColor = Color.Blue,
    // Set the color of the QR code to red
    QRCodeColor = Color.Red
};

// URL to be encoded into the QR Code
string url = "https://ironsoftware.com/csharp/qr/";

// Create a QR Code with the specified URL and style options
GeneratedBarcode qr = QRCodeWriter.CreateQrCode(url, 500, styleOptions);

// Convert the QR code to a bitmap
var qrImage = qr.Image;

// Save the QR code bitmap to a file
qrImage.SaveAsPng("qrURLColored.png");

/*
Note: 
- The code uses IronBarCode, which is the correct library for QR code generation.
- Changes were made to ensure compatibility with IronBarCode's API.
- Make sure you have the necessary library installed via NuGet:
  Install-Package Barcode -Version 2023.5.1 (version number may vary)
*/
' Import necessary namespaces for QR code generation and image processing
Imports IronBarCode
Imports IronSoftware.Drawing

' Define style options for the QR Code
Private styleOptions As New QrCodeStyling() With {
	.BackgroundColor = Color.Blue,
	.QRCodeColor = Color.Red
}

' URL to be encoded into the QR Code
Private url As String = "https://ironsoftware.com/csharp/qr/"

' Create a QR Code with the specified URL and style options
Private qr As GeneratedBarcode = QRCodeWriter.CreateQrCode(url, 500, styleOptions)

' Convert the QR code to a bitmap
Private qrImage = qr.Image

' Save the QR code bitmap to a file
qrImage.SaveAsPng("qrURLColored.png")

'
'Note: 
'- The code uses IronBarCode, which is the correct library for QR code generation.
'- Changes were made to ensure compatibility with IronBarCode's API.
'- Make sure you have the necessary library installed via NuGet:
'  Install-Package Barcode -Version 2023.5.1 (version number may vary)
'
$vbLabelText   $csharpLabel

alt text

In addition to colors and dimensions, you can also apply your company logo to the QR code. This helps users immediately recognize and associate the QR code with your brand. The Logo property makes it easy to customize a QR code by adding your company’s logo.

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-writing-15.cs
// Import necessary namespaces for QR code generation and image processing
using IronBarCode;
using IronSoftware.Drawing;

// Define style options for the QR Code
QrCodeStyling styleOptions = new QrCodeStyling()
{
    // Set the background color of the QR code to blue
    BackgroundColor = Color.Blue,
    // Set the color of the QR code to red
    QRCodeColor = Color.Red
};

// URL to be encoded into the QR Code
string url = "https://ironsoftware.com/csharp/qr/";

// Create a QR Code with the specified URL and style options
GeneratedBarcode qr = QRCodeWriter.CreateQrCode(url, 500, styleOptions);

// Convert the QR code to a bitmap
var qrImage = qr.Image;

// Save the QR code bitmap to a file
qrImage.SaveAsPng("qrURLColored.png");

/*
Note: 
- The code uses IronBarCode, which is the correct library for QR code generation.
- Changes were made to ensure compatibility with IronBarCode's API.
- Make sure you have the necessary library installed via NuGet:
  Install-Package Barcode -Version 2023.5.1 (version number may vary)
*/
' Import necessary namespaces for QR code generation and image processing
Imports IronBarCode
Imports IronSoftware.Drawing

' Define style options for the QR Code
Private styleOptions As New QrCodeStyling() With {
	.BackgroundColor = Color.Blue,
	.QRCodeColor = Color.Red
}

' URL to be encoded into the QR Code
Private url As String = "https://ironsoftware.com/csharp/qr/"

' Create a QR Code with the specified URL and style options
Private qr As GeneratedBarcode = QRCodeWriter.CreateQrCode(url, 500, styleOptions)

' Convert the QR code to a bitmap
Private qrImage = qr.Image

' Save the QR code bitmap to a file
qrImage.SaveAsPng("qrURLColored.png")

'
'Note: 
'- The code uses IronBarCode, which is the correct library for QR code generation.
'- Changes were made to ensure compatibility with IronBarCode's API.
'- Make sure you have the necessary library installed via NuGet:
'  Install-Package Barcode -Version 2023.5.1 (version number may vary)
'
$vbLabelText   $csharpLabel

alt text

The QrLogo class allows further customization of the logo's appearance. Below are the available properties:

  • Bitmap: Represents the image you want to use as the logo.
  • Width: Represents the logo’s width. The default value is 0.
  • Height: Represents the logo’s height. The default value is 0.
  • CornerRadius: Represents the radius for rounding the logo’s corners. By default, it's set to 0, meaning the logo will have square corners.
using IronQRCode;
using IronSoftware.Drawing;

class Program
{
    static void Main()
    {
        QrStyleOptions styleOptions = new QrStyleOptions
        {
            Logo = new QrLogo
            {
                Bitmap = AnyBitmap.FromBitmap("path/to/logo.png"),
                Width = 50,
                Height = 50,
                CornerRadius = 5
            }
        };

        QrCode qr = QrWriter.CreateQrCode()
                               .Write("Customized Logo Example");

        qr.SaveAs("example-customized-logo-qr.png", styleOptions);
    }
}
using IronQRCode;
using IronSoftware.Drawing;

class Program
{
    static void Main()
    {
        QrStyleOptions styleOptions = new QrStyleOptions
        {
            Logo = new QrLogo
            {
                Bitmap = AnyBitmap.FromBitmap("path/to/logo.png"),
                Width = 50,
                Height = 50,
                CornerRadius = 5
            }
        };

        QrCode qr = QrWriter.CreateQrCode()
                               .Write("Customized Logo Example");

        qr.SaveAs("example-customized-logo-qr.png", styleOptions);
    }
}
Imports IronQRCode
Imports IronSoftware.Drawing

Friend Class Program
	Shared Sub Main()
		Dim styleOptions As New QrStyleOptions With {
			.Logo = New QrLogo With {
				.Bitmap = AnyBitmap.FromBitmap("path/to/logo.png"),
				.Width = 50,
				.Height = 50,
				.CornerRadius = 5
			}
		}

		Dim qr As QrCode = QrWriter.CreateQrCode().Write("Customized Logo Example")

		qr.SaveAs("example-customized-logo-qr.png", styleOptions)
	End Sub
End Class
$vbLabelText   $csharpLabel

Checking Fault Tolerance

Along with extensive flexibility in file formats and customizations, the flexibility extends to debugging and error-handling aspects. IronQR provides various tools for developers to handle exceptions and write unit tests to verify applications.

CheckSums

QR codes may sometimes become damaged, but IronQR includes built-in checksums and data correction to keep them functional. It uses the Reed-Solomon error correction algorithm, ensuring that QR codes remain fault-tolerant.

Detailed Error Messages

IronQR provides detailed error messages that help users quickly identify issues. These messages contain a list of specific exceptions, making debugging and problem-solving more straightforward. Below is a list of IronQrException used by the library.

  • IronQrEncodingException: A subclass of IronQrException, this error occurs when there is an issue with writing the QR code. For instance, it will appear if a user attempts to create a QR code from an empty string.

alt text

  • IronQrFileException: A subclass of IronQrException, this error occurs when a file-related issue arises.

  • IronQrPdfPasswordExcception: A subclass of IronQrException, this error occurs when the PDF a user is trying to stamp is password-protected, and either no password or an incorrect password is provided. It also covers other PDF-related errors, such as when the PDF cannot be opened, as shown in the example.

alt text

Conclusion

IronQR provides a comprehensive set of methods for generating and customizing QR codes within .NET applications. With its robust features, developers can easily create QR codes with various data encodings, visual styles, and error correction levels. The library's support for diverse output formats and seamless integration into existing documents makes it a versatile tool for any QR code project. Whether you need basic QR codes or advanced, branded solutions, IronQR offers the flexibility and functionality to meet your needs efficiently.

To learn more, check out the IronQR documentation, start exploring with a free trial, and review the licensing options to see which plan best suits your needs.

Frequently Asked Questions

What is the functionality of this QR code library?

IronQR is a C# library that allows developers to create custom QR codes with options for error correction, branding, and exporting to various formats.

How can I create a QR code with a URL in C#?

You can create a QR code with a URL by using the QrWriter class in IronQR. Use the Write method to encode the URL and SaveAs to save the QR code as an image.

What types of data can be converted into QR codes?

IronQR can convert text, URLs, numbers, binary data, and streams into QR codes.

How can I customize the appearance of a QR code?

IronQR allows customization of QR codes by changing colors, adding logos, resizing, and adjusting margins using the QrStyleOptions class.

Can this library export QR codes to different image formats?

Yes, IronQR can export QR codes to multiple formats such as JPG, PNG, GIF, and TIFF using the SaveAs method.

What is the error correction feature in this QR code library?

Error correction in IronQR allows QR codes to be fault-tolerant and readable even if they are partially damaged. It supports four levels of error correction: Highest, High, Medium, and Low.

How do I stamp a QR code onto a PDF?

To stamp a QR code onto a PDF, use the StampToExistingPdfPage or StampToExistingPdfPages methods in IronQR, specifying the file path, coordinates, and page number(s).

Is this QR code library compatible with cross-platform applications?

Yes, IronQR achieves cross-platform compatibility using the IronSoftware.Drawing library, supporting various .NET versions and platforms.

Can I add a company logo to a QR code?

Yes, you can add a logo to a QR code by setting the Logo property in the QrStyleOptions class, which allows customization of the logo's appearance.

What error messages does this QR code library provide for debugging?

IronQR provides detailed error messages such as IronQrEncodingException, IronQrFileException, and IronQrPdfPasswordException to help identify issues during QR code creation and handling.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

Beyond development, Curtis has a strong interest in the Internet of Things (IoT), exploring innovative ways to integrate hardware and software. In his free time, he enjoys gaming and building Discord bots, combining his love for technology with creativity.