Spire.Office Knowledgebase Page 11 | E-iceblue

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.

Java Examples of Reading Barcodes from Image

Barcodes are widely used in various industries for inventory management, retail, logistics, and more. Reading barcodes efficiently is crucial for automating data entry and improving accuracy. In Java, one of the most reliable libraries for barcode recognition is Spire.Barcode for Java. This article provides a comprehensive guide on how to read barcode in Java using this powerful library.

Table of Contents

Introduction to Spire.Barcode for Java

Spire.Barcode for Java is a robust library designed to generate and read barcodes in Java applications. It supports a wide range of barcode symbologies, including:

  • 1D Barcodes : Code 128, Code 39, EAN-13, UPC-A, etc.
  • 2D Barcodes : QR Code, DataMatrix, PDF417, etc.

Spire.Barcode provides fast and precise barcode recognition in Java, whether scanning from a dedicated barcode image or a complex image containing additional elements.

Key Features of Spire.Barcode

Before diving into implementation, let’s explore some key features of Spire.Barcode:

  • Multi-Format Support : Read barcodes from PNG, JPG, BMP, GIF, and TIFF images.
  • Batch Processing : Scan multiple barcodes in a single image.
  • High Recognition Accuracy : Advanced algorithms ensure reliable barcode detection.
  • Customizable Settings : Adjust scan regions and barcode types for optimized recognition.
  • Cross-Platform Compatibility : Works seamlessly on Windows, Linux, and macOS.

These features make Spire.Barcode an excellent choice for enterprise-level barcode processing.

Setting Up Spire.Barcode in Your Java Project

To start reading barcodes in Java, you need to integrate Spire.Barcode into your project. Follow these steps:

Step 1: Install the Library

If you're using Maven, you can easily integrate Spire.Barcode by adding the following dependency to your pom.xml file:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.barcode</artifactId>
    <version>5.1.11</version>
</dependency>

For manual setup, download Spire.Barcode for Java from our website and add the downloaded .jar file to your project’s build path.

Step 2: Get a Temporary License

Spire.Barcode requires a license to read certain barcode types. To unlock full barcode recognition capabilities, get a free 30-day trial license. After receiving the license file, apply it using this code:

LicenseProvider.setLicenseKey("your license key");

Now, you're ready to read barcode in Java using Spire.Barcode.

Reading a Single Barcode from an Image File

Reading one barcode from an image is a fundamental scenario, and Spire.Barcode facilitates this with just a few lines of code.

Here’s a step-by-step example:

import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ReadBarcode {

    public static void main(String[] args) throws IOException {
        
        // Apply license key to remove restrictions on barcode types
        LicenseProvider.setLicenseKey("your license key");

        // Load the image file containing the barcode
        BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcode.jpg "));

        // Scan the barcode from the loaded image
        String result = BarcodeScanner.scanOne(bufferedImage);

        // Output the scanned barcode result
        System.out.print(result);
    }
}

Explanation

  • ImageIO.read() loads the image file, supporting extensions such as .png, .jpeg, .bmp, or .gif.
  • BarcodeScanner.scanOne() detects and decodes the barcode from the image.
  • The decoded result is stored in a String .

Note

The scanOne() method and the scan() method, which will be discussed later, can accept not only a BufferedImage as a parameter but also an InputStream and a String representing the image file path. Whether you're processing images from disk, user uploads, or real-time streams, this flexibility simplifies integration into diverse workflows.

Output:

Read a single barcode from an image and print out the result.

Reading Multiple Barcodes from One Image

Spire.Barcode can detect and decode multiple barcodes in a single image. Here’s how:

import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class ReadMultipleBarcodes {

    public static void main(String[] args) throws IOException {

        // Apply license key to remove restrictions on barcode types
        LicenseProvider.setLicenseKey("your license key");

        // Load the image file containing the barcode
        BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcodes.jpg"));

        // Scan the barcode from the loaded image
        String[] results = BarcodeScanner.scan(bufferedImage);

        // Output the results
        System.out.println(Arrays.toString(results));
    }
}

Explanation

  • BarcodeScanner.scan() identifies and decodes all the barcodes present in the image.
  • The results are stored in a String array .

