Merge - Node.JS

This tutorial shows how to merge documents using the LEADTOOLS Cloud Services in a Node.JS application.

Overview  
Summary This tutorial covers how to make Merge requests and process the results using the LEADTOOLS Cloud Services in a Node.JS application.
Completion Time 30 minutes
Project Download tutorial project (125 KB)
Platform LEADTOOLS Cloud Services API
IDE Visual Studio 2019
Language Node.JS
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Be sure to review the following sites for information about LEADTOOLS Cloud Services API.

Service Plans

LEADTOOLS Service Plan offerings:

Service Plan Description
Free Trial Free Evaluation
Page Packages Prepaid Page Packs
Subscriptions Prepaid Monthly Processed Pages

To further explore the offerings, refer to Pricing Information for LEADTOOLS Hosted Cloud Services > Service Plan Terms.

For pricing details, refer to https://www.leadtools.com/sdk/products/hosted-services#pricing > Page Packages and Subscriptions.

To obtain the necessary Application ID and Application Password, refer to Create an Account and Application with the LEADTOOLS Hosted Cloud Services.

Add the Merge Code

With the project created and the package added, coding can begin.

In the Solution Explorer, open server.js. Add the following variables at the top.

//Simple script to showcasing how to use the Merge API in the LEADTOOLS Cloud Services. 
 
const axios = require("axios"); 
 
//If uploading a file as multi-part content, we will need the file-system library installed. 
//const fs = require('fs'); 
 
const FormatsEnum = { 
  png: 1, 
  jpeg: 2, 
  tiff: 3, 
  pdf: 4, 
  pdfa: 5, 
  pdfImage: 6, 
  pdfImageOverText: 7, 
  pdfaImageOverText: 8, 
  docx: 9, 
  docxFramed: 10, 
  rtf: 11, 
  rtfFramed: 12, 
  txt: 13, 
  txtFramed: 14, 
}; 
 
const servicesUrl = "https://azure.leadtools.com/api/"; 
 
const tiffUrl = "http://demo.leadtools.com/images/cloud_samples/ocr1-4.tif"; 
const pdfUrl = "https://demo.leadtools.com/images/pdf/leadtools.pdf"; 
 
let firstFileId = ""; 
let secondFileId = ""; 
const outputFormat = FormatsEnum.pdf; 

Add the call uploadFile(tiffUrl, firstFileUploadCallback);, the matching functions uploadFile(url, callback) and firstFileUploadCallback(error, response, body); additionally, create the functions uploadSecondFile() and secondFileUploadCallback(error, response, body). These functions send uploadFile requests to the LEADTOOLS Cloud Services API, if successful, each file will be sent to the server and a unique identifier (GUID) will be returned and stored for later use.

uploadFile(tiffUrl, firstFileUploadCallback); 
 
function uploadFile(url, callback) { 
  const uploadUrl = `${servicesUrl}uploadFile?forMerge=true&fileurl=${url}`; 
  axios 
    .post(uploadUrl, {}, getRequestOptions(uploadUrl)) 
    .then((res) => { 
      callback(res.error, res, res.data); 
    }) 
    .catch((err) => { 
      console.error(err); 
    }); 
 
  //If uploading a file as multi-part content: 
  /*var uploadUrl = servicesUrl + "uploadFile?forMerge=true"; 
    const form = new FormData(); 
    form.append("file", fs.createReadStream('path\to\inputFile')); 
    axios.post(uploadUrl, form, getRequestOptions(uploadUrl)).then((res) => { 
        callback(res.error, res, res.data); 
    }).catch ((err) => { 
        console.error(err); 
    });*/ 
} 
 
function firstFileUploadCallback(error, response, body) { 
  if (!error && response.status === 200) { 
    firstFileId = body; 
    console.log("First File ID: " + firstFileId); 
 
    checkVerification(firstFileId, uploadSecondFile); 
  } 
} 
 
function uploadSecondFile() { 
  uploadFile(pdfUrl, secondFileUploadCallback); 
} 
 
function secondFileUploadCallback(error, response, body) { 
  if (!error && response.status === 200) { 
    secondFileId = body; 
    console.log("Second File ID: " + secondFileId); 
 
    checkVerification(secondFileId, mergeFile); 
  } 
} 

For each file upload a verification check will be performed to ensure the files were submitted to the server. Create an async function called checkVerification(id, calllback) which utilizes the file IDs from the upload requests.

