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#

C# Replace Text with Regular Expression

When working with Word templates, it's common to replace specific placeholders with real content—like names, dates, or even company logos. Manually updating each instance may take lots of effort and time. Fortunately, you can automate this process using code. In this tutorial, we'll show you how to use C# regex replace to find and replace text in Word documents. You'll learn how to apply regular expressions across the entire document, target specific paragraphs, and even replace matched text with images.

Before We Start: Install Word Library

To make this task easier, we recommend using Spire.Doc for .NET — a powerful Word library designed to automate common document operations such as reading, editing, and converting Word files. With Spire.Doc, performing a C# regex replace in Word documents can be done in just a few lines of code.

You can install the library via NuGet with the following command:

PM> Install-Package Spire.Doc

Alternatively, you can download the Spire.Doc package and install it with custom settings. A free version is also available, ideal for small projects or evaluation purposes.

Use Regex to Replace Text in an Entire Word Document

Let's start with the most common scenario — replacing text throughout the entire Word document. You can use regular expressions to match all patterns like #name or #tel, then replace them with actual values such as a person's name or phone number.

With the help of the Document.Replace() method provided by Spire.Doc, this task becomes incredibly simple. Here's a step-by-step explanation along with sample code to show how to replace text using regex in C#.

Code example - replacing #name with "May" in the entire Word document using C#:

using Spire.Doc;
using System.Text.RegularExpressions;
namespace FindText
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an object of Document class and load a Word document
            Document doc = new Document();
            doc.LoadFromFile("/input/replace template.docx");
            // Set the regular expression
            Regex regex = new Regex(@"#\w+\b");
            // Replace all matches with "May"
            doc.Replace(regex, "May");
            // Save the document
            doc.SaveToFile("/output/replacealloccurences.docx", FileFormat.Docx2013);
        }
    }
}

Here is a comparison preview of the results before and after using regex to replace text in C#: C# Regex Replace Text within an Entire Word Document

Steps Explained:

  • Create a Document instance and load a Word document from files.
  • Set the regular expression.
  • Replace all matches in the document with Documet.Replace() method.
  • Save the updated document.

Apply Regex Replace to a Specific Paragraph in C#

Replacing text across the entire document may seem straightforward, but how can we achieve the same result within a specific paragraph? When you need more precise control, such as performing regex replace only within a paragraph range, you can retrieve the paragraph text and reset its content manually. In code, this means using regular expressions to locate matches within the target paragraph, remove the original text, and insert the replacement.

Let’s first look at a real-world code example — we’ll break down the detailed steps right after.

Code example - replacing #name with "Lily" in the first paragraph using regular expression:

using Spire.Doc;
using Spire.Doc.Documents;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        // Create a Document object and load a template
        Document doc = new Document();
        doc.LoadFromFile("/input/replace template.docx");

        Regex regex = new Regex(@"#\w+\b");

        // Get the first paragraph
        Paragraph para = doc.Sections[0].Paragraphs[0];
        string originalText = para.Text;

        if (regex.IsMatch(originalText))
        {
            string newText = regex.Replace(originalText, "Lily");

            // Clear the content and append the new text
            para.ChildObjects.Clear(); 
            para.AppendText(newText);  
        }

        // Save the updated document
        doc.SaveToFile("/output/replacefirstpara.docx", FileFormat.Docx2013);
    }
}

Here is a before-and-after comparison of using regular expressions in C# to replace text in the first paragraph: Replace with Regex Using C# in a Specific Paragraph

Detailed steps explained:

  • Create a Document object and load the Word file.
  • Access the target paragraph using Sections[].Paragraphs[] property.
  • Get the original text from the paragraph.
  • Use a regular expression to find and replace matching text.
  • Clear the original content and append the updated text to the paragraph.
  • Save the modified document.

Replace Regex Matches with Images in Word Using C#

Now that we’ve covered how to replace text in the entire document or within a single paragraph, let’s move on to something more advanced—replacing text with images. This is often used in practical scenarios like generating reports or company brochures. For instance, you might want to replace a placeholder such as [logo] with your company’s actual logo.

With the help of C# regex replace and Spire.Doc’s image insertion APIs, this task can also be automated. Let’s take a look at a real code example first, then we’ll explain how it works.

Code example – replacing [avatar] with an image:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Text.RegularExpressions;

