Merge - C# .NET 6

This tutorial shows how to merge documents using the LEADTOOLS Cloud Services in a C# .NET 6 console application.

Summary This tutorial covers how to make Merge requests and process the results using the LEADTOOLS Cloud Services in a C# .NET 6 application..
Completion Time 30 minutes
Project Download tutorial project (3 KB)
Platform LEADTOOLS Cloud Services API
IDE Visual Studio 2022
Language C# .NET 6 or higher
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.

Application ID and Password

Create an Account with LEADTOOLS Hosted Cloud Services to obtain both Application ID and Password strings.

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 the LEADTOOLS Hosted Cloud Services page.

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

Create the Project and Add the Required Dependencies

In Visual Studio, create a new C# .NET 6 Console project, and add the following required NuGet package:

Add the Merge Code

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

In the Solution Explorer, open Program.cs. Add the following statements to the using block at the top.

// Using block at the top 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 
using System; 
using System.Collections.Generic; 
using System.Net; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using System.Text; 
using System.Threading.Tasks; 

Add the class enum FormatsEnum string variable called hostedServicesUrl and an async Task called Merge(). The Merge task utilizes the Merge API to upload 2 files, verify successful upload, and merges them. If successful, a unique identifier (GUID) will be returned and then a query using this GUID will be made.

private enum 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, 
private static string hostedServicesUrl = ""; 
public static async Task Merge() 
    var client = InitClient(); 
    string tiffUrl = ""; 
    string uploadUrl = string.Format("UploadFile?fileurl={0}&forMerge=true", tiffUrl); 
    //If uploading a file as multi-part content: 
    HttpContent byteContent = new ByteArrayContent(File.ReadAllBytes(@"path/to/file")); 
    byteContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") 
        Name = "attachment", 
        FileName = "file-name" 
    var formData = new MultipartFormDataContent(); 
    formData.Add(byteContent, "formFieldName"); 
    string uploadUrl = "UploadFile"; 
    var result = await client.PostAsync(uploadUrl, formData); 
    var result = await client.PostAsync(uploadUrl, null); 
    if (result.StatusCode != HttpStatusCode.OK) 
        Console.WriteLine("Upload failed with the following response: " + result.StatusCode); 
    string firstFileId = await result.Content.ReadAsStringAsync(); 
    Console.WriteLine("First File ID returned by the services: " + firstFileId); 
    if (!await CheckFileForVerification(firstFileId, client)) 
    string pdfUrl = ""; 
    uploadUrl = string.Format("UploadFile?fileurl={0}&forMerge=true", pdfUrl); 
    result = await client.PostAsync(uploadUrl, null); 
    if (result.StatusCode != HttpStatusCode.OK) 
        Console.WriteLine("Upload failed with the following response: " + result.StatusCode); 
    string secondFileid = await result.Content.ReadAsStringAsync(); 
    Console.WriteLine("Second File ID returned by the services: " + secondFileid); 
    if (!await CheckFileForVerification(secondFileid, client)) 
    if (!await MergeFiles(client, firstFileId, secondFileid)) 
        Console.WriteLine("Files failed to Merge"); 
    await Query(firstFileId, client); 

The Task Merge calls 2 additional Tasks, MergeFiles(HttpClient client, string firstFileId, string secondFileId) and CheckFileForVerification(string id, HttpClient client) and place these just below it. The MergeFiles tasks instructs the Cloud Services API to merge the 2 uploaded file IDs into 1. The CheckFileForVerification task confirms the file was successfully uploaded.

