Create and Scan Barcode
Create and Scan Barcode

Create and Scan Barcode (14)

Scan QR codes and barcodes in ASP.NET Core using C# and Spire.Barcode

Many business applications today need the ability to scan barcodes and QR codes in ASP.NET environments. From ticket validation and payment processing to inventory management, an ASP.NET QR code scanner or barcode reading feature can greatly improve efficiency and accuracy for both web and enterprise systems.

This tutorial demonstrates how to build a complete solution to scan barcodes in ASP.NET with C# code using Spire.Barcode for .NET. We’ll create an ASP.NET Core web application that can read both QR codes and various barcode formats from uploaded images, delivering high recognition accuracy and easy integration into existing projects.

Guide Overview


1. Project Setup

Step 1: Create the Project

Create a new ASP.NET Core Razor Pages project, which will serve as the foundation for the scanning feature. Use the following command to create a new project or manually configure it in Visual Studio:

dotnet new webapp -n QrBarcodeScanner
cd QrBarcodeScanner

Step 2: Install Spire.Barcode for .NET

Install the Spire.Barcode for .NET NuGet package, which supports decoding a wide range of barcode types with a straightforward API. Search for the package in the NuGet Package Manager or use the command below to install it:

dotnet add package Spire.Barcode

Spire.Barcode for .NET offers built-in support for both QR codes and multiple barcode formats such as Code128, EAN-13, and Code39, making it suitable for ASP.NET Core integration without requiring additional image processing libraries. To find out all the supported barcode types, refer to the BarcodeType API reference.

You can also use Free Spire.Barcode for .NET for smaller projects.


2. Implementing QR Code and Barcode Scanning Feature with C# in ASP.NET

A reliable scanning feature involves two main parts:

  1. Backend logic that processes and decodes uploaded images.
  2. A simple web interface that lets users upload files for scanning.

We will first focus on the backend implementation to ensure the scanning process works correctly, then connect it to a minimal Razor Page frontend.

Backend: QR & Barcode Scanning Logic with Spire.Barcode

The backend code reads the uploaded file into memory and processes it with Spire.Barcode, using either a memory stream or a file path. The scanned result is then returned. This implementation supports QR codes and other barcode types without requiring format-specific logic.

Index.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Barcode;

public class IndexModel : PageModel
{
    [BindProperty]
    public IFormFile Upload { get; set; }  // Uploaded file

    public string Result { get; set; }     // Scanning result
    public string UploadedImageBase64 { get; set; } // Base64 string for preview

    public void OnPost()
    {
        if (Upload != null && Upload.Length > 0)
        {
            using (var ms = new MemoryStream())
            {
                // Read the uploaded file into memory
                Upload.CopyTo(ms);

                // Convert the image to Base64 for displaying in HTML <img>
                UploadedImageBase64 = "data:" + Upload.ContentType + ";base64," +
                                      Convert.ToBase64String(ms.ToArray());

                // Reset the stream position before scanning
                ms.Position = 0;

                // Scan the barcode or QR code from the stream
                try
                {
                    string[] scanned = BarcodeScanner.Scan(ms);
                    // Return the scanned result
                    Result = scanned != null && scanned.Length > 0
                        ? string.Join(", ", scanned)
                        : "No code detected.";
                }
                catch (Exception ex)
                {
                    Result = "Error while scanning: " + ex.Message;
                }
            }
        }
    }
}

Explanation of Key Classes and Methods

  • BarcodeScanner: A static class in Spire.Barcode that decodes images containing QR codes or barcodes.
  • BarcodeScanner.Scan(Stream imageStream): Scans an uploaded image directly from a memory stream and returns an array of decoded strings. This method scans all barcodes in the given image.
  • Supplementary methods (optional):
    • BarcodeScanner.Scan(string imagePath): Scans an image from a file path.
    • BarcodeScanner.ScanInfo(string imagePath): Scans an image from a file path and returns additional barcode information such as type, location, and data.

These methods can be used in different ways, depending on the application requirements.

Frontend: QR & Barcode Upload & Scanning Result Interface

The following page design provides a simple upload form where users can submit an image containing a QR code or barcode. Once uploaded, the image is displayed along with the recognized result, which can be copied with a single click. The layout is intentionally kept minimal for fast testing, yet styled for a clear and polished presentation.

Index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "QR & Barcode Scanner";
}

<div style="max-width:420px;margin:40px auto;padding:20px;border:1px solid #ccc;border-radius:8px;background:#f9f9f9;">
    <h2>QR & Barcode Scanner</h2>
    <form method="post" enctype="multipart/form-data" id="uploadForm">
        <input type="file" name="upload" accept="image/*" required onchange="this.form.submit()" style="margin:10px 0;" />
    </form>

    @if (!string.IsNullOrEmpty(Model.UploadedImageBase64))
    {
        <div style="margin-top:15px;text-align:center;">
            <img src="/@Model.UploadedImageBase64" style="width:300px;height:300px;object-fit:contain;border:1px solid #ddd;background:#fff;" />
        </div>
    }

    @if (!string.IsNullOrEmpty(Model.Result))
    {
        <div style="margin-top:15px;padding:10px;background:#e8f5e9;border-radius:6px;">
            <b>Scan Result:</b>
            <p id="scanText">@Model.Result</p>
            <button type="button" onclick="navigator.clipboard.writeText(scanText.innerText)" style="background:#28a745;color:#fff;padding:6px 10px;border:none;border-radius:4px;">Copy</button>
        </div>
    }
</div>

Below is a screenshot showing the scan page after successfully recognizing both a QR code and a Code128 barcode, with the results displayed and a one-click copy button available.

