How to Read Barcode from the Uploaded File (Node for Barcode Reader API in JavaScript using PDF.co Web API

Barcodes are everywhere! Programming barcodes solutions give endless opportunies and gives convenient solution to endusers. PDF.co provides endpoints to read and create almost all kind of barcode types. And it’s very easy to implement.

In this article, we’ll review the code reading barcode from the uploaded file using PDF.co. This Source code is also available at our GitHub repository at this location. The solution in other programming languages is also avaialble at GitHub repository at this location.

PDF.co Web API is the flexible Web API that includes full set of functions from e-signature requests to data extraction, OCR, images recognition, pdf splitting and pdf splitting. Can also generate barcodes and read barcodes from images, scans and PDF.

On-demand (REST Web API) version:
 Web API (on-demand version)

On-premise offline SDK for Windows:
 60 Day Free Trial (on-premise)

app.js

      
/*jshint esversion: 6 */ var https = require("https"); var path = require("path"); 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 = ""; // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. getPresignedUrl(API_KEY, SourceFile) .then(([uploadUrl, uploadedFileUrl]) => { // 2. UPLOAD THE FILE TO CLOUD. uploadFile(API_KEY, SourceFile, uploadUrl) .then(() => { // 3. READ BARCODES FROM UPLOADED FILE readBarcodes(API_KEY, uploadedFileUrl, Pages, BarcodeTypes); }) .catch(e => { console.log(e); }); }) .catch(e => { console.log(e); }); function getPresignedUrl(apiKey, localFile) { return new Promise(resolve => { // Prepare request to `Get Presigned URL` API endpoint let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`; let reqOptions = { host: "api.pdf.co", path: encodeURI(queryPath), headers: { "x-api-key": API_KEY } }; // Send request https.get(reqOptions, (response) => { response.on("data", (d) => { let data = JSON.parse(d); if (data.error == false) { // Return presigned url we received resolve([data.presignedUrl, data.url]); } else { // Service reported error console.log("getPresignedUrl(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPresignedUrl(): " + e); }); }); } function uploadFile(apiKey, localFile, uploadUrl) { return new Promise(resolve => { fs.readFile(SourceFile, (err, data) => { request({ method: "PUT", url: uploadUrl, body: data, headers: { "Content-Type": "application/octet-stream" } }, (err, res, body) => { if (!err) { resolve(); } else { console.log("uploadFile() request error: " + e); } }); }); }); } function readBarcodes(apiKey, uploadedFileUrl, pages, barcodeTypes) { // Prepare request to `Barcode Reader` API endpoint let queryPath = `/v1/barcode/read/from/url`; // JSON payload for api request var jsonPayload = JSON.stringify({ types: barcodeTypes, pages: pages, url: uploadedFileUrl }); let reqOptions = { host: "api.pdf.co", method: "POST", path: queryPath, headers: { "x-api-key": apiKey, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(jsonPayload, 'utf8') } }; // Send request var postRequest = https.request(reqOptions, (response) => { response.on("data", (d) => { response.setEncoding("utf8"); // Parse JSON response let 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("readBarcodes(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("readBarcodes(): " + e); }); // Write request data postRequest.write(jsonPayload); postRequest.end(); }

package.json

      
{ "name": "test", "version": "1.0.0", "description": "PDF.co", "main": "app.js", "scripts": { }, "keywords": [ "pdf.co", "web", "api", "bytescout", "api" ], "author": "ByteScout & PDF.co", "license": "ISC", "dependencies": { "request": "^2.88.2" } }

Output

Though the code is straight-forward and easy to understand, let’s analyze it. We can logically divide the code into three parts; Declarations, Uploading the source file URL to PDF.co server and reading barcode values from this public URL.

At the start of the program, the necessary references such as https, path, fs, request are loaded into the program. The required data for making this barcode reading request such as SourceFile, BarcodeTypes, Pages are also collected and stored in variables.

SourceFile Source file PDF path
BarcodeTypes Value of this variable contains a comma-seperated list of barcode types that needs to be searched. Please refer to this link to get the supported barcode types.
Pages contain a comma-seperated list of page indices that needs to be processed. Please leave this field empty to process all the pages.

In order to upload the source file to PDF.co cloud we’re first getting a pre-signed URL and then uploading the input file to this pre-signed URL using PUT request. The PDF.co API endpoint /v1/file/upload/get-presigned-url is used to get a pre-signed URL. We’re passing the file name as a parameter there. This request returns two URLs in the resonse body, Pre-signed URL (data.presignedUrl) and public URL (data.url). As mentioned in function uploadFile, we’re using the PUT request to upload the source file contents. PDF.co supports both PDF and Image as an input file to read barcode values.

Once the file upload is completed, we’re preparing the barcode request /v1/barcode/read/from/url to read barcodes from the public URL. JSON payload containing barcode types, pages and Source file URL is prepared to pass as a request input. PDF.co API key is passed in the header x-api-key for authentication purposes.

The API response contains barcode information array with information such as barcode type, barcode value, page index where barcode is found, location co-ordinates of found barcode, confidence of parse barcode and more information.

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"]);

In this sample, we’ve used basic parameters for demonstration purposes. Based on our requirement we can tweak the input request. Please visit PDF.co documentations for more information.

Thank you for reading!

VIDEO

ON-PREMISE OFFLINE SDK

Get 60 Day Free Trial

See also:

ON-DEMAND REST WEB API

Get Your API Key

See also:

Related Samples: