How to Generate 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 Generate BarCodes with PDF.co Web API

How to Generate BarCodes with PDF.co Web API

In this article, we’ll see how to generate a barcode with PDF.co Barcode generation API. This API is restful in nature, hence easily consumable by most of the programming frameworks without the need to install any third-party library.

PDF.co Barcode generation API generates high-quality printable and scannable barcodes in images or PDF format. It covers all popular barcode types such as Code 39, Code 128 to QR Code, DataMatrix, and PDF417.

We’ll be covering the following programs, in order to get an idea of working with this API. Programs in this article are written with Node JS.

  1. Generating barcode
  2. Generating barcode asynchronously

In order to run these programs on your machine, you’ll require API keys from PDF.co. This can easily get for free from this URL.

Before starting with the program, let’s see API details.

Barcode Generation API details

URL: https://api.pdf.co/v1/barcode/generate
Generates high-quality printable and scannable barcodes as images or PDF. All popular types are supported from Code 39, Code 128 to QR Code, Datamatrix, and PDF417. 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.

encrypt Optional.

Enable encryption for the output file.

Must be one of true, false.

name Optional.

The filename for the generated image.

Must be a String

value Optional.

Value to be encoded into the barcode.

Must be a String

type Optional.

Sets barcode type. Valid values are: Code128, Code39, Postnet, UPCA, EAN8, ISBN, Codabar, I2of5, Code93, EAN13, JAN13, Bookland, UPCE, PDF417, PDF417Truncated, DataMatrix, QRCode, Aztec, Planet, EAN128, GS1_128, USPSSackLabel, USPSTrayLabel, DeutschePostIdentcode, DeutschePostLeitcode, Numly, PZN, OpticalProduct, SwissPostParcel, RoyalMail, DutchKix, SingaporePostalCode, EAN2, EAN5, EAN14, MacroPDF417, MicroPDF417, GS1_DataMatrix, Telepen, IntelligentMail, GS1_DataBar_Omnidirectional, GS1_DataBar_Truncated, GS1_DataBar_Stacked, GS1_DataBar_Stacked_Omnidirectional, GS1_DataBar_Limited, GS1_DataBar_Expanded, GS1_DataBar_Expanded_Stacked, MaxiCode, Plessey, MSI, ITF14, GTIN12, GTIN8, GTIN13, GTIN14.

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
{
"name" : "barcode.png",
"type" : "Code128",
"value" : "qweasd123456"
}
Response
200
{
"url": "https://pdf-temp-files.s3.amazonaws.com/97c9b70b7ed54706ace0ea4ccb66a27d/barcode.png",
"error": false,
"status": 200,
"name": "barcode.png"
}

1. Generating barcode

Here we’ll be generating a barcode of type Code128 with the value “qweasd123456”. The program is as follows.

var https = require("https");
var path = require("path");
var fs = require("fs");
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co/documentation/api
const API_KEY = "***********************************";
// Result image file name
const DestinationFile = "./barcode.png";
// Barcode type. See valid barcode types in the documentation https://app.pdf.co/documentation/api/1.0/barcode/generate.html
const BarcodeType = "Code128";
// Barcode value
const BarcodeValue = "qweasd123456";
// Prepare request to `Barcode Generator` API endpoint
var queryPath = `/v1/barcode/generate?name=${path.basename(DestinationFile)}&type=${BarcodeType}&value=${BarcodeValue}`;
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) => {
// Parse JSON response
var data = JSON.parse(d);
if (data.error == false) {
// Download the image file
var file = fs.createWriteStream(DestinationFile);
https.get(data.url, (response2) => {
response2.pipe(file).on("close", () => {
console.log(`Generated barcode saved to '${DestinationFile}' file.`);
});
});
}
else {
// Service reported error
console.log(data.message);
}
});
}).on("error", (e) => {

// Request error
console.error(e);
});

And the output is as follows.

Generate BarCodes with PDF API

We can divide this program into two steps.

1. Generate request

First of all, we’re building a query path by providing parameters and URL parts like method name, output file name, type of barcode, and for which value is to be generated.

// Prepare request to `Barcode Generator` API endpoint
var queryPath = `/v1/barcode/generate?name=${path.basename(DestinationFile)}&type=${BarcodeType}&value=${BarcodeValue}`;

Then we’re creating requests, by providing host, path, and headers.