private static async Task<bool> MergeFiles(HttpClient client, string firstFileId, string secondFileId) 
    var mergeList = new List<MergeArgument>(); 
    mergeList.Add(new MergeFirstLast() 
        fileId = firstFileId, 
        firstPage = 1, 
        lastPage = -1 
    mergeList.Add(new MergePageArray() 
        fileId = secondFileId, 
        pages = new int[] { 5, 1, 2, 4, 2 } 
    //Final output format for the merged file 
    var outputFormat = FormatsEnum.Pdf; 
    var mergeUrl = string.Format("Conversion/Merge?format={0}", outputFormat); 
    var response = await client.PostAsync(mergeUrl, new StringContent(JsonConvert.SerializeObject(mergeList), Encoding.UTF8, "application/json")); 
    return response.StatusCode == HttpStatusCode.OK; 
private static async Task<bool> CheckFileForVerification(string id, HttpClient client) 
    string queryUrl = string.Format("Query?id={0}", id.ToString()); 
    var result = await client.PostAsync(queryUrl, null); 
    var returnedContent = await result.Content.ReadAsStringAsync(); 
    var returnedData = JObject.Parse(returnedContent); 
    var fileStatus = (int)returnedData.SelectToken("FileStatus"); 
    if (fileStatus == 123) 
        //The file is still being verified.  We will check every half a second to make sure that the file has been verified 
        await Task.Delay(500); 
        return await CheckFileForVerification(id, client); 
    if (fileStatus != 122) 
        Console.WriteLine($"File ${id} failed verification with File Status: ${fileStatus}"); 
        return false; 
    return true; 

Next, create an async Task called Query(string id, HttpClient client) that utilizes the GUID provided by the Merge task. If successful the response body will contain all the request data in JSON format.

private static async Task Query(string id, HttpClient client) 
    string queryUrl = string.Format("Query?id={0}", id.ToString()); 
    HttpResponseMessage result; 
    string returnedContent; 
    JObject returnedData; 
    int fileStatus; 
        result = await client.PostAsync(queryUrl, null); 
        returnedContent = await result.Content.ReadAsStringAsync(); 
        returnedData = JObject.Parse(returnedContent); 
        fileStatus = (int)returnedData.SelectToken("FileStatus")!; 
        //The file is still being processed -- we will sleep the current thread for 5 seconds before trying again. 
        await Task.Delay(5000); 
    } while (fileStatus == 100 || fileStatus == 123); 
    Console.WriteLine("File has finished processing with return code: " + returnedData.SelectToken("FileStatus")); 
    if ((int)returnedData.SelectToken("FileStatus")! != 200) 

Then, create the function ParseJson(string json) to process the returned JSON data.

private static void ParseJson(string json) 
    JArray requestArray = JArray.Parse(json); 
    foreach (var requestReturn in requestArray) 
        Console.WriteLine("Service Type: " + requestReturn.SelectToken("ServiceType")); 
        Console.WriteLine("Returned Data:"); 
        var UrlArray = JArray.Parse(requestReturn.SelectToken("urls")!.ToString()); 
        foreach (var obj in UrlArray) 

Finally, create the function InitClient() to create a client connection to request the GUID and JSON data through. Additionally, create the model classes, MergeArgument, MergeFirstLast : MergeArgument, and MergePageArray : MergeArgument below InitClient; these facilitate the MergeFiles task.

Where it states Replace with Application ID and Replace with Application Password be sure to place your Application ID and Password accordingly.

private static HttpClient InitClient() 
    string AppId = "Replace with Application ID"; 
    string Password = "Replace with Application Password"; 
    HttpClient client = new HttpClient(); 
    client.BaseAddress = new Uri(hostedServicesUrl); 
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    string authData = string.Format("{0}:{1}", AppId, Password); 
    string authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData)); 
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue); 
    return client; 
private class MergeArgument 
    public string fileId { get; set; } 
private class MergeFirstLast : MergeArgument 
    public int firstPage { get; set; } 
    public int lastPage { get; set; } 
private class MergePageArray : MergeArgument 
    public int[] pages { get; set; } 

Run the Project

In order to test run this code be sure to add Merge().GetAwaiter().GetResults(); to the static void Main section.

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

If the steps were followed correctly, the console appears and the application displays the link to the merged file from the returned JSON data.

Merged File Information


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

See Also

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

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