How to convert Word DOCX to PDF using C# in .NET Framework

Word documents offer a variety of useful features such as text formatting and tables, but are incredibly awkward to work with outside of a word processor. This notoriously incompatible file format does not play well with the web, and may not even display properly on differing versions of Word. The easy solution to this problem is to convert your DOCX file into a PDF and dodge all these potential issues. Let’s look at how to keep this process as simple as possible.

First, we need to install our API client by entering the following command into the console of Package Manager:

Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 1.3.4

Next we call ConvertDocumentAutodetectToPdf:

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");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");
var apiInstance = new ConvertDocumentApi();
var inputFile = new System.IO.Stream(); // 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 );
}
}
}
}

And that’s it! This function can automatically detect the file format of the input file, and is compatible with a variety of different formats including XLSX, legacy DOC, and over 100 image formats.

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store