var reqOptions = {
    host: "api.pdf.co",
    path: encodeURI(queryPath),
    headers: {
        "x-api-key": API_KEY
    }
};

If you have noticed we’re passing API key in header parameter “x-api-key”, which authenticates and authorizes barcode generation API request.

2. Execute the request and process response.

We’re executing the request by passing the request options variable reqOptions and waiting on a response like below.

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

Once the response received, we’ll parse the response as JSON and check if it errored out or not. And finally, save the generated barcode file to the destination location.

    // Parse JSON response
    var data = JSON.parse(d);
    
    if (data.error == false) {
        // Download the image file
        var file = fs.createWriteStream(DestinationFile);
        https.get(data.url, (response2) => {
            response2.pipe(file).on("close", () => {
                console.log(`Generated barcode saved to '${DestinationFile}' file.`);
            });
        });
    }
    else {
        // Service reported error
        console.log(data.message);
    }

Here we’re using a file stream to save the barcode image file.

	
    // Download the image file
    var file = fs.createWriteStream(DestinationFile);

2. Generating barcode asynchronously.

PDF.co provides async options to its APIs for situations when processing is time-consuming. It’s also used to increase performance by implementing asynchronous functionality.

The program code is as follows.

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

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

// Result image file name
const DestinationFile = "./barcode.png";
// Barcode type. See valid barcode types in the documentation https://app.pdf.co/documentation/api/1.0/barcode/generate.html
const BarcodeType = "Code128";
// Barcode value
const BarcodeValue = "qweasd123456";

// Prepare request to `Barcode Generator` API endpoint
var queryPath = `/v1/barcode/generate?name=${path.basename(DestinationFile)}&type=${BarcodeType}&value=${BarcodeValue}&async=True`;
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) => {
        // Parse JSON response
        var data = JSON.parse(d);
        
        if (data.error == false) {
            console.log(`Job #${data.jobId} has been created!`);
            checkIfJobIsCompleted(data.jobId, data.url);
        }
        else {
            // Service reported error
            console.log(data.message);
        }
    });
}).on("error", (e) => {
    // Request error
    console.error(e);
});


function checkIfJobIsCompleted(jobId, resultFileUrl) {
    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, resultFileUrl);}, 3000);
            }
            else if (data.status == "success") {
                // Download image file
                var file = fs.createWriteStream(DestinationFile);
                https.get(resultFileUrl, (response2) => {
                    response2.pipe(file)
                        .on("close", () => {
                            console.log(`Generated image file saved as "${DestinationFile}" file.`);
                        });
                });
            }
            else {
                console.log(`Operation ended with status: "${data.status}".`);
            }
        })
    });
}

The output is the following.

BarCode Generator API

The code is pretty identical to the previous one, except we are using the async option, and hence handling its response differently.

1. Enable async processing in input request.

Here we’re specifying parameter async with value ‘True’, which makes async processing true.

var queryPath = `/v1/barcode/generate?name=${path.basename(DestinationFile)}&type=${BarcodeType}&value=${BarcodeValue}&async=True`;

2. Async APIs will return JOB as a response.

    response.on("data", (d) => {
        // Parse JSON response
        var data = JSON.parse(d);
        
        if (data.error == false) {
            console.log(`Job #${data.jobId} has been created!`);
            checkIfJobIsCompleted(data.jobId, data.url);
        }
        else {
            // Service reported error
            console.log(data.message);
        }
    });

In the output, we’ll receive jobId, and job URL. Then need to use this job URL with jobId to check if the request has been processed or not.

3. Check if a job is completed

Here we’re calling another API (/v1/job/check) to check whether request processing status.

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

function checkIfJobIsCompleted(jobId, resultFileUrl) {
    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, resultFileUrl);}, 3000);
            }
            else if (data.status == "success") {
                // Download image file
                var file = fs.createWriteStream(DestinationFile);
                https.get(resultFileUrl, (response2) => {
                    response2.pipe(file)
                        .on("close", () => {
                            console.log(`Generated image file saved as "${DestinationFile}" file.`);
                        });
                });
            }
            else {
                console.log(`Operation ended with status: "${data.status}".`);
            }
        })
    });
}

Method checkIfJobIsCompleted is called at an interval of 3 seconds until job status is “success” or it errors out.

I hope you get a better insight into barcode generation with PDF.co For more information regarding PDF.co APIs you can visit its documentation here.

You can also use this free online barcode scanner, for simpler daily 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