Generate PDF by Merging Different File Formats into PDF in C#

In this article, you will see how to use PDF.CO Web API in C# to merge multiple files into a single PDF document.

Merging multiple files into a single PDF document is an important task. For instance, while applying for a job, the HR manager might ask you to send your CV, motivation letter, experience letters, etc, merged as a single PDF document.

This article consists of two parts.

  1. In the first part, you will see how to merge multiple PDF documents into a single PDF file using the PDF.CO Web API in C#.
  2. In the second part, you will see how to merge different file formats documents into a single PDF document.

Merge Multiple PDF Files into a Single PDF Document

For demonstration purposes, you will be creating a C# console application that shows how to merge multiple PDF files into a single PDF document. Merging and splitting PDF files is just one of the many functionalities PDF.co has to offer.

Steps

You will need to import the following libraries to run the script in this section:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

All the above libraries come preinstalled with the .NET framework. However, you will need to install the “Newtonsoft” library.

To do so, from the Microsoft Visual Studio IDE, go to “Tools-> NuGet Package Manager”, then search for the “Newtonsoft” library. You will see the following packages. Select the first package and click the “Install” button.

Newtonsoft.JSON

Next, inside the main C# class, you need to declare three variables that store your PDF.CO API key, a list of input PDF files to be merged, and the destination path for the merged file.

Note: You can get your API key by registering at https://app.pdf.co

The following script defines these three variables:

const String API_KEY = "*********************************************************";

static string[] SourceFiles = {
      "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample1.pdf",
      "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample2.pdf" };

const string DestinationFile = @".\output.pdf";

If you go to the links for the input source files, you will see the following two files:

File 1
File 1
File 2
File 2

The rest of the code snippets should execute inside the “Main” method of your C# console application.

The following script creates an object of the standard .NET WebClient class that is used to call Web APIs in .NET.

You need to pass your PDF.CO API key to the WebClient object’s header as shown in the script below:

WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);

Next, you need to define the URL to the API call that merges pdf documents using the PDF.CO web API. The API call is as follows:

string url = "https://api.pdf.co/v1/pdf/merge";

The next step is to create a parameter dictionary that contains the destination file names, and comma-separated source file names.

The parameter dictionary is serialized before being uploaded via the WebClient class object.

Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("name", Path.GetFileName(DestinationFile));
parameters.Add("url", string.Join(",", SourceFiles));
string jsonPayload = JsonConvert.SerializeObject(parameters);

Finally, you can execute the API call via the WebClient class object by passing it the API URL, and the parameter dictionary in the form of a JSON payload.

The response can be parsed as a JSON object. If the response doesn’t contain any error, it means that the source files are successfully merged. The response object will contain the URL of the merged document which you can print on the console, and can also download.

In case the JSON response contains an error, you can catch the error inside Try/Catch block and print its error message.

The aforementioned steps are performed in the following code:

try
   {           
     string response = webClient.UploadString(url, jsonPayload);
JObject json = JObject.Parse(response);
     if (json["error"].ToObject<bool>() == false)
           {                   
           string resultFileUrl = json["url"].ToString();
           Console.WriteLine(resultFileUrl);
           webClient.DownloadFile(resultFileUrl, DestinationFile);
           Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
           }
     else
           {
Console.WriteLine(json["message"].ToString());
           }
   }
   catch (WebException e)
   {
           Console.WriteLine(e.ToString());
   }

Finally, you can destroy your WebClient object and wait for the user to press any key before the console application is closed:

webClient.Dispose();

Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();

The complete code for merging two PDF files into a single PDF file using the PDF.CO Web API in C# is as follows:

