Articles in this section
Category / Section

How to add barcode to word using C#, VB.NET

4 mins read

Syncfusion® Essential® DocIO is a .NET Word library used to create, read, and edit Word documents programmatically without Microsoft Word or interop dependencies.

Using this library, you can add barcode to Word document in C# and VB.NET. Below steps should be followed.

  • Design your template Word document with the required layout and merge fields using Microsoft Word
  • Using Syncfusion PDF library you can generate a barcode.
  • Insert the generated barcode as an image into the Word document with MergeImageField event using Essential® DocIO.

Steps to add barcode to Word document using C#:

  1. Create a new C# console application project.Create Console application in Visual Studio
  2. Install Syncfusion.DocIO.WinForms NuGet package as a reference to your .NET Framework applications from the NuGet.org.Add DocIO NuGet package reference to the project
  3. Include the following namespace in the Program.cs file.

C#

using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.Pdf.Barcode;

VB

Imports Syncfusion.DocIO
Imports Syncfusion.DocIO.DLS
Imports Syncfusion.Pdf.Barcode
  1. Use the following code to add barcode to Word document.

C#

//Opens the template document 
WordDocument document = new WordDocument(Path.GetFullPath(@"../../Template.docx"));
//Creates mail merge events handler for image fields
document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(InsertBarcode);
//Gets data to perform mail merge
DataTable table = GetDataTable();
//Performs the mail merge
document.MailMerge.ExecuteGroup(table);
//Saves and closes the Word document instance
document.Save(Path.GetFullPath(@"../../Sample.docx"));
document.Close();

VB

'Opens the template document 
Dim document As WordDocument = New WordDocument(Path.GetFullPath("../../Template.docx"))
'Creates mail merge events handler for image fields
AddHandler document.MailMerge.MergeImageField, AddressOf InsertBarcode
'Gets Data to perform mail merge
Dim table As DataTable = GetDataTable()
'Performs the mail merge
document.MailMerge.ExecuteGroup(table)
'Saves And closes the Word document instance
document.Save(Path.GetFullPath("../../Sample.docx"))
document.Close()
  1. Include the following helper method to insert barcode image using MergeImageField event.

C#

private static void InsertBarcode(object sender, MergeImageFieldEventArgs args)
{
    if (args.FieldName == "Barcode")
    {
        //Generates barcode image for field value.
        Image barcodeImage = GenerateBarcodeImage(args.FieldValue.ToString());
        //Sets barcode image for merge field
        args.Image = barcodeImage;
    }
}

VB

Private Shared Sub InsertBarcode(ByVal sender As Object, ByVal args As MergeImageFieldEventArgs)
    If args.FieldName = "Barcode" Then
        'Generates barcode image for field value.
        Dim barcodeImage As Image = GenerateBarcodeImage(args.FieldValue.ToString())
        'Sets barcode image for merge field
        args.Image = barcodeImage
    End If
End Sub
  1. Include the following helper method to generate barcode image using Syncfusion PDF library.

C#

private static Image GenerateBarcodeImage(string barcodeText)
{
    //Initialize a new PdfCode39Barcode instance
    PdfCode39Barcode barcode = new PdfCode39Barcode();
    //Set the height and text for barcode
    barcode.BarHeight = 45;
    barcode.Text = barcodeText;
    //Convert the barcode to image
    Image barcodeImage = barcode.ToImage(new SizeF(145, 45));
    return barcodeImage;
}

VB

Private Shared Function GenerateBarcodeImage(ByVal barcodeText As String) As Image
    'Initialize a New PdfCode39Barcode instance
    Dim barcode As PdfCode39Barcode = New PdfCode39Barcode()
    'Set the height And text for barcode
    barcode.BarHeight = 45
    barcode.Text = barcodeText
    'Convert the barcode to image
    Dim barcodeImage As Image = barcode.ToImage(New SizeF(145, 45))
    Return barcodeImage
End Function
  1. Include the following helper method to get data for Mail merge execution process.

C#

