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
- Open your Visual Studio.
- Create a new C# Console Application.
- Go to NuGet Package Manager > Manage NuGet Packages for Solution.
- Search for "
Microsoft.Office.Interop.Word
" and install it. This package will allow our application to communicate with Word and 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()
{
// 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
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.
Word to PDF C# Using IronPDF and IronWord
If you're building a .NET application that involves document automation, one common task you'll face is converting Word documents to PDF format. Whether you're working with .docx document templates, invoices, reports, or contracts, converting DOCX files to PDF ensures consistent formatting, secure delivery, and cross-platform compatibility.
This article explains how to easily convert Word to PDF using two powerful tools from IronSoftware: IronPDF and IronWord. You'll learn how they differ, when to use each tool, and how to implement them in C# for fast, reliable Word to PDF generation.
Why Convert Word to PDF in .NET?
Before we dive into how you can use these libraries to achieve this task, let's first take a look at why exactly converting your Word documents to PDF can elevate your workspace and documents.
So why should you convert DOCX files to PDF format?
- It ensures visual consistency across various platforms
- Locks formatting and prevents unintentional edits
- It's ideal for archiving legal or financial documents
- It makes it easier to print and share your files
- It is often the required format for many business workflows
Overview of the Tools: IronPDF and IronWord
IronWord
IronWord is a .NET library purpose-built for reading and editing Word documents. With IronWord, you can load .docx documents directly edit them to fit your needs, no need for Microsoft Office Interop or Microsoft Word installations, before using IronPDF to handle the DOCX to PDF conversion.
Let's now take a look at IronWord in action, by creating a new document object and adding text to it:
using IronWord;
using IronWord.Models;
using IronWord.Models.Abstract;
WordDocument doc = new WordDocument();
TextContent text = new TextContent("This is some example text.");
text.Style = new TextStyle()
{
Color = Color.Red,
TextFont = new Font()
{
FontFamily = "Roboto",
FontSize = 72,
}
};
doc.AddText(text);
doc.Save("example.docx");
using IronWord;
using IronWord.Models;
using IronWord.Models.Abstract;
WordDocument doc = new WordDocument();
TextContent text = new TextContent("This is some example text.");
text.Style = new TextStyle()
{
Color = Color.Red,
TextFont = new Font()
{
FontFamily = "Roboto",
FontSize = 72,
}
};
doc.AddText(text);
doc.Save("example.docx");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Abstract
Private doc As New WordDocument()
Private text As New TextContent("This is some example text.")
text.Style = New TextStyle() With {
.Color = Color.Red,
.TextFont = New Font() With {
.FontFamily = "Roboto",
.FontSize = 72
}
}
doc.AddText(text)
doc.Save("example.docx")
Output Word document
IronPDF
IronPDF is a full-featured PDF library for .NET, packed full of tools for PDF generation and manipulation. While one of it's crowning features is its high-quality HTML to PDF conversion capabilities, it is also capable of handling Word to PDF C# conversion tasks. For .NET developers looking to generate PDFs or edit existing PDF documents, IronPDF has you covered for all your needs.
So just how easy is IronPDF to use? Let's look at the following code example to see how it works when converting Word documents to PDF:
using IronPdf;
var renderer = new DocxToPdfRenderer();
var pdf = renderer.RenderDocxAsPdf("sample.docx");
pdf.SaveAs("example.pdf");
using IronPdf;
var renderer = new DocxToPdfRenderer();
var pdf = renderer.RenderDocxAsPdf("sample.docx");
pdf.SaveAs("example.pdf");
Imports IronPdf
Private renderer = New DocxToPdfRenderer()
Private pdf = renderer.RenderDocxAsPdf("sample.docx")
pdf.SaveAs("example.pdf")
PDF Output
Combined Workflow: IronWord and IronPDF
While IronWord cannot directly export to PDF, it's perfect for preparing Word documents programmatically. Here's a common flow:
Word to PDF Pipeline in C#
- Load or create a Word document with IronWord
- Edit or fill in dynamic data (e.g. replace tokens)
- Save the .docx file
- Use IronPDF to convert the document to PDF format
- After, you can go on to use IronPDF to make any further adjustments to the newly rendered PDF, such as adding watermarks or annotations
This hybrid workflow offers maximum flexibility with minimal dependencies, ideal for web apps, cloud services, and desktop applications alike.
So how does this look in action?
Using IronWord for Document Creation
First we'll use IronWord to create an example Word document.
using IronWord;
using IronWord.Models;
using IronWord.Models.Abstract;
WordDocument doc = new WordDocument();
TextContent title = new TextContent("Example Report.");
TextContent text = new TextContent("Report created using IronWord, you can use this to create dynamic text and tables.");
title.Style = new TextStyle()
{
TextFont = new Font()
{
FontSize = 72
},
IsBold = true,
};
Paragraph paragraph = new Paragraph();
paragraph.AddText(title);
paragraph.AddText(text);
doc.AddParagraph(paragraph);
doc.Save("example.docx");
using IronWord;
using IronWord.Models;
using IronWord.Models.Abstract;
WordDocument doc = new WordDocument();
TextContent title = new TextContent("Example Report.");
TextContent text = new TextContent("Report created using IronWord, you can use this to create dynamic text and tables.");
title.Style = new TextStyle()
{
TextFont = new Font()
{
FontSize = 72
},
IsBold = true,
};
Paragraph paragraph = new Paragraph();
paragraph.AddText(title);
paragraph.AddText(text);
doc.AddParagraph(paragraph);
doc.Save("example.docx");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Abstract
Private doc As New WordDocument()
Private title As New TextContent("Example Report.")
Private text As New TextContent("Report created using IronWord, you can use this to create dynamic text and tables.")
title.Style = New TextStyle() With {
.TextFont = New Font() With {.FontSize = 72},
.IsBold = True
}
Dim paragraph As New Paragraph()
paragraph.AddText(title)
paragraph.AddText(text)
doc.AddParagraph(paragraph)
doc.Save("example.docx")
Output
Using IronPDF for Word to PDF C# Conversion
In just 3 simple lines of code, we'll be able to easily convert our Word document to PDF.
using IronPdf;
var renderer = new DocxToPdfRenderer();
var pdf = renderer.RenderDocxAsPdf("example.docx");
pdf.SaveAs("output.pdf");
using IronPdf;
var renderer = new DocxToPdfRenderer();
var pdf = renderer.RenderDocxAsPdf("example.docx");
pdf.SaveAs("output.pdf");
Imports IronPdf
Private renderer = New DocxToPdfRenderer()
Private pdf = renderer.RenderDocxAsPdf("example.docx")
pdf.SaveAs("output.pdf")
Output
Just like that, we were able to create a custom Word document with IronWord, before implementing IronPDF to convert it to PDF format in just a few lines of code.
Deployment-Ready: Works Everywhere
Both IronPDF and IronWord works in:
- ASP.NET Core and Blazor
- Azure App Services and Azure Functions
- Compatible with .NET framework, .NET 6, 7, 8, 9, and .NET Core
- Easily integrated into Linux, Docker, and server environments
- Desktop (WPF/WinForms) and console applications
No Office install required. No COM interop. Just clean, modern .NET libraries.
Common Use Cases
Use Case | IronWord | IronPDF |
---|---|---|
Load/edit .docx files | ✅ | ❌ |
Replace text/tokens in Word | ✅ | ❌ |
Save .docx documents | ✅ | ❌ |
Convert HTML to PDF | ❌ | ✅ |
Generate final PDF output | ❌ | ✅ |
Server-side rendering | ✅ | ✅ |
Pro Tip: Using Razor Views to Output Word-Like PDF documents
Even if you're not using IronWord, IronPDF supports Razor templates directly. You can use Razor Pages to output Word-styled layouts with CSS, then render to PDF:
@model InvoiceModel
<html>
<body>
<h1>Invoice for @Model.CustomerName</h1>
<p>Amount Due: @Model.TotalAmount</p>
</body>
</html>
@model InvoiceModel
<html>
<body>
<h1>Invoice for @Model.CustomerName</h1>
<p>Amount Due: @Model.TotalAmount</p>
</body>
</html>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@model InvoiceModel <html> <body> <h1> Invoice for @Model.CustomerName</h1> <p> Amount Due: @Model.TotalAmount</p> </body> </html>
IronPDF can render that into a polished, print-ready PDF.
Summary: Unlock the Full Power of Word to PDF in .NET
By including IronPDF and IronWord in your .NET projects, you get a powerful, Office-free workflow for handling documents in .NET. Create dynamic Word documents with custom styling and tables, or convert your documents into pixel-perfect PDF files. No matter the task, with these libraries you'll always have powerful tools for handling Word and PDF tasks at your fingertips.
This pairing is perfect for generating invoices, reports, contracts, and any document that starts in Word but needs to end in a secure, consistent PDF format.
Whether you're building desktop software or deploying to Azure, IronWord and IronPDF give you full control over document automation - fast, reliable, and production-ready. If you want to see more of these libraries in action, be sure to check out their documentation, where you can find plenty of code examples for both IronPDF and IronWord to learn more about their features and how they work.
Get Started Today
Install both libraries via the NuGet Package Manager to quickly implement them within your Visual Studio projects. Want to try before you buy? Download the free trial for IronPDF and IronWord today and start creating powerful documents right away.
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.