Complete Code

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ByteScoutWebApiExample
{
class Program
{

const String API_KEY = "usmanmalik57@gmail.com_8df5671cedb0fb37ec9610eada409f110c38";
static string[] SourceFiles = {
"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample1.pdf",
"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample2.pdf" };

const string DestinationFile = @".\output.pdf";

static void Main(string[] args)
{

WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);

string url = "https://api.pdf.co/v1/pdf/merge";

Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("name", Path.GetFileName(DestinationFile));
parameters.Add("url", string.Join(",", SourceFiles));
string jsonPayload = JsonConvert.SerializeObject(parameters);

try
{

string response = webClient.UploadString(url, jsonPayload);

JObject json = JObject.Parse(response);

if (json["error"].ToObject<bool>() == false)
{

string resultFileUrl = json["url"].ToString();

Console.WriteLine(resultFileUrl);

webClient.DownloadFile(resultFileUrl, DestinationFile);

Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}

webClient.Dispose();

Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}

Output

Output

From the output, you can see the URL to the merged file. You can go to this URL and download the merged file. Or you can directly access the downloaded “output.pdf” file that contains your merged PDF documents.

Merge Different Format Files into a Single PDF Document

The process of merging multiple files in various formats into a single PDF document is very similar to merging multiple PDF files. All you have to do is replace the PDF.CO Web API call.

Let’s see an example. Here are 2 documents we will merge:

Input 1
Input 2

Steps

The script below imports the required C# packages.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

You will need to install the Newtonsoft package if you have not already installed it.

Next, you need to create variables for your PDF.CO API Key for the source files that are to be merged, and for the destination merged file:

The following script does that:

const String API_KEY = "************************************";

      static string[] SourceFiles = {
                 "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample1.pdf",
                 "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/doc-to-pdf/sample.docx"
                 };

const string DestinationFile = @".\output2.pdf";

From the above script, you can see that you will be merging a PDF file with an MS Word Docx file.

The rest of the script should be run inside the “Main” method of your console application.

As you did previously, you need to create an object of the WebClient class that you will use to execute your POST request to the PDF.CO Web API. The following script does that:

WebClient webClient = new WebClient();
webClient.Headers.Add("x-api-key", API_KEY);

The next step is to define the API call. This is where the difference lies between merging multiple PDF files and merging files of different formats. The API call, in this case, will be “merge2”. The complete link to the API call is defined in the script below:

string url = "https://api.pdf.co/v1/pdf/merge2";

The rest of the process is similar to what you have already seen.

You need to define a parameter dictionary that contains the source file links and the name of the merged destination file. The parameter dictionary is then serialized as a JSON object.

Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("name", Path.GetFileName(DestinationFile));
parameters.Add("url", string.Join(",", SourceFiles));
string jsonPayload = JsonConvert.SerializeObject(parameters);

Finally, inside the Try/Catch block, you have to execute the POST call to the PDF.CO web API using the WebClient class object.

The response is then parsed as a JSON object. If the response doesn’t contain any error, the URL of the destination merged file is printed on the console and the file is downloaded.

In case there is an error in response, the catch block executes and the error is printed on the console.

Look at the following script for reference:

try
            {
            
                 string response = webClient.UploadString(url, jsonPayload);

                 JObject json = JObject.Parse(response);

                 if (json["error"].ToObject<bool>() == false)
                 {
                       
                       string resultFileUrl = json["url"].ToString();

                       Console.WriteLine(resultFileUrl);

                       webClient.DownloadFile(resultFileUrl, DestinationFile);

                       Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
                 }
                 else
                 {
                       Console.WriteLine(json["message"].ToString());
                 }
            }
            catch (WebException e)
            {
                 Console.WriteLine(e.ToString());
            }

            webClient.Dispose();

            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadKey();

Here is the complete code for merging multiple documents of different formats into a single PDF document:

Complete Code

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ByteScoutWebApiExample
{
    class Program
    {

      const String API_KEY = "usmanmalik57@gmail.com_8df5671cedb0fb37ec9610eada409f110c38";

      static string[] SourceFiles = {
                 "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample1.pdf",
                 "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/doc-to-pdf/sample.docx"
                 };

      const string DestinationFile = @".\output2.pdf";

      static void Main(string[] args)
      {
    
            WebClient webClient = new WebClient();
            webClient.Headers.Add("x-api-key", API_KEY);

            string url = "https://api.pdf.co/v1/pdf/merge2";

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("name", Path.GetFileName(DestinationFile));
            parameters.Add("url", string.Join(",", SourceFiles));
            string jsonPayload = JsonConvert.SerializeObject(parameters);

            try
            {
            
                 string response = webClient.UploadString(url, jsonPayload);

                 JObject json = JObject.Parse(response);

                 if (json["error"].ToObject<bool>() == false)
                 {
                       
                       string resultFileUrl = json["url"].ToString();

                       Console.WriteLine(resultFileUrl);

                       webClient.DownloadFile(resultFileUrl, DestinationFile);

                       Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
                 }
                 else
                 {
                       Console.WriteLine(json["message"].ToString());
                 }
            }
            catch (WebException e)
            {
                 Console.WriteLine(e.ToString());
            }

            webClient.Dispose();
            
            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadKey();
      }
    }
}

Output – Merged PDF File

Output – Merged PDF File