ASP.NET Core QR code and Code128 barcode scan page with recognized results and copy button

This ASP.NET Core application can scan QR codes and other barcodes from uploaded images. If you're looking to generate QR codes or barcodes, check out How to Generate QR Codes in ASP.NET Core.


3. Testing and Troubleshooting

After running the application, test the scanning feature with:

  • A QR code image containing a URL or plain text.
  • A barcode image such as Code128 or EAN-13.

If recognition fails:

  • Ensure the image has good contrast and minimal distortion.
  • Use images of reasonable resolution (not excessively large or pixelated).
  • Test with different file formats such as JPG, PNG, or BMP.
  • Avoid images with reflections, glare, or low lighting.
  • When scanning multiple barcodes in one image, ensure each code is clearly separated to improve recognition accuracy.

A good practice is to maintain a small library of sample QR codes and barcodes to test regularly after making code changes.


4. Extending to Other .NET Applications

The barcode scanning logic in this tutorial works the same way across different .NET application types — only the way you supply the image file changes. This makes it easy to reuse the core decoding method, BarcodeScanner.Scan(), in various environments such as:

  • ASP.NET Core MVC controllers or Web API endpoints
  • Desktop applications like WinForms or WPF
  • Console utilities for batch processing

Example: Minimal ASP.NET Core Web API Endpoint — receives an image file via HTTP POST and returns decoded results as JSON:

[ApiController]
[Route("api/[controller]")]
public class ScanController : ControllerBase
{
    [HttpPost]
    public IActionResult Scan(IFormFile file)
    {
        if (file == null) return BadRequest("No file uploaded");
        using var ms = new MemoryStream();
        file.CopyTo(ms);
        ms.Position = 0;
        string[] results = BarcodeScanner.Scan(ms);
        return Ok(results);
    }
}

Example: Console application — scans a local image file and prints the decoded text:

string[] result = BarcodeScanner.Scan(@"C:\path\to\image.png");
Console.WriteLine(string.Join(", ", result));

This flexibility makes it simple for developers to quickly add QR code and barcode scanning to new projects or extend existing .NET applications.


5. Conclusion

This tutorial has shown how to implement a complete QR code and barcode scanning solution in ASP.NET Core using Spire.Barcode for .NET. From receiving uploaded images to decoding and displaying the results, the process is straightforward and adaptable to a variety of application types. With this approach, developers can quickly integrate reliable scanning functionality into e-commerce platforms, ticketing systems, document verification tools, and other business-critical web applications.

For more advanced scenarios, Spire.Barcode for .NET provides additional features such as customizing the recognition process, handling multiple image formats and barcode types, and more. Apply for a free trial license to unlock all the advanced features.

Download Spire.Barcode for .NET today and start building your own ASP.NET barcode scanning solution.

Generate QR Code in ASP.NET C# using Spire.Barcode for .NET – Tutorial Overview

QR codes have become a standard feature in modern web applications, widely used for user authentication, contactless transactions, and sharing data like URLs or contact information. For developers working with ASP.NET, implementing QR code generation using C# is a practical requirement in many real-world scenarios.

In this article, you’ll learn how to generate QR codes in ASP.NET using Spire.Barcode for .NET. We’ll walk through a complete example based on an ASP.NET Core Web App (Razor Pages) project, including backend logic and a simple UI to display the generated code. The same approach can be easily adapted to MVC, Web API, and Web Forms applications.

Article Overview


1. Project Setup and Dependencies

Prerequisites

To follow along, make sure you have:

  • Visual Studio 2019 or newer
  • .NET 6 or later
  • ASP.NET Core Web App (Razor Pages Template)
  • NuGet package: Spire.Barcode for .NET

Install Spire.Barcode for .NET

Install the required library using NuGet Package Manager Console:

Install-Package Spire.Barcode

Spire.Barcode is a fully self-contained .NET barcode library that supports in-memory generation of QR codes without external APIs. You can also use Free Spire.Barcode for .NET for smaller projects.


2. Generate QR Code in ASP.NET Using C#

This section describes how to implement QR code generation in an ASP.NET Core Web App (Razor Pages) project. The example includes a backend C# handler that generates the QR code using Spire.Barcode for .NET, and a simple Razor Page frontend for user input and real-time display.

Step 1: Add QR Code Generation Logic in PageModel

The backend logic resides in the Index.cshtml.cs file. It processes the form input, generates a QR code using Spire.Barcode, and returns the result as a Base64-encoded image string that can be directly embedded in HTML.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Barcode;

public class IndexModel : PageModel
{
    [BindProperty]
    public string InputData { get; set; }

    public string QrCodeBase64 { get; set; }

    public void OnPost()
    {
        if (!string.IsNullOrWhiteSpace(InputData))
        {
            QrCodeBase64 = GenerateQrCodeBase64(InputData);
        }
    }
    
    private string GenerateQrCodeBase64(string input)
    {
        var settings = new BarcodeSettings
        {
            Type = BarCodeType.QRCode,            // QR code type
            Data = input,                         // Main encoded data
            Data2D = input,                       // Required for 2D barcode, usually same as Data
            QRCodeDataMode = QRCodeDataMode.Byte, // Byte mode (supports multilingual content)
            QRCodeECL = QRCodeECL.M,              // Medium error correction (15%)
            X = 3,                                // Module size (affects image dimensions)
            ShowText = false,                     // Hide default barcode text
            ShowBottomText = true,                // Show custom bottom text
            BottomText = input                    // Bottom text to display under the QR code
        };

        var generator = new BarCodeGenerator(settings);
        using var ms = new MemoryStream();
        var qrImage = generator.GenerateImage();
        qrImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return Convert.ToBase64String(ms.ToArray());
    }
}

