USING IRONWORD

How to Convert Word to PDF in C#

Updated November 14, 2023
Share:

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.

How to Convert Word to PDF in C#: Figure 1 - Open Visual Studio and create a new Console App project. Go to NuGet Package Manager > Manage Packages for Solution. Search for Microsoft.Office.Interop.Word and install it. This package will help our console application to interact with Word and also convert Word files.

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()
    {
        var wordApp = new Word.Application();
        var wordDocument = wordApp.Documents.Open(@"path_to_your_word_file.docx");

        var outputPath = @"path_where_you_want_to_save_pdf.pdf";
        wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF);

        wordDocument.Close();
        wordApp.Quit();

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

class Program
{
    static void Main()
    {
        var wordApp = new Word.Application();
        var wordDocument = wordApp.Documents.Open(@"path_to_your_word_file.docx");

        var outputPath = @"path_where_you_want_to_save_pdf.pdf";
        wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF);

        wordDocument.Close();
        wordApp.Quit();

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

Friend Class Program
	Shared Sub Main()
		Dim wordApp = New Word.Application()
		Dim wordDocument = wordApp.Documents.Open("path_to_your_word_file.docx")

		Dim outputPath = "path_where_you_want_to_save_pdf.pdf"
		wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF)

		wordDocument.Close()
		wordApp.Quit()

		Console.WriteLine("Word document converted to PDF successfully!")
	End Sub
End Class
VB   C#

Code Explanation

The beginning of our code includes two vital namespaces. The System namespace provides classes fundamental to C# programming, and it's a staple in almost all C#

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 output path 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;
using System.IO;

// Import any XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Export the excel file as XLS, XLSX, XLSM, CSV, TSV, JSON, XML
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, Html string
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;
using System.IO;

// Import any XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Export the excel file as XLS, XLSX, XLSM, CSV, TSV, JSON, XML
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, Html string
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
Imports System.IO

' Import any XLSX, XLS, XLSM, XLTX, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Export the excel file as XLS, XLSX, XLSM, CSV, TSV, JSON, XML
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, Html string
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()
VB   C#

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 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 $599, providing value for your investment and ensuring smooth document handling in your applications.

< PREVIOUS
C# Edit Word (Code Example Developer Tutorial)
NEXT >
C# Open Word Document

Ready to get started? Version: 2024.5 just released

Start Free Trial Total downloads: 1,570
View Licenses >