Reading Barcodes with ByteScout Barcode Reader SDK - ByteScout
  • Home
  • /
  • Blog
  • /
  • Reading Barcodes with ByteScout Barcode Reader SDK

Reading Barcodes with ByteScout Barcode Reader SDK

Bytescout provides seamless and easy to use SDK for reading barcodes from PDF or image file format. In this article, we’ll explore Bytescout Barcode Reader SDK and see various programs to read barcode values from image/PDF files.

Some of the strong points for Bytescout Barcode Reader SDK are as follows:

  • Easy to use SDK.
  • Reads barcodes from JPG, PNG, TIFF images, and PDF (no other software required).
  • It provides support for almost all barcode types.
  • Works with noisy barcodes.
  • Inbuilt support for exporting barcode read the result in various formats such as XML, CSV, TXT, etc.
  • Works offline, no Internet connection required.
  • Royalty-free licensing (no additional run-time licenses or additional fees on bar code reader).

In order to have better exposure for Bytescout Barcode Reader SDK, we’ll be reviewing the following programs in this article.

  1. General example reading barcodes.
  2. Reading barcode from PDF or TIFF file on a page by page basis.
  3. Read checkboxes.
  4. Export results to XML, CSV, TXT.
  5. Reduce CPU usage while reading for barcode value.

These programs will be in C# Console applications. It can be created from the menu File -> New -> Project, then choose “Console Application” under the “Windows” tab. If you are using the latest IDE, at the time of writing this article is Visual Studio 2019, then select “Console App” from the start page.

Read Barcodes SDK

Then we’ll be adding a reference from ByteScout Barcode Reader assembly as shown in the following image.

Read BarCodes Online

You’ll need to have ByteScout SDK installed in your machine for this assembly reference in the project. This SDK can be downloaded and installed from here.

Let’s get started with the examples.

1. General example reading barcodes

In this program, we’ll be reading barcodes from the image file. Let’s see the program first and then we’ll analyze it later.

The input file for the program is as follows.

BarCode Reading 2D

The program is as below.

	using System;
	using System.IO;
	using Bytescout.BarCodeReader;

	namespace CommonExample
	{
		class Program
		{
			const string ImageFile = "Barcode.jpg";

			static void Main()
			{
				Console.WriteLine("Reading barcode(s) from image {0}", Path.GetFullPath(ImageFile));

				Reader reader = new Reader();
				reader.RegistrationName = "demo";
				reader.RegistrationKey = "demo";

				// Set barcode type to find
				reader.BarcodeTypesToFind.All = true;
				// We recommend using specific barcode types to avoid false positives, e.g.:
				// reader.BarcodeTypesToFind.QRCode = true;
				// reader.BarcodeTypesToFind.Code39 = true;

				// Read barcodes
				FoundBarcode[] barcodes = reader.ReadFrom(ImageFile);

				foreach (FoundBarcode barcode in barcodes)
				{
					Console.WriteLine("Found barcode with type '{0}' and value '{1}'", barcode.Type, barcode.Value);
				}

				// Cleanup
				reader.Dispose();

				Console.WriteLine("Press any key to exit..");
				Console.ReadKey();
			}
		}
	}

And here’s the output.

BarCode Reading 1D

Though the program is self-explanatory, let’s analyze it. This program can be divided into three parts.

1. Initiating Barcode reader class

	Reader reader = new Reader();
	reader.RegistrationName = "demo";
	reader.RegistrationKey = "demo";

We’re using Reader class from “Bytescout.BarCodeReader” namespace’s instance and assigning registration key and name to it. In this case, we’re using demo keys (which has the limitation of adding watermark text to output). In production usage, one should use actual keys from purchased SDK.

2. Set the barcode types to find

	// Set barcode type to find
	reader.BarcodeTypesToFind.All = true;

	// We recommend using specific barcode types to avoid false positives, e.g.:
	// reader.BarcodeTypesToFind.QRCode = true;
	// reader.BarcodeTypesToFind.Code39 = true;

Here we have enabled finding all types of barcodes from the image by setting “BarcodeTypesToFind.All” property to True. If we are sure about barcode type within input file then we should use specific barcode type(s) to read to increase performance.