Output:

Read multiple barcodes from one image and print out the results.

Customizing Barcode Recognition Settings

For improved accuracy, Spire.Barcode allows you to customize scan settings, such as defining a scan region or specifying a particular barcode type. This enhanced approach ensures you have the flexibility and control needed for effective barcode scanning in Java.

Here is an example:

import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CustomScanSettings {

    public static void main(String[] args) throws IOException {

        // Apply license key to remove restrictions on barcode types
        LicenseProvider.setLicenseKey("your license key");

        // Load the image file containing the barcode
        BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcodes.jpg"));

        // Define a rectangle area for barcode recognition
        Rectangle rectangle = new Rectangle(0,0,380,270);

        // Scan the barcode from the loaded image
        String[] results = BarcodeScanner.scan(bufferedImage, rectangle, BarCodeType.Code_93);

        // Output the first result
        System.out.print(results[0]);
    }
}

Explanation

  • Rectangle() defines a specific area within the image for barcode recognition.
  • BarCodeType enumeration allows you to specify the barcode type for more accurate detection.

Output:

Read barcodes from the specified area of an image.

Conclusion

In this article, we've explored the essential steps to set up Spire.Barcode in your Java project, read barcodes from images , handle multiple barcodes , and customize recognition settings for optimal accuracy. By leveraging these capabilities, developers can seamlessly integrate barcode scanning into their applications, improving data entry automation and reducing errors.

With Spire.Barcode, you have a reliable tool at your disposal to meet your barcode reading needs, paving the way for more efficient business operations.

FAQs

Q1. What types of barcodes can Spire.Barcode read?

Spire.Barcode supports 38+ barcode types, including both 1D barcodes like Code 128, Code 39, EAN-13, and UPC-A, as well as 2D barcodes such as QR Code, DataMatrix, and PDF417.

Q2. Can I customize the barcode scanning region?

Yes, Spire.Barcode allows you to define a specific scan area within the image by using a Rectangle object. This feature helps improve accuracy by focusing on a designated section of the image.

Q3. Can Spire.Barcode read multiple barcodes from a single image?

Yes! Using BarcodeScanner.scan(), you can detect and decode multiple barcodes in one image efficiently.

Q4. Is a license required to use Spire.Barcode for barcode recognition?

A commercial license is needed for full functionality, but you can get a free 30-day trial license to test all features before purchasing.

Q5. Can I use Spire.Barcode for Java to create barcodes?

Yes, Spire.Barcode supports generating over 38 commonly used 1D and 2D barcodes. For more information, check out: How to Create Barcode in Java

Python Examples to Read Word DOC and DOCX Files

Reading Word documents in Python is a common task for developers who work with document automation, data extraction, or content processing. Whether you're working with modern .docx files or legacy .doc formats, being able to open, read, and extract content like text, tables, and images from Word files can save time and streamline your workflows.

While many Python libraries support .docx, reading .doc files—the older binary format—can be more challenging. Fortunately, there are reliable methods for handling both file types in Python.

In this tutorial, you'll learn how to read Word documents (.doc and .docx) in Python using the Spire.Doc for Python library. We'll walk through practical code examples to extract text, images, tables, comments, lists, and even metadata. Whether you're building an automation script or a full document parser, this guide will help you work with Word files effectively across formats.

Table of Contents

Why Read Word Documents Programmatically in Python?

Reading Word files using Python allows for powerful automation of content processing tasks, such as:

  • Extracting data from reports, resumes, or forms.
  • Parsing and organizing content into databases or dashboards.
  • Converting or analyzing large volumes of Word documents.
  • Integrating document reading into web apps, APIs, or back-end systems.

Programmatic reading eliminates manual copy-paste workflows and ensures consistent and scalable results.

Install the Library for Parsing Word Documents in Python

To read .docx and .doc files in Python, you need a library that can handle both formats. Spire.Doc for Python is a versatile and easy-to-use library that lets you extract text, images, tables, comments, lists, and metadata from Word documents. It runs independently of Microsoft Word, so Office installation is not required.

To get started, install Spire.Doc easily with pip:

pip install Spire.Doc