namespace RegexReplaceWithImage
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object and load a Word file from disk
            Document document = new Document();
            document.LoadFromFile(@"\input\replace template.docx");

            // Define a regular expression to match placeholders
            Regex regex = new Regex(@"\[\w+\]", RegexOptions.IgnoreCase);

            // Find all matches in the document that match the pattern
            TextSelection[] selections = document.FindAllPattern(regex);

            // Loop through each matched placeholder
            foreach (TextSelection selection in selections)
            {
                // Create a picture object and load the image from disk
                DocPicture pic = new DocPicture(document);
                pic.LoadImage(@"\avatar-1.png");

                // Get the matched text as a single text range
                TextRange textRange = selection.GetAsOneRange();

                // Get the index of the text range in its parent paragraph
                int index = textRange.OwnerParagraph.ChildObjects.IndexOf(textRange);

                // Insert the image at the matched position
                textRange.OwnerParagraph.ChildObjects.Insert(index, pic);

                // Remove the original placeholder text
                textRange.OwnerParagraph.ChildObjects.Remove(textRange);
            }

            // Save the modified document to disk
            document.SaveToFile(@"\output\ReplaceTextWithImage.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Here is a before-and-after comparison of replacing text with an image using regex in C#: Regex Replace Text with Image Using C#

Detailed steps explained:

  • Create an object of Document class and read a Word document.
  • Define a regular expression to match target content.
  • Find all occurrences using Document.FindAllPattern() method.
  • Loop through the collection of matches.
  • Create a DocPicture instance and load an image.
  • Get the matched text as a text range and retrieve its index in the parent paragraph.
  • Insert the image at the position and remove the original text.
  • Save the Word document as a new file.

Replace Text with Regex in VB.NET

If you're working with VB.NET instead of C#, you can achieve the same result using regular expressions to search and replace text throughout a Word document. The approach is similar—load the file, apply a regex pattern, and update the content. Here's a simple example to get you started.

Imports Spire.Doc
Imports System.Text.RegularExpressions

Module Module1
	Sub Main()
		Dim doc As New Document()
		doc.LoadFromFile("/input/replace template.docx")

		Dim regex As New Regex("#\w+\b")
		doc.Replace(regex, "Lena")

		doc.SaveToFile("/output/regexreplace.docx", FileFormat.Docx2013)
	End Sub
End Module

Above is the VB.NET code for replacing text throughout an entire Word document using regular expressions.

If you need to perform other tasks, such as replacing text in specific paragraphs or replacing text with images, you can easily convert the C# code examples into VB.NET using the C# Code ⇆ VB.NET Code Converter — a handy tool developed by the Spire.Doc team.

The Conclusion

With the help of regular expressions, replacing text or even inserting images in Word documents using C# becomes a smooth and efficient process. Whether you're working on templates, reports, or personalized documents, this approach saves time and reduces manual work. Ready to try it out? Download Spire.Doc and get started with a free 30-day trial license—perfect for evaluation and small projects.

Document variables are used to preserve macro settings in between macro sessions. Spire.Doc allows adding variables, counting the number of variables, retrieving the name and value of variables, and removing specific variables in a Word document.

Add a Variable

Use the Add method to add a variable to a document. The following example adds a document variable named "A1" with a value of 12 to the document.

using Spire.Doc;
using Spire.Doc.Documents;
namespace ADDVARIABLE
{
    class Program
    {

        static void Main(string[] args)
        {
            //Instantiate a document object
            Document document = new Document();
            //Add a section
            Section section = document.AddSection();
            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            //Add a DocVariable Filed
            paragraph.AppendField("A1", FieldType.FieldDocVariable);
            //Add a document variable to the DocVariable Filed
            document.Variables.Add("A1", "12");
            //Update fields
            document.IsUpdateFields = true;
            //Save and close the document object
            document.SaveToFile("AddVariable.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Count the number of Variables

Use the Count property to return the number of variables in a document.

//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;

Console.WriteLine(number);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Retrieve Name and Value of a Variable

Use the GetNameByIndex and GetValueByIndex methods to retrieve the name and value of the variable by index, and the Variables[String Name] to retrieve or set the value of the variable by name.

using Spire.Doc;
using Spire.Doc.Documents;
using System;
namespace COUNTVARIABLE
{

    class Program
    {

        static void Main(string[] args)
        {
            //Load the document
            Document document = new Document("AddVariable.docx");
            //Get the number of variables in the document
            int number = document.Variables.Count;

            Console.WriteLine(number);

        }
    }
}

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Remove a specific Variable

Use the Remove method to remove the variable from the document.

using Spire.Doc;
using System;
namespace RETRIEVEVARIABLE
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the document
            Document document = new Document("AddVariable.docx");

            // Retrieve name of the variable by index
            string s1 = document.Variables.GetNameByIndex(0);

            // Retrieve value of the variable by index
            string s2 = document.Variables.GetValueByIndex(0);

            // Retrieve or set value of the variable by name
            string s3 = document.Variables["A1"];

            Console.WriteLine("{0} {1} {2}", s1, s2, s3);
        }
    }
}
page 197