3. Reading barcodes

	FoundBarcode[] barcodes = reader.ReadFrom(ImageFile);

	foreach (FoundBarcode barcode in barcodes)
	{
		Console.WriteLine("Found barcode with type '{0}' and value '{1}'", barcode.Type, barcode.Value);
	}

We’re using the ReadFrom method to read all barcodes from the input file. Output values are in the format of FoundBarcode class array; which contains all properties related to barcode such as barcode type, value, barcode position coordinates, etc.

2. Reading barcode from PDF or TIFF file on a page by page basis.

In this example, we’ll see how to read barcode values on a page to page basis from PDF input files or TIFF multipage image file.

The input file is as follows.

Reading Barcodes SDK

The code is as below.

    static void Main()
    {
        Reader reader = new Reader();
        reader.RegistrationName = "demo";
        reader.RegistrationKey = "demo";

        // Limit search to 1-dimensional barcodes only (exclude 2D barcodes to speed up the processing).
        // Change to barcodeReader.BarcodeTypesToFind.SetAll() to scan for all supported 1D and 2D barcode types
        // or select specific type, e.g. barcodeReader.BarcodeTypesToFind.PDF417 = True
        reader.BarcodeTypesToFind.All1D = true;

        // Input filename
        string fileName = "example.pdf";
        //string fileName = "multipage.tif";

        // Pages from which barcodes to be fetched
        int[] readFromPages = { 1, 2 };

        foreach (var pageNo in readFromPages)
        {
            Console.WriteLine("\n\nReading barcodes from PDF page {0}...", pageNo);

            // Decoding barcodes from PDF on page-by-page basis instead of reading the whole page
            FoundBarcode[] barcodes = reader.ReadFrom(fileName, (pageNo - 1));

            // Found results
            foreach (FoundBarcode barcode in barcodes)
            {
                Console.WriteLine("Found Barcode, Type: '{0}', Value: '{1}', Position: {2}", 
                    barcode.Type, barcode.Value, barcode.Rect);
            }
        }

        // Cleanup
        reader.Dispose();

        Console.WriteLine();
        Console.WriteLine("Press any key to continue.");
        Console.ReadKey();
    }

The output is as follows.
BarCode Read SDK

This example is mostly similar to the previous one, let’s analyze the differences.

We have given a multipage PDF file as input as shown below. Here we can instead give tiff file as input too.

	// Input filename
	string fileName = "example.pdf";
	//string fileName = "multipage.tif";

Then we’ve specified pages to read barcodes from. Page numbers in the method are zero indexes based, so when we are inside ReadFrom method we are deducting one from it.

    // Pages from which barcodes to be fetched
    int[] readFromPages = { 1, 2 };

The last step is to iterate from each page, and looking for barcodes in that page. We’re using an overloaded version of method ReadFrom which accepts the second parameter for page no.

    // Decoding barcodes from PDF on page-by-page basis instead of reading the whole page
    FoundBarcode[] barcodes = reader.ReadFrom(fileName, (pageNo - 1));

Then it’s displaying found barcode information such as barcode type, value, it’s position coordinates in the console.

    Console.WriteLine("Found Barcode, Type: '{0}', Value: '{1}', Position: {2}", 
		barcode.Type, barcode.Value, barcode.Rect);

3. Read Checkboxes

In this example, we’ll see how to read checkboxes with Bytescout Barcode Reader library.

The input file is as follows.

Read Checkboxes

The program code is as below.

    class Program
    {
        const string ImageFile = "checkboxes-checked.png";

        static void Main()
        {
            Console.WriteLine("Reading checkboxes from image {0}", Path.GetFullPath(ImageFile));

            Reader reader = new Reader();
            reader.RegistrationName = "demo";
            reader.RegistrationKey = "demo";

            // Enable check boxes recognition
            reader.BarcodeTypesToFind.Checkbox = true;

            // Find check boxes
            FoundBarcode[] barcodes = reader.ReadFrom(ImageFile);

            foreach (FoundBarcode barcode in barcodes)
            {
                Console.WriteLine("Found checkbox with type '{0}' and value '{1}'", barcode.Type, barcode.Value);
            }

            // Cleanup
            reader.Dispose();

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey();
        }
    }

The output is as follows.

Read BarCodes C#

Here Barcode type to find for the checkbox is set to true, which enables the finding of all checkbox type from the input document.

    // Enable check boxes recognition
    reader.BarcodeTypesToFind.Checkbox = true;