Read Text from Word DOC or DOCX in Python

Extracting text from Word documents is a common requirement in many automation and data processing tasks. Depending on your needs, you might want to read the entire content or focus on specific sections or paragraphs. This section covers both approaches.

Get Text from Entire Document

When you need to retrieve the complete textual content of a Word document — for tasks like full-text indexing or simple content export — you can use the Document.GetText() method. The following example demonstrates how to load a Word file, extract all text, and save it to a file:

from spire.doc import *

# Load the Word .docx or .doc file
document = Document()
document.LoadFromFile("sample.docx")

# Get all text
text = document.GetText()

# Save to a text file
with open("extracted_text.txt", "w", encoding="utf-8") as file:
    file.write(text)

document.Close()

Python Example to Retrieve All Text from Word Documents

Get Text from Specific Section or Paragraph

Many documents, such as reports or contracts, are organized into multiple sections. Extracting text from a specific section enables targeted processing when you need content from a particular part only. By iterating through the paragraphs of the selected section, you can isolate the relevant text:

from spire.doc import *

# Load the Word .docx or .doc file
document = Document()
document.LoadFromFile("sample.docx")

# Access the desired section
section = document.Sections[0]

# Get text from the paragraphs of the section
with open("paragraphs_output.txt", "w", encoding="utf-8") as file:
    for paragraph in section.Paragraphs:
        file.write(paragraph.Text + "\n")

document.Close()

Read Specific Elements from a Word Document in Python

Beyond plain text, Word documents often include rich content like images, tables, comments, lists, metadata, and more. These elements can easily be programmatically accessed and extracted.

Extract Images

Word documents often embed images like logos, charts, or illustrations. To extract these images:

  • Traverse each paragraph and its child objects.
  • Identify objects of type DocPicture.
  • Retrieve the image bytes and save them as separate files.
from spire.doc import *
import os

# Load the Word document
document = Document()
document.LoadFromFile("sample.docx")

# Create a list to store image byte data
images = []

# Iterate over sections
for s in range(document.Sections.Count):
    section = document.Sections.get_Item(s)

    # Iterate over paragraphs
    for p in range(section.Paragraphs.Count):
        paragraph = section.Paragraphs.get_Item(p)

        # Iterate over child objects
        for c in range(paragraph.ChildObjects.Count):
            obj = paragraph.ChildObjects[c]
            # Extract image data
            if isinstance(obj, DocPicture):
                picture = obj
                # Get image bytes
                dataBytes = picture.ImageBytes
                # Store in the list
                images.append(dataBytes)

# Create the output directory if it doesn't exist
output_folder = "ExtractedImages"
os.makedirs(output_folder, exist_ok=True)

# Save each image from byte data
for i, item in enumerate(images):
    fileName = f"Image-{i+1}.png"
    with open(os.path.join(output_folder, fileName), 'wb') as imageFile:
        imageFile.write(item)

# Close the document
document.Close()

Python Example to Extract Images from Word Documents

Get Table Data

Tables organize data such as schedules, financial records, or lists. To extract all tables and their content:

  • Loop through tables in each section.
  • Loop through rows and cells in each table.
  • Traverse over each cell’s paragraphs and combine their texts.
  • Save the extracted table data in a readable text format.
from spire.doc import *
import os

# Load the Word document
document = Document()
document.LoadFromFile("tables.docx")

# Ensure output directory exists
output_dir = "output/Tables"
os.makedirs(output_dir, exist_ok=True)

# Loop through each section
for s in range(document.Sections.Count):
    section = document.Sections.get_Item(s)
    tables = section.Tables

    # Loop through each table in the section
    for i in range(tables.Count):
        table = tables.get_Item(i)
        table_data = ""

        # Loop through each row
        for j in range(table.Rows.Count):
            row = table.Rows.get_Item(j)

            # Loop through each cell
            for k in range(row.Cells.Count):
                cell = row.Cells.get_Item(k)
                cell_text = ""

                # Combine text from all paragraphs in the cell
                for p in range(cell.Paragraphs.Count):
                    para_text = cell.Paragraphs.get_Item(p).Text
                    cell_text += para_text + " "

                table_data += cell_text.strip()

                # Add tab between cells (except after the last cell)
                if k < row.Cells.Count - 1:
                    table_data += "\t"
            table_data += "\n"

        # Save the table data to a separate text file
        output_path = os.path.join(output_dir, f"WordTable_{s+1}_{i+1}.txt")
        with open(output_path, "w", encoding="utf-8") as output_file:
            output_file.write(table_data)

