How to Upload PDF Document in ASP.NET Application and Read Barcodes from PDF Using ByteScout BarCode Reader SDK for ASP.NET - ByteScout

How to Upload PDF Document in ASP.NET Application and Read Barcodes from PDF Using ByteScout BarCode Reader SDK for ASP.NET

  • Home
  • /
  • Articles
  • /
  • How to Upload PDF Document in ASP.NET Application and Read Barcodes from PDF Using ByteScout BarCode Reader SDK for ASP.NET

How to upload PDF in ASP.NET and then read barcodes from uploaded PDF using Bytescout BarCode Reader SDK for .NET and ASP.NET

Reading barcode values from PDF documents is one of the common development requirements. ByteScout Barcode Reader SDK is an AI-based exceptional easy to use SDK with wide ranges of support for almost all barcode types. In this article, we’ll observe reading barcodes values from PDF input file with Barcode Reader SDK in ASP.NET application. Input PDF is provided through file upload control and output will be displayed in ListBox control.

Here’s how the final output will look.

You can find the full source code of this sample in the ExamplesAdvanced ExamplesASP.NET folder of ByteScout BarCode Reader SDK installation. These samples are also available at the online GitHub repository also.

Listed below is the ASPX page source code. It’s primarily having FileUpload control and ListBox inside Form control. Once the PDF file is selected in FileUpload control and upload Button control is clicked, we’ll be reading barcode contents in PDF and displaying result values in ListBox.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTestSharp._Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Web Barcode Reader Tester (C#)</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Click browse button to upload a PDF document<br />
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <br />
        <asp:Button id="UploadButton"
           Text="Upload file"
           OnClick="UploadButton_Click"
           runat="server">
       </asp:Button> 
        <br />
       <br />
        <asp:Label id="UploadStatusLabel" Text="" runat="server"></asp:Label> 
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Visible="False"></asp:ListBox><br />
        <br />
        </div>
    </form>
</body>
</html>

Backend code is basically using ByteScout Barcode Reader SDK in the Button click event and filling out ListBox. The following are the backend code in VB and C# languages.

Visual Basic in ASP.NET (Default.aspx.vb)

Imports System.Drawing

Imports Bytescout.BarCodeReader


Public Partial Class _Default
	Inherits System.Web.UI.Page
	Protected Sub UploadButton_Click(sender As Object, e As EventArgs)
		Dim savePath As [String] = "uploads"

		If FileUpload1.HasFile Then
			Dim fileName As [String] = FileUpload1.FileName
			savePath += fileName
			FileUpload1.SaveAs(Server.MapPath(savePath))

            Dim barcodeReader As New Reader()


            ' Limit search to 1D barcodes only (exclude 2D barcodes to speed up the search).
 			' Change to barcodeReader.BarcodeTypesToFind.SetAll() to scan for all supported 1D and 2D barcodes 
			' or select specific type, e.g. barcodeReader.BarcodeTypesToFind.PDF417 = True
			barcodeReader.BarcodeTypesToFind.SetAll1D()
            
            'reader.MediumTrustLevelCompatible = true ' uncomment this line to enable Medium Trust compatible mode (slows down the recognition process as direct image data access is disabled in Medium Trust mode)
			
            UploadStatusLabel.Visible = False
            ListBox1.Items.Clear()
            ListBox1.Visible = True

            ListBox1.Items.Add("Reading barcode(s) from PDF")

            Dim barcodes As FoundBarcode() = barcodeReader.ReadFrom(Server.MapPath(savePath))

            If barcodes.Length = 0 Then
                ListBox1.Items.Add("    No barcodes found")
            Else
                For Each barcode As FoundBarcode In barcodes
                    ListBox1.Items.Add([String].Format("    Found barcode with type '{0}' and value '{1}'", barcode.Type, barcode.Value))
                Next
            End If


        Else
            ' Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload."
        End If
	End Sub
End Class

Visual C# in ASP.NET (Default.aspx.cs)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Drawing.Imaging;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Collections.Generic;

using Bytescout.BarCodeReader;

namespace WebTestSharp
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void UploadButton_Click(object sender, EventArgs e)
        {
            String savePath = @"uploads";

            if (FileUpload1.HasFile)
            {
                String fileName = FileUpload1.FileName;
                savePath += fileName;
                FileUpload1.SaveAs(Server.MapPath(savePath));

				Reader barcodeReader = new Reader();

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

            				// reader.MediumTrustLevelCompatible = true; // uncomment this line to enable Medium Trust compatible mode (slows down the recognition process as direct image data access is disabled in Medium Trust mode)
					UploadStatusLabel.Visible = false;

                    ListBox1.Items.Clear();
                    ListBox1.Visible = true;
						ListBox1.Items.Add("Reading barcode(s) from image #" + imgNum);
						
						FoundBarcode[] barcodes = barcodeReader.ReadFrom(savePath);

						if (barcodes.Length == 0)
						{
							ListBox1.Items.Add("    No barcodes found");
						}
						else
						{
							foreach (FoundBarcode barcode in barcodes)
								ListBox1.Items.Add(String.Format("Found barcode with type '{0}' and value '{1}'", barcode.Type, barcode.Value));
						}

            }
            else
            {
                // Notify the user that a file was not uploaded.
                UploadStatusLabel.Text = "You did not specify a file to upload.";
            }
        }
    }
}

Though code is self-explanatory, let’s analyze how ByteScout Barcode Reader SDK is being used to get barcodes from PDF file.

1. Referencing ByteScout Barcode Reader SDK

using Bytescout.BarCodeReader;

We had already added a reference to the ByteScout Barcode Reader assembly and here giving reference to the namespace so that all members inside this can be accessed.

2. Initializing and Configuring Barcode Reader.

We’re creating an initializing barcode reader with the following code.

Reader barcodeReader = new Reader();

For this demo purpose, I am not providing the registration name and the key to the reader, and output values are masked. But in production, we should provide this registration information by using an overloaded version to get the unmasked output value.

Now that reader is created, we’re configuring the reader to read/find specific types of barcodes.

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

In this case, we’ve programmed to read all 1D barcodes, so it’ll try and match all barcode types for barcode images inside PDF. And upon completion of the process, it’ll return all matched barcode types and values. In cases when we’re sure about input barcode types for a given PDF, it’s advised to specify the exact type of barcode to improve performance. To further enhance barcode reading performance we can also provide a page to read barcode from as well exact region inside the page where to look for barcodes. You can see ways to provide these in various overloaded methods.

3. Providing input for barcode reader and getting values

ByteScout Barcode Reader SDK is providing various ways to give inputs, and we can use any version of the method which suits us. For example, we can also provide inputs in various image formats as well as PDF document format.

In this sample, we’re providing a PDF file as input to the “ReadFrom” method and it’s returning all found barcodes in an array of “FoundBarcode” format. This method is truly AI (Artificial Intelligence) based and it’s automatically analyzing all PDF pages and retrieving barcode values with matched types along with the confidence of that barcode type match.

FoundBarcode[] barcodes = barcodeReader.ReadFrom(Server.MapPath(savePath));

This “FoundBarcode” class contains various properties such as barcode type, barcode value along with different properties such as Region (where this barcode found), Confidence of retrieved values, and other useful properties.

Beneath this barcode reading mechanism, there is a lot of complex logic going on, but as we’ve seen in this sample ByteScout Barcode Reader SDK is providing very simplified and user-friendly methods to use.

I suggest you implement this sample at your side and enhance it as per your requirement. You can get free trial from here.

Thanks for reading this article!

Tutorials:

next