If we see the output; as this is the checkboxes it’s output is in the format of 1 and 0s. If Checkbox is checked it’ll be 1 else it’ll be 0.

4. Export Results to XML, CSV, TXT

In this example, we’ll see how to export found barcodes in files of different formats such as XML, CSV, TXT, JSON, etc.

The input file to the program is as follows.

Export Barcodes to Image

The program is as below.

    class Program
    {
        static void Main()
        {
            Reader reader = new Reader();
            reader.RegistrationName = "demo";
            reader.RegistrationKey = "demo";

            // Set barcode type to find
            reader.BarcodeTypesToFind.All1D = true;

            // Read barcodes
            reader.ReadFromFile("barcodes.pdf");

            // Export to files:
            // ================

            // 1. Export found barcodes to XML
            reader.ExportFoundBarcodesToXML("barcodes.xml");

            // 2a. Export found barcodes to CSV with default delimiter, quotation and character encoding
            reader.ExportFoundBarcodesToCSV("barcodes.csv");

            // 2b. Export found barcodes to CSV with custom delimiter, quotation and character encoding
            reader.ExportFoundBarcodesToCSV("barcodes2.csv", "|", "'", Encoding.UTF8);

            // 3a. Export found barcodes to plain text file in default character encoding
            reader.ExportFoundBarcodesToTXT("barcodes.txt");

            // 3b. Export only values of found barcodes to plain text file in custom character encoding
            reader.ExportFoundBarcodesToTXT("barcodes2.txt", true, Encoding.ASCII);


            // Get formatted result to a variable for further processing
            // =========================================================

            // 5a. Get found barcodes as XmlDocument
            XmlDocument xmlDocument = reader.ExportFoundBarcodesToXMLDocument();

            // 5b. Get found barcodes as XML string
            string xmlString = reader.ExportFoundBarcodesToXML();

            // 6a. Get found barcodes as string in CSV format with default delimiter and quotation
            string csv = reader.ExportFoundBarcodesToCSV();

            // 6b. Get found barcodes as string in CSV format with custom delimiter and quotation
            string csv2 = reader.ExportFoundBarcodesToCSV("|", "'");

            // 7. Get found barcodes as string in plain text format
            string txt = reader.ExportFoundBarcodesToTXT();

            // 8. Get found barcodes as string in JSON format
            string jsonString = reader.ExportFoundBarcodesToJSON();

            // Cleanup
            reader.Dispose();
        }
    }

And the output is as follows.
BarCode Reader App

Let’s analyze this code. In this example, we’re reading all one-dimensional barcodes from PDF file.

  • To export all found barcodes to the XML format file, we can use method ExportFoundBarcodesToXML by providing output XML file location as input to it.

// 1. Export found barcodes to XML
reader.ExportFoundBarcodesToXML("barcodes.xml");

  • If we want to get barcode results in the XmlDocument format, we can use the ExportFoundBarcodesToXMLDocument method like below.

// 5a. Get found barcodes as XmlDocument
XmlDocument xmlDocument = reader.ExportFoundBarcodesToXMLDocument();

  • In case just XML string is our requirement, we can use the following method.

// 5b. Get found barcodes as XML string
string xmlString = reader.ExportFoundBarcodesToXML();

  • To export all found barcodes to CSV format with default delimiter (“,”); we can use the ExportFoundBarcodesToCSV method by passing the destination file as an input argument to it.

// 2a. Export found barcodes to CSV with default delimiter, quotation and character encoding
reader.ExportFoundBarcodesToCSV("barcodes.csv");

  • We can also have custom delimiter in the output CSV format file by using the overloaded version of the ExportFoundBarcodesToCSV method as following.

// 2b. Export found barcodes to CSV with custom delimiter, quotation and character encoding
reader.ExportFoundBarcodesToCSV("barcodes2.csv", "|", "'", Encoding.UTF8);

  • To get output CSV format file in string format or string format with a custom delimiter, we can use the following overloaded versions of the ExportFoundBarcodesToCSV method.

// 6a. Get found barcodes as string in CSV format with default delimiter and quotation
string csv = reader.ExportFoundBarcodesToCSV();

// 6b. Get found barcodes as string in CSV format with custom delimiter and quotation
string csv2 = reader.ExportFoundBarcodesToCSV("|", "'");

  • To export all barcodes to a plain text file, we can use method ExportFoundBarcodesToTXT by passing the destination output file as an argument to it.