Key Components:

  • BarcodeSettings: Specifies the QR code's core configuration, such as type (QRCode), data content, encoding mode, and error correction level.

  • BarCodeGenerator: Takes the settings and generates the QR code image as a System.Drawing.Image object using the GenerateImage() method.

  • Base64 Conversion: Converts the image to a Base64 string so it can be directly embedded into the HTML page without saving to disk.

This approach keeps the entire process in memory, making it fast, portable, and suitable for serverless or cloud-hosted applications.

Step 2: Create the Razor Page for User Input and QR Code Display and Download

The following Razor markup in the Index.cshtml file defines a form for entering text or URLs, displays the generated QR code upon submission, and provides a button to download the QR code image.

@page
@model IndexModel
@{
    ViewData["Title"] = "QR Code Generator";
}

<h2>QR Code Generator</h2>

<form method="post">
    <label for="InputData">Enter text or URL:</label>
    <input type="text" id="InputData" name="InputData" style="width:300px;" required />
    <button type="submit">Generate QR Code</button>
</form>

@if (!string.IsNullOrEmpty(Model.QrCodeBase64))
{
    <div style="margin-top:20px">
        <img src="data:image/png;base64,@Model.QrCodeBase64" alt="QR Code" />
        <br />
        <a href="data:image/png;base64,@Model.QrCodeBase64" download="qrcode.png">Download QR Code</a>
    </div>
}

The Base64-encoded image is displayed directly in the browser using a data: URI. This eliminates the need for file storage and allows for immediate rendering and download.

The following screenshot shows the result after submitting text input.

Generated QR Code displayed on Razor Page in ASP.NET Core

If you need to scan QR codes instead, please refer to How to Scan QR Codes in C#.


3. Customize QR Code Output

Spire.Barcode provides several customization options through the BarcodeSettings class to control the appearance and behavior of the generated QR code:

Property Function Example
QRCodeDataMode Text encoding mode QRCodeDataMode.Byte
QRCodeECL Error correction level QRCodeECL.H (high redundancy)
X Module size (resolution) settings.X = 6
ImageWidth/Height Control dimensions of QR image settings.ImageWidth = 300
ForeColor Set QR code color settings.ForeColor = Color.Blue
ShowText Show or hide text below barcode settings.ShowText = false
BottomText Custom text to display below barcode settings.BottomText = "Scan Me"
ShowBottomText Show or hide the custom bottom text settings.ShowBottomText = true
QRCodeLogoImage Add a logo image to overlay at QR code center settings.QRCodeLogoImage = System.Drawing.Image.FromFile("logo.png");

These properties help you tailor the appearance of your QR code for branding, readability, or user interaction purposes.

To explore more QR code settings, refer to the BarcodeSettings API reference.


4. Apply Logic in MVC, Web API, and Web Forms

The same QR code generation logic used in Razor Pages can also be reused in other ASP.NET frameworks such as MVC, Web API, and Web Forms.

MVC Controller Action

In an MVC project, you can add a Generate action in a controller (e.g., QrController.cs) to generate and return the QR code image directly:

public class QrController : Controller
{
    public ActionResult Generate(string data)
    {
        var settings = new BarcodeSettings
        {
            Type = BarCodeType.QRCode,
            Data = data,
            QRCodeDataMode = QRCodeDataMode.Byte,
            QRCodeECL = QRCodeECL.M,
            X = 5
        };

        var generator = new BarCodeGenerator(settings);
        using var ms = new MemoryStream();
        generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return File(ms.ToArray(), "image/png");
    }
}

This method returns the QR code as a downloadable PNG file, ideal for server-side rendering.

Web API Endpoint

For Web API, you can define a GET endpoint in a controller such as QrApiController.cs that responds with the generated image stream:

[ApiController]
[Route("api/[controller]")]
public class QrApiController : ControllerBase
{
    [HttpGet("generate")]
    public IActionResult GetQr(string data)
    {
        var settings = new BarcodeSettings
        {
            Type = BarCodeType.QRCode,
            Data = data
        };

        var generator = new BarCodeGenerator(settings);
        using var ms = new MemoryStream();
        generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return File(ms.ToArray(), "image/png");
    }
}

This approach is suitable for frontends built with React, Vue, Angular, or any JavaScript framework.

Web Forms Code-Behind

In ASP.NET Web Forms, you can handle QR code generation in the code-behind of a page like Default.aspx.cs:

protected void btnGenerate_Click(object sender, EventArgs e)
{
    var settings = new BarcodeSettings
    {
        Type = BarCodeType.QRCode,
        Data = txtInput.Text
    };

    var generator = new BarCodeGenerator(settings);
    using var ms = new MemoryStream();
    generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    imgQR.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}

The generated image is embedded directly into an asp:Image control using a Base64 data URI.


5. Conclusion

With Spire.Barcode for .NET, you can seamlessly generate and customize QR codes across all ASP.NET project types — Razor Pages, MVC, Web API, or Web Forms. The solution is fully offline, fast, and requires no third-party API.

Returning images as Base64 strings simplifies deployment and avoids file management. Whether you're building authentication tools, ticketing systems, or contact sharing, this approach is reliable and production-ready.


FAQs

Q: Does Spire.Barcode support Unicode characters like Chinese or Arabic?

A: Yes. Use QRCodeDataMode.Byte for full Unicode support.

Q: Can I adjust QR code size and color?

A: Absolutely. Use properties like X, ForeColor, and ImageWidth.