private static DataTable GetDataTable()
{
    // List of products name.
    string[] products = { "Apple Juice", "Grape Juice", "Hot Soup", "Tender Coconut", "Vennila", "Strawberry", "Cherry", "Cone", "Butter", "Milk", "Cheese", "Salt", "Honey", "Paneer", "Curd", "Bread", "Olive oil", "Vinegar", "Sports Drinks", "Vegetable Juice", "Sugar", "Flour", "Jam", "Cake", "Brownies", "Donuts", "Egg", "Tooth Brush", "Talcum powder", "Detergent Soap", "Room Spray", "Tooth paste"};
    DataTable table = new DataTable("Product_PriceList");
    // Add fields to the Product_PriceList table.
    table.Columns.Add("ProductName");
    table.Columns.Add("Price");
    table.Columns.Add("Barcode");
    DataRow row;
    int Id =10001;
    // Inserting values to the tables.
    foreach (string product in products)
    {
        row = table.NewRow();
        row["ProductName"] = product;
        switch (product)
        {
            case "Apple Juice":
                row["Price"] = "$12.00";
                break;
            case "Grape Juice":
            case "Milk":
                row["Price"] = "$15.00";
                break;
            case "Hot Soup":
                row["Price"] = "$20.00";
                break;
            case "Tender coconut":
            case "Cheese":
                row["Price"] = "$10.00";
                break;
            case "Vennila Ice Cream":
                row["Price"] = "$15.00";
                break;
            case "Strawberry":
            case "Butter":
                row["Price"] = "$18.00";
                break;
            case "Cherry":
            case "Salt":
                row["Price"] = "$25.00";
                break;
            default:
                row["Price"] = "$20.00";
                break;
        }
        //Add barcode text
        row["Barcode"] = Id.ToString();
        table.Rows.Add(row);
        Id++;
    }
    return table;
}

VB

Private Shared Function GetDataTable() As DataTable
    'List of products name.
    Dim products As String() = {"Apple Juice", "Grape Juice", "Hot Soup", "Tender Coconut", "Vennila", "Strawberry", "Cherry", "Cone", "Butter", "Milk", "Cheese", "Salt", "Honey", "Paneer", "Curd", "Bread", "Olive oil", "Vinegar", "Sports Drinks", "Vegetable Juice", "Sugar", "Flour", "Jam", "Cake", "Brownies", "Donuts", "Egg", "Tooth Brush", "Talcum powder", "Detergent Soap", "Room Spray", "Tooth paste"}
    Dim table As DataTable = New DataTable("Product_PriceList")
    'Add fields to the Product_PriceList table.
    table.Columns.Add("ProductName")
    table.Columns.Add("Price")
    table.Columns.Add("Barcode")
    Dim row As DataRow
    Dim Id As Integer = 10001
    'Inserting values to the tables
    For Each product As String In products
        row = table.NewRow()
        row("ProductName") = product
        Select Case product
            Case "Apple Juice"
                row("Price") = "$12.00"
            Case "Grape Juice", "Milk"
                row("Price") = "$15.00"
            Case "Hot Soup"
                row("Price") = "$20.00"
            Case "Tender coconut", "Cheese"
                row("Price") = "$10.00"
            Case "Vennila Ice Cream"
                row("Price") = "$15.00"
            Case "Strawberry", "Butter"
                row("Price") = "$18.00"
            Case "Cherry", "Salt"
                row("Price") = "$25.00"
            Case Else
                row("Price") = "$20.00"
        End Select
        'Add barcode text
        row("Barcode") = Id.ToString()
        table.Rows.Add(row)
        Id += 1
    Next
    Return table
End Function

A complete working example of how to add barcode to Word document using C# can be downloaded from add barcode to Word.zip

Input Word document with merge fields as follows. Input document with merge fields

By executing the program, you will get the output Word document with barcode labels as follows. Word document with barcodes

Take a moment to peruse the documentation, where you can find basic Word document processing options along with features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly PDF and Image conversions with code examples.

Explore more about the rich set of Syncfusion® Word Framework features.

Note:

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please  to leave a comment
Access denied
Access denied