Read Different Barcode Types in C# using PDF.co
In this article, you will see how to read different barcodes in C# using the PDF.co Web API. PDF.co offers a rich API to perform various types of PDF-related tasks, e.g., searching a PDF, merging a PDF, filling PDF forms automatically, etc. You will see how to read various barcode types from PDF documents, including the QR barcode.
Read Various Barcode Types in C#
In this section, you will see how to read different types of barcodes in C# from the URL of a PDF document. You will create a C# console application for this purpose.
Steps
The first step is to import the required C# libraries, as shown in the following script.
usingSystem.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
The Microsoft.NET framework comes preinstalled with the System.Net library. However, you will have to install the “NewtonSoft” library yourself.
To install this library from the Microsoft Visual Studio IDE, go to “Tools-> NuGet Package Manager.” Search for the “Newtonsoft” library. You will see the following packages. Select the first package and click the “Install” button.
The remaining script is executed Inside the “Main” method of your C# console application.
You have to store your PDF.CO API Key in a C# variable along with the URL to the source PDF file. You can get your API key by registering at https://app.pdf.co.
The source PDF document for this article can be found at this link:
https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf
The pages of your PDF document containing the barcode are also stored in a variable. If you do not specify page numbers, barcodes will be read from all the pages.
Finally, specify the type of barcodes you want to read.
The following script performs these steps:
const String API_KEY = "**************************";
const string SourceFile = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf";
const string Pages = "";
const string BarcodeTypes = "Code128,Code39,Interleaved2of5,EAN13"
Next, you need to create a C# WebClient class object that will be used to make requests to PDF.CO Web API.
WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);
The script below defines a variable containing the PDF.CO API call that reads the barcodes from a PDF document.
string url = "https://api.pdf.co/v1/barcode/read/from/url";
Finally, the following script defines a parameter dictionary that will be passed to the Web API call. The dictionary is serialized using the SerializedObject() method.
You can look at the official documentation to see details of the other optional parameters.
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("url", SourceFile);
parameters.Add("type", BarcodeTypes);
parameters.Add("pages", Pages); // Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
Next, in the try/catch block, you made an API call to the PDF.CO Web API. The response from the call is parsed as a JSON object. If the response doesn’t contain an error, the barcode list from the JSON object is traversed, and the barcode type, value, and its coordinates on the PDF document are displayed.
try
{ string response = webClient.UploadString(url, jsonPayload);JObject json = JObject.Parse(response);if (json["error"].ToObject<bool>() == false)
{
// Display found barcodes in console
foreach (JToken token in json["barcodes"])
{
Console.WriteLine("Found barcode:");
Console.WriteLine(" Type: " + token["TypeName"]);
Console.WriteLine(" Value: " + token["Value"]);
Console.WriteLine(" Document Page Index: " + token["Page"]);
Console.WriteLine(" Rectangle: " + token["Rect"]);
Console.WriteLine(" Confidence: " + token["Confidence"]);
Console.WriteLine();
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
Finally, the WebClient object is disposed of as shown in the script below:
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
Complete Code
Here is the complete C# code for reading barcodes from PDF documents using PDF.CO Web API.
using System.Net;
using Newtonsoft.Json;
usingNewtonsoft.Json.Linq;namespace PDFCOWebApiExample
{
public class Program
{const String API_KEY = "**********************";
const string SourceFile = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf";
const string Pages = "";
const string BarcodeTypes = "Code128,Code39,Interleaved2of5,EAN13";static void Main(string[] args)
{WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);string url = "https://api.pdf.co/v1/barcode/read/from/url";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("url", SourceFile);
parameters.Add("type", BarcodeTypes);
parameters.Add("pages", Pages);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
string response = webClient.UploadString(url, jsonPayload);
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Display found barcodes in console
foreach (JToken token in json["barcodes"])
{
Console.WriteLine("Found barcode:");
Console.WriteLine(" Type: " + token["TypeName"]);
Console.WriteLine(" Value: " + token["Value"]);
Console.WriteLine(" Document Page Index: " + token["Page"]);
Console.WriteLine(" Rectangle: " + token["Rect"]);
Console.WriteLine(" Confidence: " + token["Confidence"]);
Console.WriteLine();
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
Input PDF Document
The source PDF document looks like this:
And here is the output; you can see the type, values, and locations of the barcodes from the PDF document.
Output
Read QR Barcode Type in C#
In the previous section, you saw how to read various barcode types, except the QR barcode type. In this section, you will see how to read that barcode type.
Steps
The process is similar to what you have already seen. The only difference is that you have to specify “QRCode” as the barcode type.
The following line of the script will change, while the rest of the script will remain the same.
const string BarcodeTypes = "QRCode";
Complete Code
Here is the complete code that reads the QR barcode type from a PDF document.
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;namespace PDFCOWebApiExample
{
public class Program
{
const String API_KEY = "usmanmalik57@gmail.com_8df5671cedb0fb37ec9610eada409f110c38";
const string SourceFile = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf";
const string Pages = "";
const string BarcodeTypes = "QRCode";
static void Main(string[] args)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);
string url = "https://api.pdf.co/v1/barcode/read/from/url";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("url", SourceFile);
parameters.Add("type", BarcodeTypes);
parameters.Add("pages", Pages);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
string response = webClient.UploadString(url, jsonPayload);
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Display found barcodes in console
foreach (JToken token in json["barcodes"])
{
Console.WriteLine("Found barcode:");
Console.WriteLine(" Type: " + token["TypeName"]);
Console.WriteLine(" Value: " + token["Value"]);
Console.WriteLine(" Document Page Index: " + token["Page"]);
Console.WriteLine(" Rectangle: " + token["Rect"]);
Console.WriteLine(" Confidence: " + token["Confidence"]);
Console.WriteLine();
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
Input PDF Document
You can see that the PDF document contains one QR code at the top right corner of the document.
In the output below, you can see the type, value, and coordinates of the QR code in your PDF document.
Output
Read Barcodes from an Uploaded File
In the previous section, you saw how to read barcodes from the URL of a PDF document. You can also read barcodes from a PDF document uploaded from your local file system. Let’s see how to see that.
Steps
As you saw earlier, the first step is to import the required C# libraries.
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Next, you need to define variables that store the PDF.CO API key, the path to the source file, the number of pages, and barcode types.
const String API_KEY = "***************************";
const string SourceFile = @"D:\Datasets\barcodes.pdf";
const string Pages = "";
const string BarcodeTypes = "Code128,Code39,Interleaved2of5,EAN13";
The following script defines the C# WebClient class object that will be used to send calls to the PDF.CO Web API.
The script also defines the URL from the PDF.CO cloud storage where your local PDF document will be uploaded.
WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);
string query = Uri.EscapeUriString(string.Format(
"https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}",
Path.GetFileName(SourceFile)));
The script below uses the WebClient class object to upload your local C# document to PDF.CO cloud storage.
try
{
string response = webClient.DownloadString(query);
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Get URL to use for the file upload
string uploadUrl = json["presignedUrl"].ToString();
string uploadedFileUrl = json["url"].ToString();
// 2. UPLOAD THE FILE TO CLOUD.
webClient.Headers.Add("content-type", "application/octet-stream");
webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream
webClient.Headers.Remove("content-type");
Once you upload your PDF document to any cloud storage, the rest of the process is similar to what you have already seen.
You first need to define a variable that stores the PDF.CO Web API call for reading barcodes.
The next step is to define a parameter dictionary containing parameters that will be sent to the PDF.CO Web API. The parameter dictionary needs to be serialized.
Next, inside the try/catch block, the WebClient class object makes a call to the PDF.CO Web API using the UploadString() method.
The response from the Web API call is parsed as a JSON Object. If everything goes well, the JSON object will contain a “barcodes” list, which you can iterate and print the type, value, coordinates, etc., of each of the barcodes found in the PDF document.
In case of an exception, or if the API response contains an error, the catch block, or the else block executes, respectively.
// 3. Read barcode from uploaded file
string url = "https://api.pdf.co/v1/barcode/read/from/url";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("url", uploadedFileUrl);
parameters.Add("type", BarcodeTypes);
parameters.Add("pages", Pages);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
response = webClient.UploadString(url, jsonPayload);
json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Display found barcodes in console
foreach (JToken token in json["barcodes"])
{
Console.WriteLine("Found barcode:");
Console.WriteLine(" Type: " + token["TypeName"]);
Console.WriteLine(" Value: " + token["Value"]);
Console.WriteLine(" Document Page Index: " + token["Page"]);
Console.WriteLine(" Rectangle: " + token["Rect"]);
Console.WriteLine(" Confidence: " + token["Confidence"]);
Console.WriteLine();
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
}
Finally, the script below defines the else block and the catch block for the outer try block which contains script for uploading files to PDF.CO cloud storage.
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
Complete Code
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;namespace ByteScoutWebApiExample
{
class Program
{const String API_KEY = "*************************";
const string SourceFile = @"D:\Datasets\barcodes.pdf";
const string Pages = "";
const string BarcodeTypes = "Code128,Code39,Interleaved2of5,EAN13";
static void Main(string[] args)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);
string query = Uri.EscapeUriString(string.Format(
"https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}",
Path.GetFileName(SourceFile)));
try
{
string response = webClient.DownloadString(query);
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Get URL to use for the file upload
string uploadUrl = json["presignedUrl"].ToString();
string uploadedFileUrl = json["url"].ToString();
// 2. UPLOAD THE FILE TO CLOUD.
webClient.Headers.Add("content-type", "application/octet-stream");
webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream
webClient.Headers.Remove("content-type");
// 3. SPLIT UPLOADED PDF By Text
string url = "https://api.pdf.co/v1/barcode/read/from/url";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("url", uploadedFileUrl);
parameters.Add("type", BarcodeTypes);
parameters.Add("pages", Pages);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
response = webClient.UploadString(url, jsonPayload);
json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Display found barcodes in console
foreach (JToken token in json["barcodes"])
{
Console.WriteLine("Found barcode:");
Console.WriteLine(" Type: " + token["TypeName"]);
Console.WriteLine(" Value: " + token["Value"]);
Console.WriteLine(" Document Page Index: " + token["Page"]);
Console.WriteLine(" Rectangle: " + token["Rect"]);
Console.WriteLine(" Confidence: " + token["Confidence"]);
Console.WriteLine();
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
Input PDF Document
As an example, the following document is uploaded to any cloud storage. (It is the same document that was uploaded to the cloud in the previous script).
And here is the console output: