USING IRONWORD

How to Convert Word to PDF in C#

Converting documents programmatically has become an essential feature in many applications. Especially in the business world, converting Word documents to PDF files is a routine task. Thankfully, with C# and Microsoft Interop, you can seamlessly convert Word files to PDF. This tutorial will discuss the process of converting Word to PDF programmatically using C#.

Prerequisites

Before diving into the code to convert .DOCX to PDF using C#, ensuring you have the necessary environment set up is crucial. Below are the prerequisites you need:

Microsoft Word Installation

Make sure you have Microsoft Word installed on your computer. The Interop services will use Word's built-in capabilities to handle the Word document and PDF conversion.

Visual Studio

A version of Visual Studio is necessary for creating, compiling, and running the C# program. If you don't already have Visual Studio, you can download the community version, which is free, from Microsoft's official website.

Install package Microsoft.Office.Interop.Word

This package is essential to provide the necessary functionalities for your C# program to interact with Word documents. It will be installed later using NuGet Package Manager, but knowing its importance in the conversion process is good.

Word Document for Conversion

Prepare a Word document or .docx file that you'd like to convert. Ensure you know its path on your machine, as you'll need to specify it in the C# program.

Sufficient Permissions

Ensure you can read the Word file and write the resulting PDF file to the desired directory. Running Visual Studio as an administrator can sometimes resolve permission-related issues.

With these prerequisites, you can set up your environment and convert your Word documents to PDF files.

Setting Up the Environment

  1. Open your Visual Studio.
  2. Create a new C# Console Application.
  3. Go to NuGet Package Manager > Manage NuGet Packages for Solution.
  4. Search for "Microsoft.Office.Interop.Word" and install it. This package will allow our application to communicate with Word and convert Word files.

 related to Setting Up the Environment

Sample Code to Convert Word Document to PDF

To convert a Word document to PDF using C#, we will employ the capabilities of Microsoft Interop services. The code snippet below accomplishes this task, and a detailed explanation follows.

using System;
using Word = Microsoft.Office.Interop.Word;

class Program
{
    static void Main()
    {
        // Create an instance of Microsoft Word application
        var wordApp = new Word.Application();

        // Open the Word document
        var wordDocument = wordApp.Documents.Open(@"path_to_your_word_file.docx");

        // Specify the path where the PDF should be saved
        var outputPath = @"path_where_you_want_to_save_pdf.pdf";

        // Convert the Word document to PDF
        wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF);

        // Close the Word document and quit the Word application
        wordDocument.Close();
        wordApp.Quit();

        // Output a success message
        Console.WriteLine("Word document converted to PDF successfully!");
    }
}
using System;
using Word = Microsoft.Office.Interop.Word;

class Program
{
    static void Main()
    {
        // Create an instance of Microsoft Word application
        var wordApp = new Word.Application();

        // Open the Word document
        var wordDocument = wordApp.Documents.Open(@"path_to_your_word_file.docx");

        // Specify the path where the PDF should be saved
        var outputPath = @"path_where_you_want_to_save_pdf.pdf";

        // Convert the Word document to PDF
        wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF);

        // Close the Word document and quit the Word application
        wordDocument.Close();
        wordApp.Quit();

        // Output a success message
        Console.WriteLine("Word document converted to PDF successfully!");
    }
}
Imports System
Imports Word = Microsoft.Office.Interop.Word

Friend Class Program
	Shared Sub Main()
		' Create an instance of Microsoft Word application
		Dim wordApp = New Word.Application()

		' Open the Word document
		Dim wordDocument = wordApp.Documents.Open("path_to_your_word_file.docx")

		' Specify the path where the PDF should be saved
		Dim outputPath = "path_where_you_want_to_save_pdf.pdf"

		' Convert the Word document to PDF
		wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF)

		' Close the Word document and quit the Word application
		wordDocument.Close()
		wordApp.Quit()

		' Output a success message
		Console.WriteLine("Word document converted to PDF successfully!")
	End Sub
End Class
$vbLabelText   $csharpLabel

Code Explanation

The beginning of our code includes a crucial namespace alias Word to refer to the Microsoft.Office.Interop.Word namespace easily. The System namespace provides classes fundamental to C# programming, and it's a staple in almost all C# applications.

The real action begins inside the Main method. We first create a new instance of the Word application using new Word.Application(). This step is akin to launching MS Word, but everything happens in the background, unseen by the user. Once the application instance is initialized, we instruct it to open a Word document with the wordApp.Documents.Open method. Specifying the path to your Word document in place of "path_to_your_word_file.docx" is crucial.

Now, having the document open, we determine where we want our PDF to be saved. This is specified in the outputPath variable. It's essential to note that the path should be adjusted to where you'd like your converted output PDF file to reside.

The magic of converting the Word document to PDF happens with the line wordDocument.ExportAsFixedFormat(...). The Interop services provide a built-in method, enabling the conversion without hassle. The method takes two primary arguments: the path where the PDF should be saved and the export format, which in our case is PDF.

Following the conversion, closing resources we've used is good practice. Thus, wordDocument.Close() ensures that the document we opened is now closed, while wordApp.Quit() ensures that the instance of the Word application we launched in the background is terminated.

Lastly, our program communicates the result to the user with a simple console message. The Console.WriteLine() method provides feedback, signaling that the conversion process was successfully executed.

Thus, Microsoft.Office.Interop.Word provides a suitable solution to handle and convert Word documents.

Introducing IronXL: A Superior Alternative to Interop

While Microsoft.Office.Interop provides a feasible solution for document conversion, there's a more efficient and robust alternative available to work with Excels: IronXL.

IronXL simplifies the process of handling Excel files in C#. Not only does it outperform Interop in terms of speed and ease of use, but it also requires no additional installations like Microsoft Office. Interested in exploring further? Check out their detailed tutorial on how to read Excel files using C#.

IronXL library can be installed using the following command in the NuGet Package Manager console:

Install-Package IronWord

How to Convert Word to PDF in C#: Figure 2 - IronXL for .Net: The C# Excel Library

Convert Spreadsheet File Types

using IronXL;

class ExcelConverter
{
    static void Main()
    {
        // Load an Excel file into an IronXL WorkBook object
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Export the Excel file in various formats
        workBook.SaveAs("sample.xls");
        workBook.SaveAs("sample.xlsx");
        workBook.SaveAs("sample.tsv");
        workBook.SaveAsCsv("sample.csv");
        workBook.SaveAsJson("sample.json");
        workBook.SaveAsXml("sample.xml");

        // Export the Excel file as HTML
        workBook.ExportToHtml("sample.html");
        string htmlString = workBook.ExportToHtmlString();

        // Export the Excel file as Binary, Byte array, Data set, Stream
        byte[] binary = workBook.ToBinary();
        byte[] byteArray = workBook.ToByteArray();
        System.Data.DataSet dataSet = workBook.ToDataSet(); // Allow easy integration with DataGrids, SQL and EF
        Stream stream = workBook.ToStream();
    }
}
using IronXL;

class ExcelConverter
{
    static void Main()
    {
        // Load an Excel file into an IronXL WorkBook object
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Export the Excel file in various formats
        workBook.SaveAs("sample.xls");
        workBook.SaveAs("sample.xlsx");
        workBook.SaveAs("sample.tsv");
        workBook.SaveAsCsv("sample.csv");
        workBook.SaveAsJson("sample.json");
        workBook.SaveAsXml("sample.xml");

        // Export the Excel file as HTML
        workBook.ExportToHtml("sample.html");
        string htmlString = workBook.ExportToHtmlString();

        // Export the Excel file as Binary, Byte array, Data set, Stream
        byte[] binary = workBook.ToBinary();
        byte[] byteArray = workBook.ToByteArray();
        System.Data.DataSet dataSet = workBook.ToDataSet(); // Allow easy integration with DataGrids, SQL and EF
        Stream stream = workBook.ToStream();
    }
}
Imports IronXL

Friend Class ExcelConverter
	Shared Sub Main()
		' Load an Excel file into an IronXL WorkBook object
		Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")

		' Export the Excel file in various formats
		workBook.SaveAs("sample.xls")
		workBook.SaveAs("sample.xlsx")
		workBook.SaveAs("sample.tsv")
		workBook.SaveAsCsv("sample.csv")
		workBook.SaveAsJson("sample.json")
		workBook.SaveAsXml("sample.xml")

		' Export the Excel file as HTML
		workBook.ExportToHtml("sample.html")
		Dim htmlString As String = workBook.ExportToHtmlString()

		' Export the Excel file as Binary, Byte array, Data set, Stream
		Dim binary() As Byte = workBook.ToBinary()
		Dim byteArray() As Byte = workBook.ToByteArray()
		Dim dataSet As System.Data.DataSet = workBook.ToDataSet() ' Allow easy integration with DataGrids, SQL and EF
		Dim stream As Stream = workBook.ToStream()
	End Sub
End Class
$vbLabelText   $csharpLabel

As shown in the above sample code, the IronXL library helps to read Excel files without using Interop. You can further use the IronXL library to load your workbook and export it with SaveAs method to different formats such as XLS, XLSX, XLSM, CSV, TSV, JSON, XML. It also allows for the export of data types like HTML strings, binaries, byte arrays, data sets, and memory streams directly in code.

Conclusion

In today's digital era, document conversions, especially Word documents to PDF, have become indispensable for many applications. One can achieve this using C# and the capabilities provided by Microsoft Interop.

However, staying updated with superior tools like IronXL is essential, which offers enhanced performance and simplifies the process. If you're considering trying out IronXL, they offer a free trial. Once you've experienced its prowess, the licensing starts from a reasonable $749, providing value for your investment and ensuring smooth document handling in your applications.

Frequently Asked Questions

What are the prerequisites for converting documents to PDF using C#?

You need Microsoft Word installed, Visual Studio, the Microsoft.Office.Interop.Word package, a Word document for conversion, and sufficient permissions for reading and writing files.

How do you set up the environment for document conversion in C#?

Open Visual Studio, create a new C# Console Application, install the Microsoft.Office.Interop.Word package via NuGet Package Manager, and prepare your Word document for conversion.

Can you provide a sample code to convert a document to PDF using C#?

Yes, the sample code involves creating a Word application instance, opening a Word document, specifying the PDF output path, exporting the document to PDF, and then closing the application.

What is the role of Microsoft.Office.Interop.Word in the conversion process?

Microsoft.Office.Interop.Word provides the necessary functionalities to interact with Word documents and convert them to PDF programmatically within a C# application.

What is a superior alternative to Microsoft.Office.Interop for handling Excel files?

IronXL is a library that simplifies handling Excel files in C#. Unlike Interop, it doesn't require Microsoft Office installation and offers faster performance and ease of use.

How can I install the IronXL library?

You can install IronXL using the command Install-Package IronXL.Excel in the NuGet Package Manager console.

What file types can a library like IronXL convert Excel files into?

IronXL can convert Excel files into various formats including XLS, XLSX, XLSM, CSV, TSV, JSON, XML, HTML, and others like binary and byte arrays.

Why might a developer choose a library like IronXL over Interop services?

A developer might choose IronXL for its speed, ease of use, no requirement for Microsoft Office installation, and its ability to handle a wider range of file formats.

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
C# Edit Word (Code Example Developer Tutorial)
NEXT >
C# Open Word Document

Ready to get started? Version: 2025.6 just released

View Licenses >