async function checkVerification(id, callback) { 
  const queryUrl = servicesUrl + "Query?id=" + id; 
  await axios 
    .post(queryUrl, {}, getRequestOptions(queryUrl)) 
    .then((res) => { 
      const results = res.data; 
      if (!res.error && results["FileStatus"] !== 123) { 
        console.log("Verification finished with return code: " + res.status); 
        if (results["FileStatus"] == 122) { 
          callback(); 
        } else { 
          console.log( 
            "File failed verification with File Status: " + 
              results["FileStatus"] 
          ); 
        } 
      } else { 
        //The file has not yet finished processing. 
        return new Promise((resolve) => { 
          setTimeout(() => { 
            //Sleep for 5 seconds before trying again 
            resolve(checkVerification(id, callback)); //Call the method again. 
          }, 5000); 
        }); 
      } 
    }) 
    .catch((err) => { 
      console.error(err); 
    }); 
} 

Once verifications for both files are complete and valid a Merge request will need to be sent to combine the files into one. Create a function called mergeFile() that will submit the merge request with the fileIDs gathered previously.

function mergeFile() { 
  const mergeUrl = `${servicesUrl}Conversion/Merge?format=${outputFormat}`; 
  const options = getRequestOptions(mergeUrl); 
  const json = JSON.stringify([ 
    { 
      firstPage: 1, 
      lastPage: -1, 
      fileId: firstFileId, 
    }, 
    { 
      pages: [5, 1, 2, 4, 3], 
      fileId: secondFileId, 
    }, 
  ]); 
  axios.post(mergeUrl, json, options).then((res) => { 
    console.log("Merging Files..."); 
    if (!res.error && res.status === 200) { 
      console.log("Merge command was successful"); 
      queryServices(firstFileId); 
    } else { 
      console.log("Merge failed with HTTP code: " + res.status); 
      console.log(res.data); 
    } 
  }); 
} 

Next, create an async function called queryServices(guid) that utilizes the GUID provided by Merge request. If successful the response body will contain all the request data in JSON format.

async function queryServices(guid) { 
  //Function to query the status of a request.  If the request has not yet finished, this function will recursively call itself until the file has finished. 
  const queryUrl = servicesUrl + "Query?id=" + guid; 
  await axios 
    .post(queryUrl, {}, getRequestOptions(queryUrl)) 
    .then((res) => { 
      const results = res.data; 
      if ( 
        !res.error && 
        results["FileStatus"] !== 100 && 
        results["FileStatus"] !== 123 
      ) { 
        console.log("File finished processing with return code: " + res.status); 
        console.log(results["FileStatus"]); 
        if (results["FileStatus"] !== 200) { 
          return; 
        } 
        console.log("Results: \n"); 
        parseJson(results["RequestData"]); 
      } else { 
        //The file has not yet finished processing. 
        return new Promise((resolve) => { 
          setTimeout(() => { 
            //Sleep for 5 seconds before trying again 
            resolve(queryServices(guid)); //Call the method again. 
          }, 5000); 
        }); 
      } 
    }) 
    .catch((err) => { 
      console.error(err); 
    }); 
} 

Then, create the function parseJson(jsonObject) to process the returned JSON data.

function parseJson(jsonObject) { 
  //Function to decode the JSON object that was returned by the LEADTOOLS CloudServices. 
  for (let i = 0; i < jsonObject.length; i++) { 
    let currentRequest = jsonObject[i]; 
    console.log("Service Type: " + currentRequest["ServiceType"]); 
    if (currentRequest["ServiceType"] === "Conversion") { 
      console.log("Urls: "); 
      currentRequest["urls"].forEach((url) => { 
        console.log(url); 
      }); 
    } 
  } 
} 

Finally, create the function getRequestOptions(url) to provide header and authorization to the axios.post connections in order to request the GUID and JSON data through. Where it states Replace with Application ID and Replace with Application Password be sure to place your Application ID and Password accordingly.

function getRequestOptions(url) { 
  const appId = "Replace with Application ID"; 
  const password = "Replace with Application Password"; 
 
  const token = Buffer.from(`${appId}:${password}`, "utf8").toString("base64"); 
  //Function to generate and return HTTP request  options. 
  const requestOptions = { 
    url: url, 
    data: {}, 
    //If uploading a file as multi-part content, remove the Content-Length header. 
    headers: { 
      "Content-Length": 0, 
      Authorization: `Basic ${token}`, 
    }, 
  }; 
  return requestOptions; 
} 

Run the Project

Run the project by pressing Ctrl + F5, or by selecting Debug -> Start Without Debugging.

If the steps were followed correctly, the console appears and the application displays the parsed check information from the returned JSON data.

Merged File Information

Wrap-up

This tutorial showed how to merge files via the LEADTOOLS Cloud Services API.

See Also

Help Version 21.0.2023.3.1
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2021 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2021 LEAD Technologies, Inc. All Rights Reserved.