Saltar al pie de página
USANDO IRONWORD

Cómo Convertir Word a PDF en 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.

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 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()
    {
        // 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.

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

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")
$vbLabelText   $csharpLabel

Output Word document

Word output

IronPDF

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")
$vbLabelText   $csharpLabel

PDF Output

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#

  1. Load or create a Word document with IronWord
  2. Edit or fill in dynamic data (e.g. replace tokens)
  3. Save the .docx file
  4. Use IronPDF to convert the document to PDF format
  5. 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")
$vbLabelText   $csharpLabel

Output

Word document 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")
$vbLabelText   $csharpLabel

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 Yes No
Replace text/tokens in Word Yes No
Save .docx documents Yes No
Convert HTML to PDF No Yes
Generate final PDF output No Yes
Server-side rendering Yes Yes

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>
$vbLabelText   $csharpLabel

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.

Preguntas Frecuentes

¿Cómo puedo convertir un documento de Word a PDF usando C#?

Puedes usar el paquete Microsoft.Office.Interop.Word para convertir documentos de Word a PDF en C#. Esto involucra crear una instancia de la aplicación Word, cargar el documento y usar el método ExportAsFixedFormat para guardarlo como un PDF.

¿Cuál es el papel del método ExportAsFixedFormat en la conversión de Word a PDF?

El método ExportAsFixedFormat en Microsoft.Office.Interop.Word se usa para exportar un documento de Word como un archivo PDF, proporcionando un formato fijo que es adecuado para compartir e imprimir.

¿Cuáles son los requisitos previos para convertir documentos de Word a PDF en C#?

Para convertir documentos de Word a PDF en C#, necesitas tener Microsoft Word instalado, Visual Studio y el paquete Microsoft.Office.Interop.Word disponible a través del Administrador de Paquetes NuGet.

¿Por qué es importante cerrar la aplicación de Word después de la conversión?

Cerrar la aplicación de Word después de la conversión es esencial para liberar recursos del sistema y evitar fugas de memoria. Asegura que la aplicación no permanezca abierta en segundo plano, consumiendo recursos innecesarios.

¿Cuál es una alternativa más eficiente para manejar archivos Excel que Microsoft Interop?

IronXL es una alternativa más eficiente para manejar archivos Excel en C#. No requiere que Microsoft Office esté instalado y proporciona un rendimiento más rápido con una amplia gama de formatos de archivo soportados.

¿Cómo instalo la biblioteca IronXL para usarla en mi aplicación C#?

Para instalar IronXL en tu aplicación C#, usa la consola del Administrador de Paquetes NuGet y ejecuta el comando Install-Package IronXL.Excel.

¿Qué formatos de archivo puede manejar IronXL al trabajar con archivos Excel?

IronXL puede convertir y manejar archivos Excel en varios formatos, incluidos XLS, XLSX, XLSM, CSV, TSV, JSON, XML, HTML, así como matrices binarias y de bytes.

¿Cuáles son las ventajas de usar IronXL sobre los servicios Microsoft Interop?

IronXL ofrece ventajas tales como no requerir la instalación de Microsoft Office, velocidades de procesamiento más rápidas, facilidad de uso y soporte para una gama más amplia de formatos de archivo en comparación con los servicios Microsoft Interop.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más