Q: Is this solution fully offline?

A: Yes. It works without any external API calls or services.

Q: Can I expose this QR logic via API?

A: Yes. Use ASP.NET Web API to serve generated images to client apps.

Read QR code in C# – tutorial cover with barcode scanner and C# sample code

QR codes have become a common part of modern applications — from user authentication and digital payments to product packaging and event tickets. In many of these scenarios, developers often need to read QR codes in C# as part of their workflow, especially when working with image-based inputs like scanned documents or uploaded files.

To handle such tasks reliably, a decoding method that’s both accurate and easy to implement is essential. In this tutorial, we’ll walk through a straightforward approach to reading QR codes from images using C#, with minimal setup and clean integration.

Quick Navigation


1. Project Setup

To begin, we’ll use a .NET barcode library that supports QR code decoding. In this guide, we demonstrate with Spire.Barcode for .NET, which provides a simple API for reading QR codes from image files and streams.

1.1 Install the Library via NuGet

You can install the library through NuGet Package Manager:

Install-Package Spire.Barcode

For basic scenarios, you can also use Free Spire.Barcode for .NET:

Install-Package FreeSpire.Barcode

1.2 Create a New Console Project

For demonstration, create a C# Console App in Visual Studio:

  • Target .NET Framework, .NET Core/.NET 6+, ASP.NET, or Xamarin for cross-platform mobile development
  • Add reference to Spire.Barcode.dll (if not using NuGet)

2. Read QR Code from Image in C#

To read QR codes from an image file in C#, you can simply use the static BarcodeScanner.Scan() method provided by the library. This method takes an image path and the BarCodeType as input and returns all decoded results that match the specified barcode type — in this case, QR codes.

This method supports scanning images in formats like JPG, PNG, and EMF. It’s the most direct way to scan QR code data in desktop applications or backend services that receive uploaded files.

2.1 Sample Code: Decode QR Code from an Image File

using Spire.Barcode;

class Program
{
    static void Main(string[] args)
    {
        // Load the QR code image
        string imagePath = @"C:\qr-code.png";

        // Barcode scanner reads QR code from image file
        string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);

        // Display QR code result(s)
        foreach (string result in results)
        {
            Console.WriteLine("QR Code Data: " + result + "\n");
        }
    }
}

The QR code image and the scan results from C# code:

C# QR code scanner reading from image and showing decoded result in console

2.2 Explanation

  • Scan() reads and decodes all barcodes found in the image.
  • BarCodeType.QRCode ensures only QR codes are detected (you can change it to detect other types).
  • Returns an array in case the image contains multiple QR codes.

You may also like: How to Generate QR Codes Using C#


3. Read QR Code from Stream in C#

In web APIs or modern applications where images are processed in memory, you’ll often deal with Stream objects—such as when handling file uploads or reading from cloud storage.

The BarcodeScanner.Scan() method also accepts a Stream directly, allowing you to decode QR codes from memory streams without converting them to Bitmap.

using Spire.Barcode;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        using (FileStream fs = new FileStream(@"C:\qr-code.png", FileMode.Open, FileAccess.Read))
        {
            // Directly scan the QR codes from the image stream
            string[] results = BarcodeScanner.Scan(fs, BarCodeType.QRCode, false);
            foreach (string result in results)
            {
                Console.WriteLine("QR Code Data: " + result);
            }
        }
    }
}

This method is useful for WPF or ASP.NET Core apps that handle QR code images in memory.

Related article: Scan Barcodes from PDF Using C#


4. Improve Accuracy and Handle Errors

In real-world scenarios, QR code recognition may occasionally fail due to image quality or unexpected input issues. Here are best practices to improve decoding accuracy and handle failures in C#:

4.1 Boost Recognition Accuracy

  • Use high-resolution images. Avoid blurred or overcompressed files.
  • Ensure quiet zone (white space) around the QR code is preserved.
  • Use formats like PNG for better clarity.
  • Avoid perspective distortion — use straight, scanned images.

4.2 Add Robust Error Handling

Wrap your decoding logic in a try-catch block to prevent crashes and inform the user clearly:

try
{
    string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);

    if (results.Length == 0)
    {
        Console.WriteLine("No QR code found.");
    }
    else
    {
        Console.WriteLine("QR Code: " + results[0]);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Error decoding QR code: " + ex.Message);
}

5. Bonus: Get QR Code Coordinates

Sometimes, you may need to locate the QR code’s exact position in the image—for cropping, overlay, or annotation. The ScanInfo() method helps retrieve bounding boxes:

BarcodeInfo[] results = BarcodeScanner.ScanInfo(imagePath, BarCodeType.QRCode);
foreach (BarcodeInfo result in results)
{
    Console.WriteLine("Data: " + result.DataString);
    Console.WriteLine($"Coordinates: " + string.Join(",", result.Vertexes.Select(p => $"({p.X},{p.Y})")) + "\n");
}

This provides both the data and the coordinates of each detected QR code.

The reading results:

C# QR Code Reader getting QR code data and position form images


6. FAQ

How to read QR code in C#?

You can use the Spire.Barcode for .NET library and its BarcodeScanner.Scan() method to read QR codes from image files or memory streams in just a few lines of code.

How do I read my own QR code image?

Load your QR code image file path into the scanner, or open it as a stream if you're working in a web or WPF application. The scanner will decode all readable QR codes in the image.

How to read barcodes in C# (not just QR codes)?

You can simply pass the image path to the Scan() method, and it will automatically detect and read all supported barcode types. To restrict detection to a specific type (e.g., only QR codes or Code128), pass the corresponding BarCodeType as the second parameter.