// 3a. Export found barcodes to a plain text file in default character encoding
reader.ExportFoundBarcodesToTXT("barcodes.txt");

  • We can use the overloaded version of the ExportFoundBarcodesToTXT method like the following to have custom character encoding for the output text file.

// 3b. Export only values of found barcodes to plain text file in custom character encoding
reader.ExportFoundBarcodesToTXT("barcodes2.txt", true, Encoding.ASCII);

  • To get output in string variable we can use following overloaded version of ExportFoundBarcodesToTXT method.

// 7. Get found barcodes as string in plain text format
string txt = reader.ExportFoundBarcodesToTXT();

  • If we want to get output in JSON format we can use method ExportFoundBarcodesToJSON as follows.

// 8. Get found barcodes as string in JSON format
string jsonString = reader.ExportFoundBarcodesToJSON();

5. Reduce CPU usage while reading for barcode value

In applications where barcode reading is implemented, speed is a very essential element; an end-user might be surrounded by a long queue!

In this example, we’ll see how to reduce CPU usage and make speedy barcode read operation.

Input document for this program is as follows.

BarCode Reading C#

The program is as below:

    class Program
    {
        static void Main()
        {
            // Barcode reader instance
            Reader reader = new Reader();
            reader.RegistrationName = "demo";
            reader.RegistrationKey = "demo";

            // Input filename
            string inputFileName = "barcode_multipage.pdf";

            // Set specific barcode type to read
            reader.BarcodeTypesToFind.Code128 = true;

            // Reduce PDF rendering resolution
            reader.PDFRenderingResolution = 150;

            // Set specific area to read from
            reader.CustomAreaLeft = 407;
            reader.CustomAreaTop = 494;
            reader.CustomAreaHeight = 605;
            reader.CustomAreaWidth = 999;

            // Set specific page to read from along with filename
            reader.ReadFromPdfFilePage(inputFileName, 1, 1);

            // Get all found barcodes
            FoundBarcode[] barcodes = reader.FoundBarcodes;

            // Display found barcodes
            Console.WriteLine("Reading barcode(s) from PDF file...");

            foreach (FoundBarcode barcode in barcodes)
            {
                Console.WriteLine("Found Barcode - Type: '{0}', Value: '{1}'", barcode.Type, barcode.Value);
            }

            // Cleanup
            reader.Dispose();

            Console.WriteLine();
            Console.WriteLine("Press any key to continue.");
            Console.ReadKey();
        }
    }

The output is as follows:

BarCode Reader Features

In order to reduce CPU and RAM load following are the steps, we can consider:

  • Instead of using All1D or All2D barcode types, set it to the specific types you have in your documents like PDF417 or Code 39. You may set multiple barcode types if you need to.
  • Reduce PDF rendering resolution to 200-150 dpi (this depends on your document).
  • If you are reading from a multipage document, then set specific pages to read barcodes from. If you have barcodes on the first two pages only; then change the code to read barcodes from the first two pages only.
  • If barcodes are always located/printed in the same corner then also specify the area to read from instead of the whole page for scanning.

In this program, we are reading barcode from a multipage document, and we are following the same guidelines specified above.

  • We have specified the exact barcode type to read which is Code128, so SDK won’t try to analyze input image/PDF to find-out it’s possible barcode type.

// Set specific barcode type to read
reader.BarcodeTypesToFind.Code128 = true;

  • Reducing PDF rendering resolution to 150

// Reduce PDF rendering resolution
reader.PDFRenderingResolution = 150;

  • We are aware of a specific area to read barcodes from, hence specifying a specific area to read from.

// Set specific area to read from
reader.CustomAreaLeft = 407;
reader.CustomAreaTop = 494;
reader.CustomAreaHeight = 605;
reader.CustomAreaWidth = 999;

  • Lastly, we are reading a barcode from a specific page.

// Set specific page to read from along with filename
reader.ReadFromPdfFilePage(inputFileName, 1, 1);

That’s all guys. I hope you enjoyed this article and have a bit of insight into Bytescout Barcode Reader SDK. You can refer to this link to explore more.

You can also use a barcode reader online for simple non-programming tasks.

Happy Coding 🙂

 

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next