# Close the document
document.Close()

Python Example to Get Table Data from Word Documents

Read Lists

Lists are frequently used to structure content in Word documents. This example identifies paragraphs formatted as list items and writes the list marker together with the text to a file.

from spire.doc import *

# Load the Word document
document = Document()
document.LoadFromFile("sample.docx")

# Open a text file for writing the list items
with open("list_items.txt", "w", encoding="utf-8") as output_file:

    # Iterate over sections
    for s in range(document.Sections.Count):
        section = document.Sections.get_Item(s)

        # Iterate over paragraphs
        for p in range(section.Paragraphs.Count):
            paragraph = section.Paragraphs.get_Item(p)

            # Check if the paragraph is a list
            if paragraph.ListFormat.ListType != ListType.NoList:
                # Write the combined list marker and paragraph text to file
                output_file.write(paragraph.ListText + paragraph.Text + "\n")

# Close the document
document.Close()

Extract Comments

Comments are typically used for collaboration and feedback in Word documents. This code retrieves all comments, including the author and content, and saves them to a file with clear formatting for later review or audit.

from spire.doc import *

# Load the Word .docx or .doc document
document = Document()
document.LoadFromFile("sample.docx")

# Open a text file to save comments
with open("extracted_comments.txt", "w", encoding="utf-8") as output_file:

    # Iterate over the comments
    for i in range(document.Comments.Count):
        comment = document.Comments.get_Item(i)

        # Write comment header with comment number
        output_file.write(f"Comment {i + 1}:\n")

        # Write comment author
        output_file.write(f"Author: {comment.Format.Author}\n")

        # Extract full comment text by concatenating all paragraph texts
        comment_text = ""
        for j in range(comment.Body.Paragraphs.Count):
            paragraph = comment.Body.Paragraphs[j]
            comment_text += paragraph.Text + "\n"

        # Write the comment text
        output_file.write(f"Content: {comment_text.strip()}\n")

        # Add a blank line between comments
        output_file.write("\n")

# Close the document
document.Close()

Retrieve Metadata (Document Properties)

Metadata provides information about the document such as author, title, creation date, and modification date. This code extracts common built-in properties for reporting or cataloging purposes.

from spire.doc import *

# Load the Word .docx or .doc document
document = Document()
document.LoadFromFile("sample.docx")

# Get the built-in document properties
props = document.BuiltinDocumentProperties

# Open a text file to write the properties
with open("document_properties.txt", "w", encoding="utf-8") as output_file:
    output_file.write(f"Title: {props.Title}\n")
    output_file.write(f"Author: {props.Author}\n")
    output_file.write(f"Subject: {props.Subject}\n")
    output_file.write(f"Created: {props.CreateDate}\n")
    output_file.write(f"Modified: {props.LastSaveDate}\n")

# Close the document
document.Close()

Conclusion

Reading both .doc and .docx Word documents in Python is fully achievable with the right tools. With Spire.Doc, you can:

  • Read text from the entire document, any section or paragraph.
  • Extract tables and process structured data.
  • Export images embedded in the document.
  • Extract comments and lists from the document.
  • Work with both modern and legacy Word formats without extra effort.

Try Spire.Doc today to simplify your Word document parsing workflows in Python!

FAQs

Q1: How do I read a Word DOC or DOCX file in Python?

A1: Use a Python library like Spire.Doc to load and extract content from Word files.

Q2: Do I need Microsoft Word installed to use Spire.Doc?

A2: No, it works without any Office installation.

Q3: Can I generate or update Word documents with Spire.Doc?

A3: Yes, Spire.Doc not only allows you to read and extract content from Word documents but also provides powerful features to create, modify, and save Word files programmatically.

Get a Free License

To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.

page 11