How to Convert Microsoft Word to PDF in .NET with C#

Learn how to Convert Microsoft Word to PDF in .NET with C# by Calling Convert to PDF API Tool by pdfRest.
Share this page

Why Convert Word to PDF with C#?

The pdfRest Convert to PDF API Tool is a powerful resource that allows developers to convert various file formats to PDF with ease. By integrating this API into a C# application, you can automate the process of converting documents such as Word, Excel, HTML, or images to PDF format.

This can be particularly useful in scenarios such as generating reports, archiving documents, or preparing files for printing or sharing, where you need to ensure consistency and compatibility across different platforms and devices.

Convert Word to PDF with C# Code Example

using System.Text;

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
{
    using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf"))
    {
        request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
        request.Headers.Accept.Add(new("application/json"));
        var multipartContent = new MultipartFormDataContent();

        var byteArray = File.ReadAllBytes("/path/to/file");
        var byteAryContent = new ByteArrayContent(byteArray);
        multipartContent.Add(byteAryContent, "file", "file_name.docx");
        byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "text/html");

        var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("lossless"));
        multipartContent.Add(byteArrayOption, "compression");

        var byteArrayOption2 = new ByteArrayContent(Encoding.UTF8.GetBytes("output.pdf"));
        multipartContent.Add(byteArrayOption2, "output");
        request.Content = multipartContent;
        var response = await httpClient.SendAsync(request);

        var apiResult = await response.Content.ReadAsStringAsync();

        Console.WriteLine("API response received.");
        Console.WriteLine(apiResult);
    }
}

Source: pdfRest API Samples on GitHub

Breaking Down the Code

The provided code snippet is a C# example of how to make a multipart/form-data POST request to the pdfRest API to convert a file to PDF.

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
{
    // ...
}

This initializes an instance of HttpClient with the base address set to the pdfRest API endpoint.

using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf"))
{
    // ...
}

A new HttpRequestMessage is created with the HTTP POST method targeting the "pdf" endpoint.

request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

The API key is added to the request headers. Replace "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" with your actual API key.

var multipartContent = new MultipartFormDataContent();

A MultipartFormDataContent object is created to hold the form data.

var byteArray = File.ReadAllBytes("/path/to/file");
var byteAryContent = new ByteArrayContent(byteArray);
multipartContent.Add(byteAryContent, "file", "file_name");
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "text/html");

The file to be converted is read into a byte array, wrapped in a ByteArrayContent, and added to the multipart form data with the appropriate content type header.

var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("lossless"));
multipartContent.Add(byteArrayOption, "compression");

An additional form field is added for the "compression" option, specifying the desired image compression option for the output PDF.

var byteArrayOption2 = new ByteArrayContent(Encoding.UTF8.GetBytes("output.pdf"));
multipartContent.Add(byteArrayOption2, "output");

Another form field is added for the "output" option, specifying the desired output file name.

var response = await httpClient.SendAsync(request);

The request is sent asynchronously, and the response is awaited.

var apiResult = await response.Content.ReadAsStringAsync();

The response content is read as a string, which contains the result of the API call.

Beyond the Tutorial

In this tutorial, we've walked through how to use C# to make an API call to the pdfRest Convert to PDF API endpoint using multipart form data. This example demonstrates how to convert a file to PDF format and retrieve the result programmatically.

I encourage you to demo all of the pdfRest API Tools in the API Lab at https://pdfrest.com/apilab/ and refer to the API Reference documentation at https://pdfrest.com/documentation/ for further exploration.

Note that this is an example of a multipart API call. Code samples using JSON payloads can be found at pdfRest API Samples on GitHub.

Generate a self-service API Key now!

Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.

Compare Plans
Contact Us