How to Read BarCodes with PDF.co Web API - ByteScout
Announcement
Our ByteScout SDK products are sunsetting as we focus on expanding new solutions.
Learn More Open modal
Close modal
Announcement Important Update
ByteScout SDK Sunsetting Notice
Our ByteScout SDK products are sunsetting as we focus on our new & improved solutions. Thank you for being part of our journey, and we look forward to supporting you in this next chapter!
  • Home
  • /
  • Blog
  • /
  • How to Read BarCodes with PDF.co Web API

How to Read BarCodes with PDF.co Web API

PDF.co provides a restful API to read the barcode input file and extract its value. In this article, we’ll explore the following programs to get a better understanding of PDF.co barcode reader API.

Before we jump into programs let’s get an overview of barcode reader API.

Read Barcodes From URL or file API Details

URL: https://api.pdf.co/v1/barcode/read/from/url
Read barcodes from images, tiff, pdf documents, scanned documents. All popular types of barcodes are supported from Code 39, Code 128 to QR Code, Datamatrix, and PDF417. Supports noisy and damaged barcodes, scans, documents. GET or POST request.

Input Parameters

Param Description
async Optional.

Runs processing asynchronously. Returns Use JobId that you may use with /job/check to check the state of the processing (possible states: working, failed, aborted, and success).

Must be one of true, false.

types Optional.

A comma-separated list of barcode types to decode.

Valid types: AustralianPostCode, Aztec, CircularI2of5, Codabar, CodablockF, Code128, Code16K, Code39, Code39Extended, Code39Mod43, Code39Mod43Extended, Code93, DataMatrix, EAN13, EAN2, EAN5, EAN8, GS1, GS1DataBarExpanded, GS1DataBarExpandedStacked, GS1DataBarLimited, GS1DataBarOmnidirectional, GS1DataBarStacked, GTIN12, GTIN13, GTIN14, GTIN8, IntelligentMail, Interleaved2of5, ITF14, MaxiCode, MICR, MicroPDF, MSI, PatchCode, PDF417, Pharmacode, PostNet, PZN, QRCode, RoyalMail, RoyalMailKIX, Trioptic, UPCA, UPCE, UPU.

Must be a String.

file Optional.

Source barcodes file.

url Optional.

URL of the image or pdf file to decode barcodes from.

Must be a String.

pages Optional.

