How to Convert Common Documents to PDF using C# .NET Framework
Coding a workflow to convert one document — let alone dozens of unique document formats — to PDF format can take up a significant chunk of time.
Thankfully, using the below code, we can take advantage of a free API to handle those conversions for us. We can use this API to convert all major Office formats (Word, Excel, PowerPoint), 100+ unique image formats (including JPG, PNG, etc.), html files, text files, and even multi-page TIFF files. The underlying service will automatically detect the input file type before making the conversion, so we don’t have to worry about specifying our file type ahead of time.
To structure our API call, we can begin by installing the SDK. Let’s take care of that by running the below command in our Package Manager console (to install via NuGet):
Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.4.2
Next, let’s prepare to authorize our API calls by obtaining a free-tier API key. These will allow a limit of 800 API calls per month with no commitments.
Finally, let’s include the below code in our file to call the function. We can make our request with multipart/form-data:
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;
namespace Example
{
public class ConvertDocumentAutodetectToPdfExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
var apiInstance = new ConvertDocumentApi();
var inputFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Input file to perform the operation on.
try
{
// Convert Document to PDF
byte[] result = apiInstance.ConvertDocumentAutodetectToPdf(inputFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDocumentApi.ConvertDocumentAutodetectToPdf: " + e.Message );
}
}
}
}
That’s all there is to it — now we can easily convert a variety of documents to PDF with a single, low-code solution.