What is the best barcode reader library for C#?

Spire.Barcode for .NET is a popular choice for its simplicity, format support, and clean API. It supports both free and commercial use cases.


7. Final Thoughts

Reading QR codes in C# can be implemented with just a few lines of code using Spire.Barcode for .NET. It supports image and stream-based decoding, works well for desktop, server-side, or WPF applications, and offers solid performance with minimal setup.

You can further explore QR code generation, document integration, and real-time scanning workflows based on this foundation.

Need to unlock full barcode reading features?

Request a free temporary license and try the full capabilities of Spire.Barcode for .NET without limitations.

read barcode from PDF in C# overview image

Reading barcodes from PDF in C# is a common requirement in document processing workflows, especially when dealing with scanned forms or digital PDFs. In industries like logistics, finance, healthcare, and manufacturing, PDFs often contain barcodes—either embedded as images or rendered as vector graphics. Automating this process can reduce manual work and improve accuracy.

This guide shows how to read barcode from PDF with C# using two practical methods: extracting images embedded in PDF pages and scanning them, or rendering entire pages as images and detecting barcodes from the result. Both techniques support reliable recognition of 1D and 2D barcodes in different types of PDF documents.

Table of Contents


Getting Started: Tools and Setup

To extract or recognize barcodes from PDF documents using C#, make sure your environment is set up correctly.

Here’s what you need:

  • Any C# project that supports NuGet package installation (such as .NET Framework, .NET Core, or .NET).
  • The following libraries, Spire.Barcode for .NET for barcode recognition and Spire.PDF for .NET for PDF processing, can be installed via NuGet Package Manager:
Install-Package Spire.Barcode
Install-Package Spire.PDF

Step-by-Step: Read Barcodes from PDF in C#

There are two ways to extract barcode data from PDF files. Choose one based on how the barcode is stored in the document.

Method 1: Extract Embedded Images and Detect Barcodes

This method is suitable for scanned PDF documents, where each page often contains a raster image with one or more barcodes. The BarcodeScanner.ScanOne() method can read one barcode from one image.

Code Example: Extract and Scan

using Spire.Barcode;
using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Drawing;

namespace ReadPDFBarcodeByExtracting
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load a PDF file
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Sample.pdf");

            // Get a page and the image information on the page
            PdfPageBase page = pdf.Pages[0];
            PdfImageHelper imageHelper = new PdfImageHelper();
            PdfImageInfo[] imagesInfo = imageHelper.GetImagesInfo(page);

            // Loop through the image information
            int index = 0;
            foreach (PdfImageInfo imageInfo in imagesInfo)
            {
                // Get the image as an Image object
                Image image = imageInfo.Image;
                // Scan the barcode and output the result
                string scanResult = BarcodeScanner.ScanOne((Bitmap)image);
                Console.WriteLine($"Scan result of image {index + 1}:\n" + scanResult + "\n");
                index++;
            }
        }
    }
}

The following image shows a scanned PDF page and the barcode recognition result using Method 1 (extracting embedded images):

Extract barcode from embedded image in PDF using C#

When to use: If the PDF is a scan or contains images with embedded barcodes.

You may also like: Generate Barcodes in C# (QR Code Example)

Method 2: Render Page as Image and Scan

When barcodes are drawn using vector elements (not embedded images), you can render each PDF page as a bitmap and perform barcode scanning on it. The BarcodeScanner.Scan() method can read multiple barcodes from one image.

Code Example: Render and Scan

using Spire.Barcode;
using Spire.Pdf;
using System.Drawing;

namespace ReadPDFBarcodeByExtracting
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load a PDF file
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Sample.pdf");

            // Save each page as an image
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                Image image = pdf.SaveAsImage(i);
                // Read the barcodes on the image
                string[] scanResults = BarcodeScanner.Scan((Bitmap)image);
                // Output the results
                for (int j = 0; j < scanResults.Length; j++)
                {
                    Console.WriteLine($"Scan result of barcode {j + 1} on page {i + 1}:\n" + scanResults[j] + "\n");
                }
            }
        }
    }
}

Below is the result of applying Method 2 (rendering full PDF page) to detect vector barcodes on the page:

Scan barcode from vector-rendered PDF page using C#

When to use: When barcodes are drawn on the page directly, not embedded as image elements.

Related article: Convert PDF Pages to Images in C#


Which Method Should You Use?

Use Case Recommended Method
Scanned pages or scanned barcodes Extract embedded images
Digital PDFs with vector barcodes Render full page as image
Hybrid or unknown structure Try both methods optionally

You can even combine both methods for maximum reliability when handling unpredictable document structures.


Real-World Use Cases

Here are some typical scenarios where barcode recognition from PDFs in C# proves useful:

  • Logistics automation Extract tracking numbers and shipping IDs from scanned labels, dispatch forms, or signed delivery receipts in bulk.

  • Invoice and billing systems Read barcode-based document IDs or payment references from digital or scanned invoices in batch processing tasks.

  • Healthcare document digitization Automatically scan patient barcodes from lab reports, prescriptions, or admission forms in PDF format.

  • Manufacturing and supply chain Recognize barcodes from packaging reports, quality control sheets, or equipment inspection PDFs.

  • Educational institutions Process barcoded student IDs on scanned test forms or attendance sheets submitted as PDFs.

Tip: In many of these use cases, PDFs come from scanners or online systems, which may embed barcodes as images or page content—both cases are supported with the two methods introduced above.


Conclusion

Reading barcodes from PDF files in C# can be achieved reliably using either image extraction or full-page rendering. Whether you need to extract a barcode from a scanned document or recognize one embedded in PDF content, both methods provide flexible solutions for barcode recognition in C#.


FAQ

Q: Does this work with multi-page PDFs?
Yes. You can loop through all pages in the PDF and scan each one individually.

Q: Can I extract multiple barcodes per page?
Yes. The BarcodeScanner.Scan() method can detect and return all barcodes found on each image.

Q: Can I improve recognition accuracy by increasing resolution?
Yes. When rendering a PDF page to an image, you can set a higher DPI using PdfDocument.SaveAsImage(pageIndex: int, PdfImageType.Bitmap: PdfImageType, dpiX: int, dpiY: int). For example, 300 DPI is ideal for small or low-quality barcodes.

Q: Can I read barcodes from PDF using C# for free?
Yes. You can use Free Spire.Barcode for .NET and Free Spire.PDF for .NET to read barcodes from PDF files in C#. However, the free editions have feature limitations, such as page count or supported barcode types. If you need full functionality without restrictions, you can request a free temporary license to evaluate the commercial editions.

When generating a QR code, you might want to add a custom image such as your company’s logo or your personal profile image to it. In this article, you will learn how to achieve this task programmatically in C# and VB.NET using Spire.Barcode for .NET library.

Install Spire.Barcode for .NET

To begin with, you need to add the DLL files included in the Spire.Barcode for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Barcode

Note: This feature relies on a commercial license. If you want to test it, please go to the end of this article to request a temporary license.

Generate QR Code with a Logo Image in C# and VB.NET

The following are the steps to generate a QR code with a logo image:

  • Create a BarcodeSettings object.
  • Set barcode type, error correction level and data etc. using BarcodeSettings.Type, BarcodeSettings.QRCodeECL and BarcodeSetting.Data properties.
  • Set logo image using BarcodeSettings.QRCodeLogoImage property.
  • Create a BarCodeGenerator object based on the settings.
  • Generate QR code image using BarCodeGenerator.GenerateImage() method.
  • Save the image using Image.Save() method.
  • C#
  • VB.NET
using Spire.Barcode;
using Spire.License;
using System.Drawing;

namespace AddLogoToQR
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load license
            Spire.License.LicenseProvider.SetLicenseFileFullPath("license.elic.xml");

            //Create a BarcodeSettings object
            BarcodeSettings settings = new BarcodeSettings();

            //Set barcode type, error correction level, data, etc.
            settings.Type = BarCodeType.QRCode;
            settings.QRCodeECL = QRCodeECL.M;
            settings.ShowText = false;
            settings.X = 2.5f;
            string data = "www.e-iceblue.com";
            settings.Data = data;
            settings.Data2D = data;

            //Set logo image
            settings.QRCodeLogoImage = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");

            //Generate QR image based on the settings
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            Image image = generator.GenerateImage();
            image.Save("QR.png", System.Drawing.Imaging.ImageFormat.Png);
        }
    }
}

C#/VB.NET: Generate QR Code with a Logo Image

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

How to Create EAN-13 Barcode in C#

2017-11-27 01:56:35 Written by Koohji

EAN-13, based upon the UPC-A standard, is used world-wide for marking retail goods. The 13-digit EAN-13 number consists of four components:

  • Country code - 2 or 3 digits
  • Manufacturer Code - 5 to 7 digits
  • Product Code - 3 to 5 digits
  • Check digit - last digit

The following code snippets demonstrate how to create EAN-13 barcode image using Spire.Barcode in C#.

Step 1: Create a BarcodeSettings instance.

BarcodeSettings settings = new BarcodeSettings();

Step 2: Set the barcode type as EAN13.

settings.Type = BarCodeType.EAN13;

Step 3: Set the data to encode.

settings.Data = "123456789012";

Step 4: Calculate checksum and add the check digit to barcode.

settings.UseChecksum = CheckSumMode.ForceEnable;

Step 5: Display barcode's text on bottom and centrally align the text.

settings.ShowTextOnBottom = true;
settings.TextAlignment = StringAlignment.Center;

Step 6: Generate barcode image based on the settings and save it in .png format.

BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();
image.Save("EAN-13.png", System.Drawing.Imaging.ImageFormat.Png);

Output:

How to Create EAN-13 Barcode in C#

Full Code:

using Spire.Barcode;
using System.Drawing;

namespace EAN-13
{
    class Program
    {
        static void Main(string[] args)
        {
            BarcodeSettings settings = new BarcodeSettings();
            settings.Type = BarCodeType.EAN13;
            settings.Data = "123456789012";
            settings.UseChecksum = CheckSumMode.ForceEnable;
            settings.ShowTextOnBottom = true;
            settings.TextAlignment = StringAlignment.Center;
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            Image image = generator.GenerateImage();
            image.Save("EAN-13.png", System.Drawing.Imaging.ImageFormat.Png);
        }
    }
}

How to Create DataMatrix Barcode in C#

2017-11-17 07:15:23 Written by Koohji

A DataMatrix code is a two-dimensional barcode consisting of black and white "cells" or modules arranged in either a square or rectangular pattern. The information to be encoded can be text or numeric data.

Following code snippets show how to create a DataMatrix barcode image using Spire.Barcode.

Step 1: Create a BarcodeSettings instance.

BarcodeSettings settings = new BarcodeSettings();

Step 2: Set the width of barcode module

settings.X = 2;

Step 3: Set the barcode type as DataMatrix.

settings.Type = BarCodeType.DataMatrix;

Step 4: Set the data and display text