A comma-separated list of page indices (or ranges) to process. IMPORTANT: the very first page starts at 0 (zero). To set a range use the dash -, for example, 0,2-5,7-. To set a range from the index to the last page use range like this: 2- (from page #3 as the index starts at zero and till the of the document). For ALL pages just leave this param empty. Example: 0,2-5,7- means first page, then 3rd page to 6th page, and then the range from 8th (index = 7) page till the end of the document.

Must be a String.

Output Status Codes

Code Description
200 All is OK
400 Bad input parameters
401 Unauthorized
403 Not enough credits
405 Timeout error.

To process large documents or files please use asynchronous mode ( set an async parameter to true) and then check the status using /job/check endpoint. If a file contains many pages then specify a page range using pages parameter. The number of pages of the document can be obtained using the endpoint /pdf/info

Example

Sample Request:

! Don’t forget to set x-api-key param or header param to an API key, get yours here
POST

{
	"types" : "Code128,Code39,Interleaved2of5,EAN13",
	"pages" : "",
	"url" : "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf"
}

Response Code: 200
Response

{
    "barcodes": [
        {
            "Value": "test123",
            "RawData": null,
            "Type": 2,
            "Rect": "{X=111,Y=60,Width=255,Height=37}",
            "Page": 0,
            "File": "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf",
            "Confidence": 0.90625155,
            "TypeName": "Code128"
        },
        {
            "Value": "123456",
            "RawData": null,
            "Type": 4,
            "Rect": "{X=111,Y=129,Width=306,Height=37}",
            "Page": 0,
            "File": "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf",
            "Confidence": 0.7710818,
            "TypeName": "Code39"
        },
        {
            "Value": "&<FNC1&>0112345678901231",
            "RawData": null,
            "Type": 2,
            "Rect": "{X=111,Y=198,Width=305,Height=37}",
            "Page": 0,
            "File": "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf",
            "Confidence": 0.9156459,
            "TypeName": "Code128"
        },
        {
            "Value": "12345670",
            "RawData": [
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                0
            ],
            "Type": 5,
            "Rect": "{X=111,Y=267,Width=182,Height=0}",
            "Page": 0,
            "File": "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf",
            "Confidence": 1,
            "TypeName": "I2of5"
        },
        {
            "Value": "1234567890128",
            "RawData": null,
            "Type": 6,
            "Rect": "{X=102,Y=336,Width=71,Height=72}",
            "Page": 0,
            "File": "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf",
            "Confidence": 0.895925164,
            "TypeName": "EAN13"
        }
    ],
    "pageCount": 1,
    "error": false,
    "status": 200,
    "name": null
}

Now back to programs. Programs in this article are written in node.js, so if you want to code along you’ll need node.js installed on your machine. You can get node.js from its official website. For the code editor, I’ll be using Visual Studio Code, it’s one of the best open-source code editors available.

Also, all PDF.co APIs requires API-keys to be passed in the method header for authentication purpose. You can get your own keys by registering at https://app.pdf.co/signup.

With all this done let’s get started.

1. Read barcode from URL input

In this example, we’ll demonstrate how to read barcode values by input pdf URL.

For input, we are using the following pdf file URL.

https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf

Its content is as below.

BarCode Reader API

The source program is as follows.

var https = require("https");

// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co/documentation/api
const API_KEY = "***********************************";


// Direct URL of source file to search barcodes in.
const SourceFileUrl = "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf";

// Comma-separated list of barcode types to search. 
// See valid barcode types in the documentation https://app.pdf.co/documentation/api/1.0/barcode/read_from_url.html
const BarcodeTypes = "Code128,Code39,Interleaved2of5,EAN13";
// Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
const Pages = "";


// Prepare request to `Barcode Reader` API endpoint
var queryPath = `/v1/barcode/read/from/url?types=${BarcodeTypes}&pages=${Pages}&url=${SourceFileUrl}`;
var reqOptions = {
    host: "api.pdf.co",
    path: encodeURI(queryPath),
    headers: {
        "x-api-key": API_KEY
    }
};
// Send request
https.get(reqOptions, (response) => {
    response.on("data", (d) => {

        // Set utf8 encoding
        response.setEncoding("utf8");

        // Parse JSON response
        var data = JSON.parse(d);
        
        if (data.error == false) {
            // Display found barcodes in console
            data.barcodes.forEach((element) => {
                console.log("Found barcode:");
                console.log("  Type: " + element.TypeName);
                console.log("  Value: " + element.Value);
                console.log("  Document Page Index: " + element.Page);
                console.log("  Rectangle: " + element.Rect);
                console.log("  Confidence: " + element.Confidence);
                console.log("");
            }, this);
        }
        else {
            // Service reported error
            console.log(data.message);
        }
    });
}).on("error", (e) => {
    // Request error
    console.error(e);
});

And the output is as below.

BarCode Reading

If we analyze this program, the Program can be divided into three logical parts.

1. Prepare request to `Barcode Reader` API endpoint

At the start of the program, we’ve listed out all the needed parameters in the API query, as shown in the table below.

Parameter Usage
API_KEY Authentication key
SourceFileUrl URL of source file to search barcodes into
BarcodeTypes All the barcode types to look for in a comma-separated format. Example input might look like “Code128,Code39,Interleaved2of5,EAN13”.
Pages This parameter contains a comma-separated list of page indices (or ranges) to process. If we want to search in all pages then leave this blank. Valid input might look like “0,2-5,7-“.

Then we’re creating a query path for the ‘Barcode Reader‘ API endpoint, and also creating request options. In the request options’ header, we’re providing an API key for authenticating an API request.

// Prepare request to `Barcode Reader` API endpoint
var queryPath = `/v1/barcode/read/from/url?types=${BarcodeTypes}pages=${Pages}url=${SourceFileUrl}`;
var reqOptions = {
    host: "api.pdf.co",
    path: encodeURI(queryPath),
    headers: {
        "x-api-key": API_KEY
    }
};

2. Sending Request

In this step, we’re sending barcode reading requests by passing reqOptions which we set, and waiting for its response. We’ve enabled data events on the response so that whenever its response is received, further operations will be executed.

// Send request
https.get(reqOptions, (response) => {
    response.on("data", (d) => {
	...

3. Processing output and displaying output information

Here, we first convert the response to JSON format; so that it will be convenient to read and process output data further.

 // Parse JSON response
 var data = JSON.parse(d);

Next, we’ll check whether it does not error out by checking the error property inside the data variable (data.error) property. And if doesn’t error out we’ll loop through the response and display all barcode output in the console.

	// Display found <a href="https://bytescout.com/blog/zapier-integration-barcode-reading.html" target="_blank" rel="noopener">barcodes</a> in console
	data.barcodes.forEach((element) => {
		console.log("Found barcode:");
		console.log("  Type: " + element.TypeName);
		console.log("  Value: " + element.Value);
		console.log("  Document Page Index: " + element.Page);
		console.log("  Rectangle: " + element.Rect);
		console.log("  Confidence: " + element.Confidence);
		console.log("");
	}, this);

2. Read barcode from file input

This program is mostly similar to the previous one, the only difference is that we’re uploading an input pdf file here. In the previous example, we provided the input URL of a PDF file.

The input is as below:

Read BarCodes Program

The program is as follows.

var fs = require("fs");

// `request` module is required for file upload.
// Use "npm install request" command to install.
var request = require("request");

// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co/documentation/api
const API_KEY = "******************************";

// Source file name
const SourceFile = "./sample.pdf";
// Comma-separated list of barcode types to search. 
// See valid barcode types in the documentation https://app.pdf.co/documentation/api/1.0/barcode/read_from_url.html
const BarcodeTypes = "Code128,Code39,Interleaved2of5,EAN13";
// Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
const Pages = "";

// Prepare request to `Barcode Reader` API endpoint
var query = `https://api.pdf.co/v1/barcode/read/from/url`;
let reqOptions = {
    uri: query,
    headers: { "x-api-key": API_KEY },
    formData: {
        types: BarcodeTypes,
        pages: Pages,
        file: fs.createReadStream(SourceFile)
    }
};

// Send request
request.post(reqOptions, function (error, response, body) {
    if (error) {
        return console.error("Error: ", error);
    }

    // Parse JSON response
    let data = JSON.parse(body);
    data.barcodes.forEach((element) => {
        console.log("Found barcode:");
        console.log("  Type: " + element["TypeName"]);
        console.log("  Value: " + element["Value"]);
        console.log("  Document Page Index: " + element["Page"]);
        console.log("  Rectangle: " + element["Rect"]);
        console.log("  Confidence: " + element["Confidence"]);
        console.log();
    }, this);
});

The output is as below:

BarCode Reader Demo

In this program, we’re passing file content as a form of data into the ‘file’ parameter. We are using the file stream’s method createReadStream by passing the file path as an argument, which will create a PDF stream synchronously.

// Prepare request to `Barcode Reader` API endpoint
var query = `https://api.pdf.co/v1/barcode/read/from/url`;
let reqOptions = {
    uri: query,
    headers: { "x-api-key": API_KEY },
    formData: {
        types: BarcodeTypes,
        pages: Pages,
        file: fs.createReadStream(SourceFile)
    }
};

3. Read Barcode from file input Asynchronously

PDF.co provides support for asynchronous processing of requests by providing the ‘async’ parameter to true. This asynchronous request outputs a job, and we have to check the status of that job by calling it periodically until it completes.

This approach is very useful when we are having requests which are very time-consuming to process. For example, if we are having a big PDF file and we have to extract all barcodes from all pages in that PDF, then asynchronous processing is our go-to approach.

For this program, we are having an input file as following.

Barcoding Tools

Our program is as below.

var https = require("https");
var fs = require("fs");

// `request` module is required for file upload.
// Use "npm install request" command to install.
var request = require("request");

// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co/documentation/api
const API_KEY = "******************************";

// Source file name
const SourceFile = "./sample.pdf";
// Comma-separated list of barcode types to search. 
// See valid barcode types in the documentation https://app.pdf.co/documentation/api/1.0/barcode/read_from_url.html
const BarcodeTypes = "Code128,Code39,Interleaved2of5,EAN13";
// Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
const Pages = "";

// Prepare request uri for `Barcode Reader` API endpoint
var query = `https://api.pdf.co/v1/barcode/read/from/url`;
let reqOptions = {
    uri: query,
    headers: { "x-api-key": API_KEY },
    formData: {
        types: BarcodeTypes,
        pages: Pages,
        async: 'True',
        file: fs.createReadStream(SourceFile)
    }
};

// Send request
request.post(reqOptions, function (error, response, body) {
    if (error) {
        return console.error("Error: ", error);
    }

    // Parse JSON response
    let data = JSON.parse(body);
    console.log(`Job #${data.jobId} has been created!`);
    checkIfJobIsCompleted(data.jobId, data.url);
});


function checkIfJobIsCompleted(jobId, resultFileUrlJson) {
    let queryPath = `/v1/job/check?jobid=${jobId}`;
    let reqOptions = {
        host: "api.pdf.co",
        path: encodeURI(queryPath),
        method: "GET",
        headers: { "x-api-key": API_KEY }
    };

    https.get(reqOptions, (response) => {
        response.on("data", (d) => {
            response.setEncoding("utf8");
            // Parse JSON response
            let data = JSON.parse(d);
            console.log(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`);

            if (data.status == "working") {
                // Check again after 3 seconds
				setTimeout(function(){ checkIfJobIsCompleted(jobId, resultFileUrlJson);}, 3000);
            }
            else if (data.status == "success") {

                request({ method: 'GET', uri: resultFileUrlJson, gzip: true },
                function (error, response, body) {

                    // Parse JSON response
                    let respJsonFileArray = JSON.parse(body);

                    respJsonFileArray.forEach((element) => {
                        console.log("Found barcode:");
                        console.log("  Type: " + element["TypeName"]);
                        console.log("  Value: " + element["Value"]);
                        console.log("  Document Page Index: " + element["Page"]);
                        console.log("  Rectangle: " + element["Rect"]);
                        console.log("  Confidence: " + element["Confidence"]);
                        console.log();
                    }, this);
                });
            }
            else {
                console.log(`Operation ended with status: "${data.status}".`);
            }
        })
    });
}

And the output is as follows:

Barcoding Tool

We have enabled the async operation to true here.

    formData: {
        types: BarcodeTypes,
        pages: Pages,
        async: 'True',
        file: fs.createReadStream(SourceFile)
    }

Now after sending the request, it’ll return us a job. In this example, we’re using response JobID and job’s URL to periodically check job status by calling the checkIfJobIsCompleted method.

	
// Send request
request.post(reqOptions, function (error, response, body) {
    if (error) {
        return console.error("Error: ", error);
    }

    // Parse JSON response
    let data = JSON.parse(body);
    console.log(`Job #${data.jobId} has been created!`);
    checkIfJobIsCompleted(data.jobId, data.url);
});

Function checkIfJobIsCompleted internally calls job check API (/v1/job/check) to check request processing status. And once its status is Success we’ll get job response and display output.

In order to get more detail regarding job/check API, refer to this URL.

That’s all guys. I hope you enjoyed this article and had good insight into PDF.co barcode reading API. For more information regarding PDF.co APIs, you can visit its documentation here.

You may also try online barcode reader for daily 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