settings.Data = "ABC 123456789ABC 123456789ABC 123456789";
settings.Data2D = "ABC 123456789ABC 123456789ABC 123456789";

Step 5: Set the DataMatrix symbol shape to square.

settings.DataMatrixSymbolShape = DataMatrixSymbolShape.Square;

Step 6: Generate barcode image based on the settings and save it in .png format.

BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();
image.Save("DataMatrix.png", System.Drawing.Imaging.ImageFormat.Png);

How to Create DataMatrix Barcode in C#

To create a rectangular DataMatrix barcode, set the DataMatrixSymbolShape property to Rectangle.

settings.DataMatrixSymbolShape = DataMatrixSymbolShape.Rectangle;

How to Create DataMatrix Barcode in C#

Full Code:

using Spire.Barcode;
using System.Drawing;

namespace DataMatrix
{
    class Program
    {
        static void Main(string[] args)
        {
            BarcodeSettings settings = new BarcodeSettings();
            settings.Type = BarCodeType.DataMatrix;
            settings.X = 1.5f;
            settings.DataMatrixSymbolShape = DataMatrixSymbolShape.Square;
            //rectangular DataMatrix barcode
            //settings.DataMatrixSymbolShape = DataMatrixSymbolShape.Rectangle;  
            settings.Data = "ABC 123456789ABC 123456789ABC 123456789";
            settings.Data2D = "ABC 123456789ABC 123456789ABC 123456789";
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            Image image = generator.GenerateImage();
            image.Save("DataMatrix.png", System.Drawing.Imaging.ImageFormat.Png);
        }
    }
}

How to Scan Barcode in C#

2017-06-28 08:40:26 Written by Koohji

We have already demonstrated how to generate 1D barcode and 2D barcodes by using Spire.Barcode. This article will demonstrate how to scan the barcode images with Spire.Barcode. Spire.Barcode supports scanning the barcode image in .bmp, .png and .jpg image format. We will use Spire.Barcode to scan both 1D barcode and 2D barcode for example.

Scan Code39 barcode image:

string[] data = Spire.Barcode.BarcodeScanner.Scan("Code39.png",
Spire.Barcode.BarCodeType.Code39);

How to Scan Barcode in C#

Scan QRCode barcode image:

string[] data = Spire.Barcode.BarcodeScanner.Scan("QRCode.png", Spire.Barcode.BarCodeType.QRCode);

How to Scan Barcode in C#

How to Create PDF417 Barcode in C#

2017-06-16 06:20:53 Written by Koohji

The PDF417 barcode, also known as Portable Data File 417 or PDF417 Truncated, is a two-dimensional (2D), high-density symbology capable of encoding text, numbers, files and actual data bytes.

Compaction Modes

The data is encoded using one of three compaction modes: Text compaction mode, Binary compaction mode, and Numeric compaction mode.

  • Text: It allows encoding all printable ASCII characters, i.e. values from 32 to 126 inclusive in accordance with ISO/IEC 646, as well as selected control characters such as TAB (horizontal tab ASCII 9), LF (NL line feed, new line ASCII 10) and CR (carriage return ASCII 13).
  • Binary: It allows encoding all 256 possible 8-bit byte values. This includes all ASCII characters value from 0 to 127 inclusive and provides for international character set support.
  • Numeric: It allows efficient encoding of numeric data strings.
  • Auto: It switches between Text, Binary and Numeric modes in order to minimize the number of codewords to be encoded.

PDF417 Error Correction Levels

Error correction allows the symbol to endure some damage without causing loss of data. The error correction level depends on the amount of data that needs to be encoded, the size and the amount of symbol damage that could occur. The error correction levels range from 0 to 8.

EC Level 0 1 2 3 4 5 6 7 8
EC Codewords Generated 2 4 6 8 16 32 64 128 512
Data Codewords 1-40 41-160 161-320 321-863
Data Bytes Encoded 1-56 57-192 193-384 385-1035

Following code snippets show how to create a PDF417 barcode image using Spire.Barcode.

Step 1: Create an instance of BarcodeSetting class.

BarcodeSettings settings = new BarcodeSettings();

Step 2: Set the barode type as Pdf417 and set the data to be encoded.

settings.Type = BarCodeType.Pdf417;
settings.Data = "123456789";

Step 3: Set the data mode as numeric.

settings.Pdf417DataMode = Pdf417DataMode.Numeric;

Step 4: Set the error correction level as level 2.

settings.Pdf417ECL = Pdf417ECL.Level2;

Step 5: Initialize an instance of BarcodeGenerator and generate an image based on the settings.

BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();   

Step 6: Save the image in .png format.

image.Save("PDF417Code.png");

Output:

How to Create PDF417 Barcode in C#

Full Code:

using Spire.Barcode;
using System.Drawing;

namespace PDF417Code
{
    class Program
    {
        static void Main(string[] args)
        {
            BarcodeSettings settings = new BarcodeSettings();
            settings.Type = BarCodeType.Pdf417;
            settings.Data = "123456789";
            settings.Data2D = "123456789";
            settings.Pdf417DataMode = Pdf417DataMode.Numeric;
            settings.Pdf417ECL = Pdf417ECL.Level2;
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            Image image = generator.GenerateImage();
            image.Save("PDF417Code.png");
        }
    }
}

C# QR Code Generating Guide

Generating QR codes with C# is a practical solution for many common development tasks—such as encoding URLs, login tokens, or product information. With the help of a .NET-compatible barcode library, you can quickly create scannable QR images and integrate them into your applications or documents.

This tutorial shows how to build a simple yet powerful C# QR code generator: from generating a QR code from a string, embedding a logo, to inserting the image into PDF, Word, and Excel files. It also covers usage in both Windows and ASP.NET applications, using clean and reusable C# code examples.

Quick Navigation


1. How QR Code Generation Works in C#

Before diving into the code, it’s useful to understand what a QR code is. QR codes are 2D matrix barcodes that can encode URLs, text, contact info, and more. In C#, QR code generation involves three steps:

  1. Encode your content (usually a string)
  2. Configure QR code options (error correction, size, margin, etc.)
  3. Export the result as an image

In this tutorial, we use a simple .NET-compatible library Spire.Barcode for .NET to keep things straightforward and flexible.

Install Spire.Barcode for .NET via NuGet

PM> Install-Package Spire.Barcode

You can also choose Free Spire.Barcode for .NET for smaller tasks:

PM> Install-Package FreeSpire.Barcode

2. Generate QR Code from String in C#

Let’s start with a basic example: generating a QR code from a string in C#. Using the BarcodeSettings and BarCodeGenerator classes provided by Spire.Barcode for .NET, you can easily encode any text or URL into a scannable QR code.

The key steps include:

  • Defining QR code content and format using BarcodeSettings, including data string, error correction level, size, margin, and optional logo;
  • Generating the image via BarCodeGenerator, which produces a ready-to-use System.Drawing.Image object;
  • Saving or embedding the result in external documents or applications.

The following code demonstrates how to configure the QR code and export it as a PNG image.

using Spire.Barcode;
using System.Drawing;
using System.Drawing.Imaging;

namespace GenerateQRCode
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize barcode settings
            BarcodeSettings settings = new BarcodeSettings();
            // Specify the barcode type as QR Code
            settings.Type = BarCodeType.QRCode;
            // Set the QR code data
            settings.Data = "https://www.example.com/";
            // Set the text to display (optional)
            settings.Data2D = "Scan to go to example.com";
            settings.ShowTextOnBottom = true;
            settings.TextFont = new Font(FontFamily.GenericSansSerif, 16.0f);

            // Set data mode and error correction level
            settings.QRCodeDataMode = QRCodeDataMode.Auto;
            settings.QRCodeECL = QRCodeECL.H;
            // (Optional) Embed a logo image in the QR code
            settings.QRCodeLogoImage = Image.FromFile("Logo.png");
            // Set the width of bar module
            settings.X = 3.0f;

            // Generate the QR code image
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            // Generate the QR code image
            Image qr = generator.GenerateImage();
            // Save the image to a file
            qr.Save("QR Code.png", ImageFormat.Png);
        }
    }
}

You can change the settings.Data to encode any text or URL. To embed a logo, use QRCodeLogoImage with a local image path. Error correction level H ensures that the QR code remains scannable even with a logo.

The QR code generated using C#:

QR Code Image Generated Using C#

You may also like: How to Scan QR Code Using C#


3. Insert QR Codes into Documents (PDF, Word, Excel)

A common use case for a c# qr generator is embedding QR codes into documents—automatically generating reports, receipts, or certificates. The generated QR image can be inserted into files using standard .NET Office libraries.

Insert into PDF

PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.AppendPage();

page.Canvas.DrawImage(PdfImage.FromImage(qr), 100, 400, 100, 100);

pdf.SaveToFile("output.pdf");

Use cases: digital invoices, shipping labels, authentication docs.

Insert into Word Document

Document doc = new Document();
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();

DocPicture picture = para.AppendPicture(qr);

doc.SaveToFile("output.docx", FileFormat.Docx);

Use cases: contracts, personalized letters, ID cards.

Insert into Excel Worksheet

Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];

sheet.Pictures.Add(2, 2, qr);  // Cell C3

book.SaveToFile("output.xlsx", ExcelVersion.Version2016);

Use cases: customer records, product sheets, logistics tracking.

Recommended article: Read Barcodes from PDF Documents


4. QR Code Generator in Windows and Web Applications

Windows Application

In a Windows Forms app, you can display the generated QR image in a PictureBox, and allow users to save it. This is useful for desktop-based systems like check-in kiosks or internal tools.

pictureBox1.Image = qr;

ASP.NET Web Application

In ASP.NET, return the QR image in a memory stream:

MemoryStream ms = new MemoryStream();
qr.Save(ms, ImageFormat.Png);
return File(ms.ToArray(), "image/png");

These approaches are lightweight and do not depend on heavy frameworks.


FAQ

Q: How to generate a QR code in .NET C# by code? A: Use a barcode library like Spire.Barcode for .NET. Simply define your QR code content, set the desired options (e.g., error correction level, logo image), and export it as an image. It's straightforward to integrate into C# applications.

Q: What is the best QR code generator for C#? A: There are several good options available. Spire.Barcode for .NET is a solid choice—it supports multiple barcode formats, allows logo insertion, and integrates well with Office documents.

Q: Can I adjust the size and layout of the generated QR code? A: Yes. You can modify properties like X, LeftMargin, and TopMargin to control the module size and spacing around the QR code.

Q: How can I use the generated QR code in documents or applications? A: The generated image can be embedded into PDFs, Word documents, Excel sheets, or displayed in Windows Forms or ASP.NET pages. This makes it useful in reports, labels, and web systems.


Conclusion

Creating a QR code generator in C# is simple yet highly effective. This tutorial demonstrated how to generate QR codes with a few lines of C# code, insert them into documents, and deploy them in both desktop and web environments. You can further expand on this by exploring batch generation, QR styling, or integrating scanning features in future enhancements.

To try it yourself, you can apply for a free temporary license here to unlock the full capabilities of Spire.Barcode for .NET.

page